Initial work is done
parent
d965541c59
commit
f7347fbe67
@ -1,2 +1,3 @@
|
||||
key.json
|
||||
/nbproject/private/
|
||||
node_modules/
|
@ -1,366 +0,0 @@
|
||||
{
|
||||
"name": "nomoreacronyms",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"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/@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/@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/node": {
|
||||
"version": "18.15.11",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz",
|
||||
"integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q=="
|
||||
},
|
||||
"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/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/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/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/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/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/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
|
||||
},
|
||||
"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.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/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/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/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/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/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/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/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/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/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/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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,233 +0,0 @@
|
||||
# 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))
|
@ -1,191 +0,0 @@
|
||||
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.
|
@ -1,70 +0,0 @@
|
||||
<div align="center">
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
|
||||
</p>
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
|
||||
<a href="https://www.npmjs.com/package/@discordjs/builders"><img src="https://img.shields.io/npm/v/@discordjs/builders.svg?maxAge=3600" alt="npm version" /></a>
|
||||
<a href="https://www.npmjs.com/package/@discordjs/builders"><img src="https://img.shields.io/npm/dt/@discordjs/builders.svg?maxAge=3600" alt="npm downloads" /></a>
|
||||
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
|
||||
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=builders" alt="Code coverage" /></a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## 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
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@ -1,88 +0,0 @@
|
||||
{
|
||||
"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 <kingdgrizzle@gmail.com>",
|
||||
"Crawl <icrawltogo@gmail.com>",
|
||||
"Amish Shah <amishshah.2k@gmail.com>",
|
||||
"SpaceEEC <spaceeec@yahoo.com>",
|
||||
"Aura Román <kyradiscord@gmail.com>"
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
@ -1,128 +0,0 @@
|
||||
# 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))
|
@ -1,191 +0,0 @@
|
||||
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.
|
@ -1,67 +0,0 @@
|
||||
<div align="center">
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
|
||||
</p>
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
|
||||
<a href="https://www.npmjs.com/package/@discordjs/collection"><img src="https://img.shields.io/npm/v/@discordjs/collection.svg?maxAge=3600" alt="npm version" /></a>
|
||||
<a href="https://www.npmjs.com/package/@discordjs/collection"><img src="https://img.shields.io/npm/dt/@discordjs/collection.svg?maxAge=3600" alt="npm downloads" /></a>
|
||||
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
|
||||
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=collection" alt="Code coverage" /></a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## 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
|
@ -1,457 +0,0 @@
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
interface CollectionConstructor {
|
||||
new (): Collection<unknown, unknown>;
|
||||
new <K, V>(entries?: readonly (readonly [K, V])[] | null): Collection<K, V>;
|
||||
new <K, V>(iterable: Iterable<readonly [K, V]>): Collection<K, V>;
|
||||
readonly prototype: Collection<unknown, unknown>;
|
||||
readonly [Symbol.species]: CollectionConstructor;
|
||||
}
|
||||
/**
|
||||
* Represents an immutable version of a collection
|
||||
*/
|
||||
type ReadonlyCollection<K, V> = Omit<Collection<K, V>, 'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'> & ReadonlyMap<K, V>;
|
||||
/**
|
||||
* Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
interface Collection<K, V> extends Map<K, V> {
|
||||
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<K, V> extends Map<K, V> {
|
||||
/**
|
||||
* 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<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;
|
||||
find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;
|
||||
find<This, V2 extends V>(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): V2 | undefined;
|
||||
find<This>(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<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;
|
||||
findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;
|
||||
findKey<This, K2 extends K>(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): K2 | undefined;
|
||||
findKey<This>(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<T>(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<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): Collection<K2, V>;
|
||||
filter<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): Collection<K, V2>;
|
||||
filter(fn: (value: V, key: K, collection: this) => unknown): Collection<K, V>;
|
||||
filter<This, K2 extends K>(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): Collection<K2, V>;
|
||||
filter<This, V2 extends V>(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): Collection<K, V2>;
|
||||
filter<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection<K, V>;
|
||||
/**
|
||||
* 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<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): [Collection<K2, V>, Collection<Exclude<K, K2>, V>];
|
||||
partition<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): [Collection<K, V2>, Collection<K, Exclude<V, V2>>];
|
||||
partition(fn: (value: V, key: K, collection: this) => unknown): [Collection<K, V>, Collection<K, V>];
|
||||
partition<This, K2 extends K>(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): [Collection<K2, V>, Collection<Exclude<K, K2>, V>];
|
||||
partition<This, V2 extends V>(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): [Collection<K, V2>, Collection<K, Exclude<V, V2>>];
|
||||
partition<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): [Collection<K, V>, Collection<K, V>];
|
||||
/**
|
||||
* 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<T>(fn: (value: V, key: K, collection: this) => Collection<K, T>): Collection<K, T>;
|
||||
flatMap<T, This>(fn: (this: This, value: V, key: K, collection: this) => Collection<K, T>, thisArg: This): Collection<K, T>;
|
||||
/**
|
||||
* 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<T>(fn: (value: V, key: K, collection: this) => T): T[];
|
||||
map<This, T>(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<T>(fn: (value: V, key: K, collection: this) => T): Collection<K, T>;
|
||||
mapValues<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection<K, T>;
|
||||
/**
|
||||
* 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<T>(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<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): this is Collection<K2, V>;
|
||||
every<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): this is Collection<K, V2>;
|
||||
every(fn: (value: V, key: K, collection: this) => unknown): boolean;
|
||||
every<This, K2 extends K>(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): this is Collection<K2, V>;
|
||||
every<This, V2 extends V>(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): this is Collection<K, V2>;
|
||||
every<This>(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<T>(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<T>(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<T>(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<K, V>;
|
||||
/**
|
||||
* 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<K, V>[]): Collection<K, V>;
|
||||
/**
|
||||
* 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<K, V>): 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<K, V>): 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<T>(other: ReadonlyCollection<K, T>): Collection<K, 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.
|
||||
*
|
||||
* @param other - The other Collection to filter against
|
||||
*/
|
||||
subtract<T>(other: ReadonlyCollection<K, T>): Collection<K, V>;
|
||||
/**
|
||||
* 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<T>(other: ReadonlyCollection<K, T>): Collection<K, T | V>;
|
||||
/**
|
||||
* 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<T, R>(other: ReadonlyCollection<K, T>, whenInSelf: (value: V, key: K) => Keep<R>, whenInOther: (valueOther: T, key: K) => Keep<R>, whenInBoth: (value: V, valueOther: T, key: K) => Keep<R>): Collection<K, R>;
|
||||
/**
|
||||
* 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<K, V>): Collection<K, V>;
|
||||
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<K, V>(entries: Iterable<[K, V]>, combine: (firstValue: V, secondValue: V, key: K) => V): Collection<K, V>;
|
||||
}
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
type Keep<V> = {
|
||||
keep: false;
|
||||
} | {
|
||||
keep: true;
|
||||
value: V;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
type Comparator<K, V> = (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 };
|
@ -1,569 +0,0 @@
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/index.ts
|
||||
var src_exports = {};
|
||||
__export(src_exports, {
|
||||
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
|
File diff suppressed because one or more lines are too long
@ -1,543 +0,0 @@
|
||||
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
|
File diff suppressed because one or more lines are too long
@ -1,74 +0,0 @@
|
||||
{
|
||||
"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 <icrawltogo@gmail.com>",
|
||||
"Amish Shah <amishshah.2k@gmail.com>",
|
||||
"SpaceEEC <spaceeec@yahoo.com>",
|
||||
"Vlad Frangu <kingdgrizzle@gmail.com>",
|
||||
"Aura Román <kyradiscord@gmail.com>"
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
# 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))
|
||||
|
@ -1,191 +0,0 @@
|
||||
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.
|
@ -1,80 +0,0 @@
|
||||
<div align="center">
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
|
||||
</p>
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
|
||||
<a href="https://www.npmjs.com/package/@discordjs/formatters"><img src="https://img.shields.io/npm/v/@discordjs/formatters.svg?maxAge=3600" alt="npm version" /></a>
|
||||
<a href="https://www.npmjs.com/package/@discordjs/formatters"><img src="https://img.shields.io/npm/dt/@discordjs/formatters.svg?maxAge=3600" alt="npm downloads" /></a>
|
||||
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
|
||||
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=formatters" alt="Code coverage" /></a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## 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
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -1,70 +0,0 @@
|
||||
{
|
||||
"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 <icrawltogo@gmail.com>",
|
||||
"SpaceEEC <spaceeec@yahoo.com>",
|
||||
"Vlad Frangu <kingdgrizzle@gmail.com>",
|
||||
"Aura Román <kyradiscord@gmail.com>"
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
@ -1,185 +0,0 @@
|
||||
# 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))
|
@ -1,192 +0,0 @@
|
||||
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.
|
@ -1,112 +0,0 @@
|
||||
<div align="center">
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
|
||||
</p>
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
|
||||
<a href="https://www.npmjs.com/package/@discordjs/rest"><img src="https://img.shields.io/npm/v/@discordjs/rest.svg?maxAge=3600" alt="npm version" /></a>
|
||||
<a href="https://www.npmjs.com/package/@discordjs/rest"><img src="https://img.shields.io/npm/dt/@discordjs/rest.svg?maxAge=3600" alt="npm downloads" /></a>
|
||||
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Tests status" /></a>
|
||||
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=rest" alt="Code coverage" /></a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## 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
|
@ -1,870 +0,0 @@
|
||||
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<BaseImageURLOptions>): 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<BaseImageURLOptions>): 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<ImageURLOptions>): 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<ImageURLOptions>): 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<BaseImageURLOptions>): 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<BaseImageURLOptions>): 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<ImageURLOptions>): 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<ImageURLOptions>): 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<ImageURLOptions>): 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<BaseImageURLOptions>): 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<BaseImageURLOptions>): 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<BaseImageURLOptions>): 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<BaseImageURLOptions>): 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<BaseImageURLOptions>): 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<Dispatcher.ResponseData>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string, string>;
|
||||
/**
|
||||
* 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> | 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<string, IHandler>];
|
||||
hashSweep: [sweptHashes: Collection<string, HashData>];
|
||||
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<Parameters<typeof request>[1], undefined>;
|
||||
interface REST {
|
||||
emit: (<K extends keyof RestEvents>(event: K, ...args: RestEvents[K]) => boolean) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, ...args: any[]) => boolean);
|
||||
off: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
|
||||
on: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
|
||||
once: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
|
||||
removeAllListeners: (<K extends keyof RestEvents>(event?: K) => this) & (<S extends string | symbol>(event?: Exclude<S, keyof RestEvents>) => this);
|
||||
}
|
||||
declare class REST extends EventEmitter {
|
||||
readonly cdn: CDN;
|
||||
readonly requestManager: RequestManager;
|
||||
constructor(options?: Partial<RESTOptions>);
|
||||
/**
|
||||
* 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<unknown>;
|
||||
/**
|
||||
* 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<unknown>;
|
||||
/**
|
||||
* 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<unknown>;
|
||||
/**
|
||||
* 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<unknown>;
|
||||
/**
|
||||
* 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<unknown>;
|
||||
/**
|
||||
* Runs a request from the api
|
||||
*
|
||||
* @param options - Request options
|
||||
*/
|
||||
request(options: InternalRequest): Promise<unknown>;
|
||||
/**
|
||||
* Runs a request from the API, yielding the raw Response object
|
||||
*
|
||||
* @param options - Request options
|
||||
*/
|
||||
raw(options: InternalRequest): Promise<Dispatcher.ResponseData>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string, string>;
|
||||
/**
|
||||
* Whether to pass-through the body property directly to `fetch()`.
|
||||
* <warn>This only applies when files is NOT present</warn>
|
||||
*/
|
||||
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<InternalRequest, 'auth' | 'body' | 'files' | 'signal'>;
|
||||
/**
|
||||
* 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: (<K extends keyof RestEvents>(event: K, ...args: RestEvents[K]) => boolean) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, ...args: any[]) => boolean);
|
||||
off: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
|
||||
on: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
|
||||
once: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
|
||||
removeAllListeners: (<K extends keyof RestEvents>(event?: K) => this) & (<S extends string | symbol>(event?: Exclude<S, keyof RestEvents>) => 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<void> | null;
|
||||
/**
|
||||
* The timestamp at which the global bucket resets
|
||||
*/
|
||||
globalReset: number;
|
||||
/**
|
||||
* API bucket hashes that are cached from provided routes
|
||||
*/
|
||||
readonly hashes: Collection<string, HashData>;
|
||||
/**
|
||||
* Request handlers created from the bucket hash and the major parameters
|
||||
*/
|
||||
readonly handlers: Collection<string, IHandler>;
|
||||
private hashTimer;
|
||||
private handlerTimer;
|
||||
readonly options: RESTOptions;
|
||||
constructor(options: Partial<RESTOptions>);
|
||||
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<Dispatcher.ResponseData>;
|
||||
/**
|
||||
* 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<InternalRequest, 'body' | 'files'>);
|
||||
/**
|
||||
* 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<InternalRequest, 'body' | 'files'>);
|
||||
}
|
||||
|
||||
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<T extends object>(options?: Readonly<T>): URLSearchParams;
|
||||
/**
|
||||
* Converts the response to usable data
|
||||
*
|
||||
* @param res - The fetch response
|
||||
*/
|
||||
declare function parseResponse(res: Dispatcher.ResponseData): Promise<unknown>;
|
||||
|
||||
/**
|
||||
* 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 };
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@ -1,86 +0,0 @@
|
||||
{
|
||||
"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 <icrawltogo@gmail.com>",
|
||||
"Amish Shah <amishshah.2k@gmail.com>",
|
||||
"SpaceEEC <spaceeec@yahoo.com>",
|
||||
"Vlad Frangu <kingdgrizzle@gmail.com>",
|
||||
"Aura Román <kyradiscord@gmail.com>"
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
# 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))
|
@ -1,190 +0,0 @@
|
||||
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.
|
@ -1,60 +0,0 @@
|
||||
<div align="center">
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
|
||||
</p>
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
|
||||
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## 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
|
@ -1,104 +0,0 @@
|
||||
/**
|
||||
* Represents a type that may or may not be a promise
|
||||
*/
|
||||
type Awaitable<T> = PromiseLike<T> | 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<T>(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<number, void, unknown>;
|
||||
|
||||
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<T> {
|
||||
/**
|
||||
* 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<unknown>;
|
||||
|
||||
/**
|
||||
* 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<T> {
|
||||
/**
|
||||
* 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<unknown>;
|
||||
|
||||
export { Awaitable, Equatable, JSONEncodable, RangeOptions, calculateShardId, isEquatable, isJSONEncodable, lazy, range };
|
@ -1,82 +0,0 @@
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/index.ts
|
||||
var src_exports = {};
|
||||
__export(src_exports, {
|
||||
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
|
@ -1 +0,0 @@
|
||||
{"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<T>(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<T> {\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<unknown> {\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<T> {\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<unknown> {\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"]}
|
@ -1,53 +0,0 @@
|
||||
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
|
@ -1 +0,0 @@
|
||||
{"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<T>(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<T> {\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<unknown> {\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<T> {\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<unknown> {\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"]}
|
@ -1,78 +0,0 @@
|
||||
{
|
||||
"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 <icrawltogo@gmail.com>",
|
||||
"Amish Shah <amishshah.2k@gmail.com>",
|
||||
"Vlad Frangu <kingdgrizzle@gmail.com>",
|
||||
"SpaceEEC <spaceeec@yahoo.com>",
|
||||
"Aura Román <kyradiscord@gmail.com>"
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
@ -1,148 +0,0 @@
|
||||
# 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))
|
@ -1,116 +0,0 @@
|
||||
<div align="center">
|
||||
|
||||
![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)
|
||||
|
||||
</div>
|
||||
|
||||
## 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)):
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
|
||||
<!-- prettier-ignore-start -->
|
||||
<!-- markdownlint-disable -->
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center"><a href="https://favware.tech/"><img src="https://avatars3.githubusercontent.com/u/4019718?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jeroen Claassens</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=favna" title="Code">💻</a> <a href="#infra-favna" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#projectManagement-favna" title="Project Management">📆</a> <a href="https://github.com/sapphiredev/utilities/commits?author=favna" title="Documentation">📖</a> <a href="https://github.com/sapphiredev/utilities/commits?author=favna" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/kyranet"><img src="https://avatars0.githubusercontent.com/u/24852502?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Antonio Román</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=kyranet" title="Code">💻</a> <a href="#projectManagement-kyranet" title="Project Management">📆</a> <a href="https://github.com/sapphiredev/utilities/pulls?q=is%3Apr+reviewed-by%3Akyranet" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/sapphiredev/utilities/commits?author=kyranet" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/PyroTechniac"><img src="https://avatars2.githubusercontent.com/u/39341355?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Gryffon Bellish</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=PyroTechniac" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/pulls?q=is%3Apr+reviewed-by%3APyroTechniac" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/sapphiredev/utilities/commits?author=PyroTechniac" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/vladfrangu"><img src="https://avatars3.githubusercontent.com/u/17960496?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vlad Frangu</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=vladfrangu" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/issues?q=author%3Avladfrangu" title="Bug reports">🐛</a> <a href="https://github.com/sapphiredev/utilities/pulls?q=is%3Apr+reviewed-by%3Avladfrangu" title="Reviewed Pull Requests">👀</a> <a href="#userTesting-vladfrangu" title="User Testing">📓</a> <a href="https://github.com/sapphiredev/utilities/commits?author=vladfrangu" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/Stitch07"><img src="https://avatars0.githubusercontent.com/u/29275227?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stitch07</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Stitch07" title="Code">💻</a> <a href="#projectManagement-Stitch07" title="Project Management">📆</a> <a href="https://github.com/sapphiredev/utilities/commits?author=Stitch07" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/apps/depfu"><img src="https://avatars3.githubusercontent.com/in/715?v=4?s=100" width="100px;" alt=""/><br /><sub><b>depfu[bot]</b></sub></a><br /><a href="#maintenance-depfu[bot]" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://github.com/apps/allcontributors"><img src="https://avatars0.githubusercontent.com/in/23186?v=4?s=100" width="100px;" alt=""/><br /><sub><b>allcontributors[bot]</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=allcontributors[bot]" title="Documentation">📖</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/Nytelife26"><img src="https://avatars1.githubusercontent.com/u/22531310?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tyler J Russell</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Nytelife26" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/Alcremie"><img src="https://avatars0.githubusercontent.com/u/54785334?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ivan Lieder</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Alcremie" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/issues?q=author%3AAlcremie" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/RealShadowNova"><img src="https://avatars3.githubusercontent.com/u/46537907?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Hezekiah Hendry</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=RealShadowNova" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/Vetlix"><img src="https://avatars.githubusercontent.com/u/31412314?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vetlix</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Vetlix" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/ethamitc"><img src="https://avatars.githubusercontent.com/u/27776796?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ethan Mitchell</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=ethamitc" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/noftaly"><img src="https://avatars.githubusercontent.com/u/34779161?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Elliot</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=noftaly" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://jurien.dev"><img src="https://avatars.githubusercontent.com/u/5418114?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jurien Hamaker</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=jurienhamaker" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://fanoulis.dev/"><img src="https://avatars.githubusercontent.com/u/38255093?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Charalampos Fanoulis</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=cfanoulis" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/apps/dependabot"><img src="https://avatars.githubusercontent.com/in/29110?v=4?s=100" width="100px;" alt=""/><br /><sub><b>dependabot[bot]</b></sub></a><br /><a href="#maintenance-dependabot[bot]" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://kaname.netlify.app/"><img src="https://avatars.githubusercontent.com/u/56084970?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kaname</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=kaname-png" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/nandhagk"><img src="https://avatars.githubusercontent.com/u/62976649?v=4?s=100" width="100px;" alt=""/><br /><sub><b>nandhagk</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/issues?q=author%3Anandhagk" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://megatank58.me/"><img src="https://avatars.githubusercontent.com/u/51410502?v=4?s=100" width="100px;" alt=""/><br /><sub><b>megatank58</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=megatank58" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/UndiedGamer"><img src="https://avatars.githubusercontent.com/u/84702365?v=4?s=100" width="100px;" alt=""/><br /><sub><b>UndiedGamer</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=UndiedGamer" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/Lioness100"><img src="https://avatars.githubusercontent.com/u/65814829?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Lioness100</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Lioness100" title="Documentation">📖</a> <a href="https://github.com/sapphiredev/utilities/commits?author=Lioness100" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://gitlab.com/DavidPH/"><img src="https://avatars.githubusercontent.com/u/44669930?v=4?s=100" width="100px;" alt=""/><br /><sub><b>David</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=DavidPHH" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/apps/renovate"><img src="https://avatars.githubusercontent.com/in/2740?v=4?s=100" width="100px;" alt=""/><br /><sub><b>renovate[bot]</b></sub></a><br /><a href="#maintenance-renovate[bot]" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://renovate.whitesourcesoftware.com/"><img src="https://avatars.githubusercontent.com/u/25180681?v=4?s=100" width="100px;" alt=""/><br /><sub><b>WhiteSource Renovate</b></sub></a><br /><a href="#maintenance-renovate-bot" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://fc5570.me/"><img src="https://avatars.githubusercontent.com/u/68158483?v=4?s=100" width="100px;" alt=""/><br /><sub><b>FC</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=FC5570" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/Tokipudi"><img src="https://avatars.githubusercontent.com/u/29551076?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jérémy de Saint Denis</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Tokipudi" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/ItsMrCube"><img src="https://avatars.githubusercontent.com/u/25201357?v=4?s=100" width="100px;" alt=""/><br /><sub><b>MrCube</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=ItsMrCube" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/bitomic"><img src="https://avatars.githubusercontent.com/u/35199700?v=4?s=100" width="100px;" alt=""/><br /><sub><b>bitomic</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=bitomic" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://c43721.dev/"><img src="https://avatars.githubusercontent.com/u/55610086?v=4?s=100" width="100px;" alt=""/><br /><sub><b>c43721</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=c43721" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://commandtechno.com/"><img src="https://avatars.githubusercontent.com/u/68407783?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Commandtechno</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Commandtechno" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/dhruv-kaushikk"><img src="https://avatars.githubusercontent.com/u/73697546?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aura</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=dhruv-kaushikk" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://axis.moe/"><img src="https://avatars.githubusercontent.com/u/54381371?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jonathan</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=axisiscool" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/imranbarbhuiya"><img src="https://avatars.githubusercontent.com/u/74945038?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Parbez</b></sub></a><br /><a href="#maintenance-imranbarbhuiya" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://github.com/NotKaskus"><img src="https://avatars.githubusercontent.com/u/75168528?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Paul Andrew</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=NotKaskus" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://linktr.ee/mzato0001"><img src="https://avatars.githubusercontent.com/u/62367547?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mzato</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Mzato0001" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/issues?q=author%3AMzato0001" title="Bug reports">🐛</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/MajesticString"><img src="https://avatars.githubusercontent.com/u/66224939?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Harry Allen</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=MajesticString" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/EvolutionX-10"><img src="https://avatars.githubusercontent.com/u/85353424?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Evo</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=EvolutionX-10" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://enes.ovh/"><img src="https://avatars.githubusercontent.com/u/61084101?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Enes Genç</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=enxg" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/muchnameless"><img src="https://avatars.githubusercontent.com/u/12682826?v=4?s=100" width="100px;" alt=""/><br /><sub><b>muchnameless</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=muchnameless" title="Code">💻</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<!-- markdownlint-restore -->
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
||||
|
||||
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
|
@ -1,55 +0,0 @@
|
||||
/**
|
||||
* 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<AsyncQueueWaitOptions>): Promise<void>;
|
||||
/**
|
||||
* 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 };
|
@ -1,125 +0,0 @@
|
||||
"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
|
File diff suppressed because one or more lines are too long
@ -1,128 +0,0 @@
|
||||
"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
|
File diff suppressed because one or more lines are too long
@ -1,102 +0,0 @@
|
||||
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
|
File diff suppressed because one or more lines are too long
@ -1,65 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
@ -1,263 +0,0 @@
|
||||
# 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))
|
@ -1,24 +0,0 @@
|
||||
# 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.
|
@ -1,955 +0,0 @@
|
||||
<div align="center">
|
||||
|
||||
![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)
|
||||
|
||||
</div>
|
||||
|
||||
## 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<string, number>
|
||||
```
|
||||
|
||||
#### Sets
|
||||
|
||||
[Back to top][toc]
|
||||
|
||||
```typescript
|
||||
const set = s.set(s.number);
|
||||
// Set<number>
|
||||
```
|
||||
|
||||
#### 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<string, T>` 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<typeof schema>;
|
||||
|
||||
// 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<IInstruction>;
|
||||
// Expected Type: ObjectValidator<IInstruction>
|
||||
|
||||
type IngredientSchemaType = SchemaOf<IIngredient>;
|
||||
// Expected Type: ObjectValidator<IIngredient>
|
||||
|
||||
type RecipeSchemaType = SchemaOf<IRecipe>;
|
||||
// Expected Type: ObjectValidator<IRecipe>
|
||||
|
||||
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<T, Error>`: 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<R>((value: T) => R): NopValidator<R>`: 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<R>((value: T) => Result<R, Error> | IConstraint): NopValidator<R>`: 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)):
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
|
||||
<!-- prettier-ignore-start -->
|
||||
<!-- markdownlint-disable -->
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/kyranet"><img src="https://avatars.githubusercontent.com/u/24852502?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Antonio Román</b></sub></a><br /><a href="https://github.com/sapphiredev/shapeshift/commits?author=kyranet" title="Code">💻</a> <a href="https://github.com/sapphiredev/shapeshift/commits?author=kyranet" title="Documentation">📖</a> <a href="#ideas-kyranet" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/vladfrangu"><img src="https://avatars.githubusercontent.com/u/17960496?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vlad Frangu</b></sub></a><br /><a href="https://github.com/sapphiredev/shapeshift/commits?author=vladfrangu" title="Code">💻</a> <a href="https://github.com/sapphiredev/shapeshift/commits?author=vladfrangu" title="Documentation">📖</a> <a href="#ideas-vladfrangu" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://favware.tech/"><img src="https://avatars.githubusercontent.com/u/4019718?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jeroen Claassens</b></sub></a><br /><a href="https://github.com/sapphiredev/shapeshift/commits?author=favna" title="Documentation">📖</a> <a href="#maintenance-favna" title="Maintenance">🚧</a> <a href="#infra-favna" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
<td align="center"><a href="https://github.com/apps/renovate"><img src="https://avatars.githubusercontent.com/in/2740?v=4?s=100" width="100px;" alt=""/><br /><sub><b>renovate[bot]</b></sub></a><br /><a href="#maintenance-renovate[bot]" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://renovate.whitesourcesoftware.com/"><img src="https://avatars.githubusercontent.com/u/25180681?v=4?s=100" width="100px;" alt=""/><br /><sub><b>WhiteSource Renovate</b></sub></a><br /><a href="#maintenance-renovate-bot" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://github.com/Khasms"><img src="https://avatars.githubusercontent.com/u/36800359?v=4?s=100" width="100px;" alt=""/><br /><sub><b>John</b></sub></a><br /><a href="https://github.com/sapphiredev/shapeshift/commits?author=Khasms" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/imranbarbhuiya"><img src="https://avatars.githubusercontent.com/u/74945038?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Parbez</b></sub></a><br /><a href="https://github.com/sapphiredev/shapeshift/commits?author=imranbarbhuiya" title="Code">💻</a> <a href="https://github.com/sapphiredev/shapeshift/commits?author=imranbarbhuiya" title="Tests">⚠️</a> <a href="https://github.com/sapphiredev/shapeshift/issues?q=author%3Aimranbarbhuiya" title="Bug reports">🐛</a> <a href="https://github.com/sapphiredev/shapeshift/commits?author=imranbarbhuiya" title="Documentation">📖</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/apps/allcontributors"><img src="https://avatars.githubusercontent.com/in/23186?v=4?s=100" width="100px;" alt=""/><br /><sub><b>allcontributors[bot]</b></sub></a><br /><a href="https://github.com/sapphiredev/shapeshift/commits?author=allcontributors[bot]" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/RealShadowNova"><img src="https://avatars.githubusercontent.com/u/46537907?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Hezekiah Hendry</b></sub></a><br /><a href="#tool-RealShadowNova" title="Tools">🔧</a></td>
|
||||
<td align="center"><a href="https://github.com/legendhimslef"><img src="https://avatars.githubusercontent.com/u/69213593?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Voxelli</b></sub></a><br /><a href="https://github.com/sapphiredev/shapeshift/commits?author=legendhimslef" title="Documentation">📖</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<!-- markdownlint-restore -->
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
||||
|
||||
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
|
@ -1,713 +0,0 @@
|
||||
import { InspectOptionsStylized } from 'node:util';
|
||||
|
||||
declare class Result<T, E extends Error = Error> {
|
||||
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<T, E extends Error = Error>(value: T): Result<T, E>;
|
||||
static err<T, E extends Error = Error>(error: E): Result<T, E>;
|
||||
}
|
||||
|
||||
type ArrayConstraintName = `s.array(T).${'unique' | `length${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual' | 'Range' | 'RangeInclusive' | 'RangeExclusive'}`}`;
|
||||
declare function arrayLengthLessThan<T>(value: number): IConstraint<T[]>;
|
||||
declare function arrayLengthLessThanOrEqual<T>(value: number): IConstraint<T[]>;
|
||||
declare function arrayLengthGreaterThan<T>(value: number): IConstraint<T[]>;
|
||||
declare function arrayLengthGreaterThanOrEqual<T>(value: number): IConstraint<T[]>;
|
||||
declare function arrayLengthEqual<T>(value: number): IConstraint<T[]>;
|
||||
declare function arrayLengthNotEqual<T>(value: number): IConstraint<T[]>;
|
||||
declare function arrayLengthRange<T>(start: number, endBefore: number): IConstraint<T[]>;
|
||||
declare function arrayLengthRangeInclusive<T>(start: number, end: number): IConstraint<T[]>;
|
||||
declare function arrayLengthRangeExclusive<T>(startAfter: number, endBefore: number): IConstraint<T[]>;
|
||||
|
||||
type BigIntConstraintName = `s.bigint.${'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'equal' | 'notEqual' | 'divisibleBy'}`;
|
||||
declare function bigintLessThan(value: bigint): IConstraint<bigint>;
|
||||
declare function bigintLessThanOrEqual(value: bigint): IConstraint<bigint>;
|
||||
declare function bigintGreaterThan(value: bigint): IConstraint<bigint>;
|
||||
declare function bigintGreaterThanOrEqual(value: bigint): IConstraint<bigint>;
|
||||
declare function bigintEqual(value: bigint): IConstraint<bigint>;
|
||||
declare function bigintNotEqual(value: bigint): IConstraint<bigint>;
|
||||
declare function bigintDivisibleBy(divider: bigint): IConstraint<bigint>;
|
||||
|
||||
type BooleanConstraintName = `s.boolean.${boolean}`;
|
||||
declare const booleanTrue: IConstraint<boolean, true>;
|
||||
declare const booleanFalse: IConstraint<boolean, false>;
|
||||
|
||||
type DateConstraintName = `s.date.${'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'equal' | 'notEqual' | 'valid' | 'invalid'}`;
|
||||
declare function dateLessThan(value: Date): IConstraint<Date>;
|
||||
declare function dateLessThanOrEqual(value: Date): IConstraint<Date>;
|
||||
declare function dateGreaterThan(value: Date): IConstraint<Date>;
|
||||
declare function dateGreaterThanOrEqual(value: Date): IConstraint<Date>;
|
||||
declare function dateEqual(value: Date): IConstraint<Date>;
|
||||
declare function dateNotEqual(value: Date): IConstraint<Date>;
|
||||
declare const dateInvalid: IConstraint<Date>;
|
||||
declare const dateValid: IConstraint<Date>;
|
||||
|
||||
type NumberConstraintName = `s.number.${'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'equal' | 'equal(NaN)' | 'notEqual' | 'notEqual(NaN)' | 'int' | 'safeInt' | 'finite' | 'divisibleBy'}`;
|
||||
declare function numberLessThan(value: number): IConstraint<number>;
|
||||
declare function numberLessThanOrEqual(value: number): IConstraint<number>;
|
||||
declare function numberGreaterThan(value: number): IConstraint<number>;
|
||||
declare function numberGreaterThanOrEqual(value: number): IConstraint<number>;
|
||||
declare function numberEqual(value: number): IConstraint<number>;
|
||||
declare function numberNotEqual(value: number): IConstraint<number>;
|
||||
declare const numberInt: IConstraint<number>;
|
||||
declare const numberSafeInt: IConstraint<number>;
|
||||
declare const numberFinite: IConstraint<number>;
|
||||
declare const numberNaN: IConstraint<number>;
|
||||
declare const numberNotNaN: IConstraint<number>;
|
||||
declare function numberDivisibleBy(divider: number): IConstraint<number>;
|
||||
|
||||
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<T> 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<T = unknown> extends BaseConstraintError<T> {
|
||||
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<string | number, string | number>;
|
||||
constructor(value: string | number, keys: string[], enumMappings: Map<string | number, string | number>);
|
||||
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<T extends bigint> extends BaseValidator<T> {
|
||||
lessThan(number: bigint): this;
|
||||
lessThanOrEqual(number: bigint): this;
|
||||
greaterThan(number: bigint): this;
|
||||
greaterThanOrEqual(number: bigint): this;
|
||||
equal<N extends bigint>(number: N): BigIntValidator<N>;
|
||||
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<T, ValidationError>;
|
||||
}
|
||||
|
||||
declare class BooleanValidator<T extends boolean = boolean> extends BaseValidator<T> {
|
||||
get true(): BooleanValidator<true>;
|
||||
get false(): BooleanValidator<false>;
|
||||
equal<R extends true | false>(value: R): BooleanValidator<R>;
|
||||
notEqual<R extends true | false>(value: R): BooleanValidator<R>;
|
||||
protected handle(value: unknown): Result<T, ValidationError>;
|
||||
}
|
||||
|
||||
declare class DateValidator extends BaseValidator<Date> {
|
||||
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<Date, ValidationError>;
|
||||
}
|
||||
|
||||
declare class DefaultValidator<T> extends BaseValidator<T> {
|
||||
private readonly validator;
|
||||
private defaultValue;
|
||||
constructor(validator: BaseValidator<T>, value: T | (() => T), constraints?: readonly IConstraint<T>[]);
|
||||
default(value: Exclude<T, undefined> | (() => Exclude<T, undefined>)): DefaultValidator<Exclude<T, undefined>>;
|
||||
protected handle(value: unknown): Result<T, ValidatorError>;
|
||||
protected clone(): this;
|
||||
}
|
||||
|
||||
declare class InstanceValidator<T> extends BaseValidator<T> {
|
||||
readonly expected: Constructor<T>;
|
||||
constructor(expected: Constructor<T>, constraints?: readonly IConstraint<T>[]);
|
||||
protected handle(value: unknown): Result<T, ExpectedValidationError<Constructor<T>>>;
|
||||
protected clone(): this;
|
||||
}
|
||||
|
||||
declare class LiteralValidator<T> extends BaseValidator<T> {
|
||||
readonly expected: T;
|
||||
constructor(literal: T, constraints?: readonly IConstraint<T>[]);
|
||||
protected handle(value: unknown): Result<T, ExpectedValidationError<T>>;
|
||||
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<K, V> extends BaseValidator<Map<K, V>> {
|
||||
private readonly keyValidator;
|
||||
private readonly valueValidator;
|
||||
constructor(keyValidator: BaseValidator<K>, valueValidator: BaseValidator<V>, constraints?: readonly IConstraint<Map<K, V>>[]);
|
||||
protected clone(): this;
|
||||
protected handle(value: unknown): Result<Map<K, V>, ValidationError | CombinedPropertyError>;
|
||||
}
|
||||
|
||||
declare class NativeEnumValidator<T extends NativeEnumLike> extends BaseValidator<T[keyof T]> {
|
||||
readonly enumShape: T;
|
||||
readonly hasNumericElements: boolean;
|
||||
private readonly enumKeys;
|
||||
private readonly enumMapping;
|
||||
constructor(enumShape: T);
|
||||
protected handle(value: unknown): Result<T[keyof T], ValidationError | UnknownEnumValueError>;
|
||||
protected clone(): this;
|
||||
}
|
||||
interface NativeEnumLike {
|
||||
[key: string]: string | number;
|
||||
[key: number]: string;
|
||||
}
|
||||
|
||||
declare class NeverValidator extends BaseValidator<never> {
|
||||
protected handle(value: unknown): Result<never, ValidationError>;
|
||||
}
|
||||
|
||||
declare class NullishValidator extends BaseValidator<undefined | null> {
|
||||
protected handle(value: unknown): Result<undefined | null, ValidationError>;
|
||||
}
|
||||
|
||||
declare class NumberValidator<T extends number> extends BaseValidator<T> {
|
||||
lessThan(number: number): this;
|
||||
lessThanOrEqual(number: number): this;
|
||||
greaterThan(number: number): this;
|
||||
greaterThanOrEqual(number: number): this;
|
||||
equal<N extends number>(number: N): NumberValidator<N>;
|
||||
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<T, ValidationError>;
|
||||
}
|
||||
|
||||
declare class ObjectValidator<T extends object, I = UndefinedToOptional<T>> extends BaseValidator<I> {
|
||||
readonly shape: MappedObjectValidator<T>;
|
||||
readonly strategy: ObjectValidatorStrategy;
|
||||
private readonly keys;
|
||||
private readonly handleStrategy;
|
||||
private readonly requiredKeys;
|
||||
private readonly possiblyUndefinedKeys;
|
||||
private readonly possiblyUndefinedKeysWithDefaults;
|
||||
constructor(shape: MappedObjectValidator<T>, strategy?: ObjectValidatorStrategy, constraints?: readonly IConstraint<I>[]);
|
||||
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<ET extends object>(schema: ObjectValidator<ET> | MappedObjectValidator<ET>): ObjectValidator<T & ET>;
|
||||
pick<K extends keyof I>(keys: readonly K[]): ObjectValidator<{
|
||||
[Key in keyof Pick<I, K>]: I[Key];
|
||||
}>;
|
||||
omit<K extends keyof I>(keys: readonly K[]): ObjectValidator<{
|
||||
[Key in keyof Omit<I, K>]: I[Key];
|
||||
}>;
|
||||
protected handle(value: unknown): Result<I, ValidationError | CombinedPropertyError>;
|
||||
protected clone(): this;
|
||||
private handleIgnoreStrategy;
|
||||
private handleStrictStrategy;
|
||||
private handlePassthroughStrategy;
|
||||
}
|
||||
declare const enum ObjectValidatorStrategy {
|
||||
Ignore = 0,
|
||||
Strict = 1,
|
||||
Passthrough = 2
|
||||
}
|
||||
|
||||
declare class PassthroughValidator<T extends any | unknown> extends BaseValidator<T> {
|
||||
protected handle(value: unknown): Result<T, ValidationError>;
|
||||
}
|
||||
|
||||
declare class RecordValidator<T> extends BaseValidator<Record<string, T>> {
|
||||
private readonly validator;
|
||||
constructor(validator: BaseValidator<T>, constraints?: readonly IConstraint<Record<string, T>>[]);
|
||||
protected clone(): this;
|
||||
protected handle(value: unknown): Result<Record<string, T>, ValidationError | CombinedPropertyError>;
|
||||
}
|
||||
|
||||
declare class SetValidator<T> extends BaseValidator<Set<T>> {
|
||||
private readonly validator;
|
||||
constructor(validator: BaseValidator<T>, constraints?: readonly IConstraint<Set<T>>[]);
|
||||
protected clone(): this;
|
||||
protected handle(values: unknown): Result<Set<T>, 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<string>;
|
||||
declare function stringLengthLessThanOrEqual(length: number): IConstraint<string>;
|
||||
declare function stringLengthGreaterThan(length: number): IConstraint<string>;
|
||||
declare function stringLengthGreaterThanOrEqual(length: number): IConstraint<string>;
|
||||
declare function stringLengthEqual(length: number): IConstraint<string>;
|
||||
declare function stringLengthNotEqual(length: number): IConstraint<string>;
|
||||
declare function stringEmail(): IConstraint<string>;
|
||||
declare function stringUrl(options?: UrlOptions): IConstraint<string>;
|
||||
declare function stringIp(version?: 4 | 6): IConstraint<string>;
|
||||
declare function stringRegex(regex: RegExp): IConstraint<string, string>;
|
||||
declare function stringUuid({ version, nullable }?: StringUuidOptions): IConstraint<string, string>;
|
||||
|
||||
declare class StringValidator<T extends string> extends BaseValidator<T> {
|
||||
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<T, ValidationError>;
|
||||
}
|
||||
|
||||
declare class TupleValidator<T extends any[]> 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<T extends TypedArray> extends BaseValidator<T> {
|
||||
private readonly type;
|
||||
constructor(type: TypedArrayName, constraints?: readonly IConstraint<T>[]);
|
||||
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<T, ValidationError>;
|
||||
}
|
||||
|
||||
declare class UnionValidator<T> extends BaseValidator<T> {
|
||||
private validators;
|
||||
constructor(validators: readonly BaseValidator<T>[], constraints?: readonly IConstraint<T>[]);
|
||||
get optional(): UnionValidator<T | undefined>;
|
||||
get required(): UnionValidator<Exclude<T, undefined>>;
|
||||
get nullable(): UnionValidator<T | null>;
|
||||
get nullish(): UnionValidator<T | null | undefined>;
|
||||
or<O>(...predicates: readonly BaseValidator<O>[]): UnionValidator<T | O>;
|
||||
protected clone(): this;
|
||||
protected handle(value: unknown): Result<T, ValidationError | CombinedError>;
|
||||
}
|
||||
|
||||
type ObjectConstraintName = `s.object(T.when)`;
|
||||
type WhenKey = PropertyKey | PropertyKey[];
|
||||
interface WhenOptions<T extends BaseValidator<any>, Key extends WhenKey> {
|
||||
is?: boolean | ((value: Key extends Array<any> ? any[] : any) => boolean);
|
||||
then: (predicate: T) => T;
|
||||
otherwise?: (predicate: T) => T;
|
||||
}
|
||||
|
||||
declare class ExpectedConstraintError<T = unknown> extends BaseConstraintError<T> {
|
||||
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<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayByteLengthLessThanOrEqual<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayByteLengthGreaterThan<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayByteLengthGreaterThanOrEqual<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayByteLengthEqual<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayByteLengthNotEqual<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayByteLengthRange<T extends TypedArray>(start: number, endBefore: number): IConstraint<T>;
|
||||
declare function typedArrayByteLengthRangeInclusive<T extends TypedArray>(start: number, end: number): {
|
||||
run(input: T): Result<T, Error> | Result<unknown, ExpectedConstraintError<T>>;
|
||||
};
|
||||
declare function typedArrayByteLengthRangeExclusive<T extends TypedArray>(startAfter: number, endBefore: number): IConstraint<T>;
|
||||
declare function typedArrayLengthLessThan<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayLengthLessThanOrEqual<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayLengthGreaterThan<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayLengthGreaterThanOrEqual<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayLengthEqual<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayLengthNotEqual<T extends TypedArray>(value: number): IConstraint<T>;
|
||||
declare function typedArrayLengthRange<T extends TypedArray>(start: number, endBefore: number): IConstraint<T>;
|
||||
declare function typedArrayLengthRangeInclusive<T extends TypedArray>(start: number, end: number): IConstraint<T>;
|
||||
declare function typedArrayLengthRangeExclusive<T extends TypedArray>(startAfter: number, endBefore: number): IConstraint<T>;
|
||||
|
||||
type ConstraintErrorNames = TypedArrayConstraintName | ArrayConstraintName | BigIntConstraintName | BooleanConstraintName | DateConstraintName | NumberConstraintName | ObjectConstraintName | StringConstraintName;
|
||||
declare abstract class BaseConstraintError<T = unknown> extends BaseError {
|
||||
readonly constraint: ConstraintErrorNames;
|
||||
readonly given: T;
|
||||
constructor(constraint: ConstraintErrorNames, message: string, given: T);
|
||||
}
|
||||
|
||||
interface IConstraint<Input, Return extends Input = Input> {
|
||||
run(input: Input, parent?: any): Result<Return, BaseConstraintError<Input>>;
|
||||
}
|
||||
|
||||
declare class ArrayValidator<T extends unknown[], I = T[number]> extends BaseValidator<T> {
|
||||
private readonly validator;
|
||||
constructor(validator: BaseValidator<I>, constraints?: readonly IConstraint<T>[]);
|
||||
lengthLessThan<N extends number>(length: N): ArrayValidator<ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, N>]>>>;
|
||||
lengthLessThanOrEqual<N extends number>(length: N): ArrayValidator<ExpandSmallerTuples<[...Tuple<I, N>]>>;
|
||||
lengthGreaterThan<N extends number>(length: N): ArrayValidator<[...Tuple<I, N>, I, ...T]>;
|
||||
lengthGreaterThanOrEqual<N extends number>(length: N): ArrayValidator<[...Tuple<I, N>, ...T]>;
|
||||
lengthEqual<N extends number>(length: N): ArrayValidator<[...Tuple<I, N>]>;
|
||||
lengthNotEqual(length: number): ArrayValidator<[...T]>;
|
||||
lengthRange<S extends number, E extends number>(start: S, endBefore: E): ArrayValidator<Exclude<ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, E>]>>, ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, S>]>>>>;
|
||||
lengthRangeInclusive<S extends number, E extends number>(startAt: S, endAt: E): ArrayValidator<Exclude<ExpandSmallerTuples<[...Tuple<I, E>]>, ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, S>]>>>>;
|
||||
lengthRangeExclusive<S extends number, E extends number>(startAfter: S, endBefore: E): ArrayValidator<Exclude<ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, E>]>>, ExpandSmallerTuples<[...Tuple<T, S>]>>>;
|
||||
get unique(): this;
|
||||
protected clone(): this;
|
||||
protected handle(values: unknown): Result<T, ValidationError | CombinedPropertyError>;
|
||||
}
|
||||
|
||||
declare abstract class BaseValidator<T> {
|
||||
protected parent?: object;
|
||||
protected constraints: readonly IConstraint<T>[];
|
||||
protected isValidationEnabled: boolean | (() => boolean) | null;
|
||||
constructor(constraints?: readonly IConstraint<T>[]);
|
||||
setParent(parent: object): this;
|
||||
get optional(): UnionValidator<T | undefined>;
|
||||
get nullable(): UnionValidator<T | null>;
|
||||
get nullish(): UnionValidator<T | null | undefined>;
|
||||
get array(): ArrayValidator<T[]>;
|
||||
get set(): SetValidator<T>;
|
||||
or<O>(...predicates: readonly BaseValidator<O>[]): UnionValidator<T | O>;
|
||||
transform(cb: (value: T) => T): this;
|
||||
transform<O>(cb: (value: T) => O): BaseValidator<O>;
|
||||
reshape(cb: (input: T) => Result<T>): this;
|
||||
reshape<R extends Result<unknown>, O = InferResultType<R>>(cb: (input: T) => R): BaseValidator<O>;
|
||||
default(value: Exclude<T, undefined> | (() => Exclude<T, undefined>)): DefaultValidator<Exclude<T, undefined>>;
|
||||
when<Key extends WhenKey, This extends BaseValidator<any> = this>(key: Key, options: WhenOptions<This, Key>): this;
|
||||
run(value: unknown): Result<T, BaseError>;
|
||||
parse<R extends T = T>(value: unknown): R;
|
||||
is<R extends T = T>(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<T, ValidatorError>;
|
||||
protected addConstraint(constraint: IConstraint<T>): this;
|
||||
}
|
||||
type ValidatorError = ValidationError | CombinedError | CombinedPropertyError | UnknownEnumValueError;
|
||||
|
||||
type Constructor<T> = (new (...args: readonly any[]) => T) | (abstract new (...args: readonly any[]) => T);
|
||||
type Type<V> = V extends BaseValidator<infer T> ? 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<T> = {
|
||||
[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<T> = {
|
||||
[K in keyof T as undefined extends T[K] ? K : never]+?: Exclude<T[K], undefined>;
|
||||
};
|
||||
type FilterDefinedKeys<TObj extends object> = Exclude<{
|
||||
[TKey in keyof TObj]: undefined extends TObj[TKey] ? never : TKey;
|
||||
}[keyof TObj], undefined>;
|
||||
type UndefinedToOptional<T extends object> = Pick<T, FilterDefinedKeys<T>> & {
|
||||
[k in keyof Omit<T, FilterDefinedKeys<T>>]?: Exclude<T[k], undefined>;
|
||||
};
|
||||
type MappedObjectValidator<T> = {
|
||||
[key in keyof T]: BaseValidator<T[key]>;
|
||||
};
|
||||
/**
|
||||
* 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<IInstruction>;
|
||||
* // Expected Type: ObjectValidator<IInstruction>
|
||||
*
|
||||
* type IngredientSchemaType = SchemaOf<IIngredient>;
|
||||
* // Expected Type: ObjectValidator<IIngredient>
|
||||
*
|
||||
* type RecipeSchemaType = SchemaOf<IRecipe>;
|
||||
* // Expected Type: ObjectValidator<IRecipe>
|
||||
*
|
||||
* 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<T extends object> = ObjectValidator<T>;
|
||||
/**
|
||||
* 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<typeof schema>;
|
||||
* // Expected type:
|
||||
* // type Inferredtype = {
|
||||
* // foo: string;
|
||||
* // bar: number;
|
||||
* // baz: boolean;
|
||||
* // qux: bigint;
|
||||
* // quux: Date;
|
||||
* // };
|
||||
* ```
|
||||
*/
|
||||
type InferType<T extends ObjectValidator<any>> = T extends ObjectValidator<any, infer U> ? U : never;
|
||||
type InferResultType<T extends Result<any>> = T extends Result<infer U> ? U : never;
|
||||
type UnwrapTuple<T extends [...any[]]> = T extends [infer Head, ...infer Tail] ? [Unwrap<Head>, ...UnwrapTuple<Tail>] : [];
|
||||
type Unwrap<T> = T extends BaseValidator<infer V> ? V : never;
|
||||
type UnshiftTuple<T extends [...any[]]> = T extends [T[0], ...infer Tail] ? Tail : never;
|
||||
type ExpandSmallerTuples<T extends [...any[]]> = T extends [T[0], ...infer Tail] ? T | ExpandSmallerTuples<Tail> : [];
|
||||
type Shift<A extends Array<any>> = ((...args: A) => void) extends (...args: [A[0], ...infer R]) => void ? R : never;
|
||||
type GrowExpRev<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : GrowExpRev<[...A, ...P[0]][N] extends undefined ? [...A, ...P[0]] : A, N, Shift<P>>;
|
||||
type GrowExp<A extends Array<any>, N extends number, P extends Array<Array<any>>> = [...A, ...A][N] extends undefined ? GrowExp<[...A, ...A], N, [A, ...P]> : GrowExpRev<A, N, P>;
|
||||
type Tuple<T, N extends number> = number extends N ? Array<T> : N extends 0 ? [] : N extends 1 ? [T] : GrowExp<[T], N, [[]]>;
|
||||
|
||||
declare class LazyValidator<T extends BaseValidator<unknown>, R = Unwrap<T>> extends BaseValidator<R> {
|
||||
private readonly validator;
|
||||
constructor(validator: (value: unknown) => T, constraints?: readonly IConstraint<R>[]);
|
||||
protected clone(): this;
|
||||
protected handle(values: unknown): Result<R, ValidatorError>;
|
||||
}
|
||||
|
||||
declare class Shapes {
|
||||
get string(): StringValidator<string>;
|
||||
get number(): NumberValidator<number>;
|
||||
get bigint(): BigIntValidator<bigint>;
|
||||
get boolean(): BooleanValidator<boolean>;
|
||||
get date(): DateValidator;
|
||||
object<T extends object>(shape: MappedObjectValidator<T>): ObjectValidator<T, UndefinedToOptional<T>>;
|
||||
get undefined(): BaseValidator<undefined>;
|
||||
get null(): BaseValidator<null>;
|
||||
get nullish(): NullishValidator;
|
||||
get any(): PassthroughValidator<any>;
|
||||
get unknown(): PassthroughValidator<unknown>;
|
||||
get never(): NeverValidator;
|
||||
enum<T>(...values: readonly T[]): UnionValidator<T>;
|
||||
nativeEnum<T extends NativeEnumLike>(enumShape: T): NativeEnumValidator<T>;
|
||||
literal<T>(value: T): BaseValidator<T>;
|
||||
instance<T>(expected: Constructor<T>): InstanceValidator<T>;
|
||||
union<T extends [...BaseValidator<any>[]]>(...validators: [...T]): UnionValidator<Unwrap<T[number]>>;
|
||||
array<T>(validator: BaseValidator<T[][number]>): ArrayValidator<T[], T[][number]>;
|
||||
array<T extends unknown[]>(validator: BaseValidator<T[number]>): ArrayValidator<T, T[number]>;
|
||||
typedArray<T extends TypedArray>(type?: TypedArrayName): TypedArrayValidator<T>;
|
||||
get int8Array(): TypedArrayValidator<Int8Array>;
|
||||
get uint8Array(): TypedArrayValidator<Uint8Array>;
|
||||
get uint8ClampedArray(): TypedArrayValidator<Uint8ClampedArray>;
|
||||
get int16Array(): TypedArrayValidator<Int16Array>;
|
||||
get uint16Array(): TypedArrayValidator<Uint16Array>;
|
||||
get int32Array(): TypedArrayValidator<Int32Array>;
|
||||
get uint32Array(): TypedArrayValidator<Uint32Array>;
|
||||
get float32Array(): TypedArrayValidator<Float32Array>;
|
||||
get float64Array(): TypedArrayValidator<Float64Array>;
|
||||
get bigInt64Array(): TypedArrayValidator<BigInt64Array>;
|
||||
get bigUint64Array(): TypedArrayValidator<BigUint64Array>;
|
||||
tuple<T extends [...BaseValidator<any>[]]>(validators: [...T]): TupleValidator<UnwrapTuple<T>>;
|
||||
set<T>(validator: BaseValidator<T>): SetValidator<T>;
|
||||
record<T>(validator: BaseValidator<T>): RecordValidator<T>;
|
||||
map<T, U>(keyValidator: BaseValidator<T>, valueValidator: BaseValidator<U>): MapValidator<T, U>;
|
||||
lazy<T extends BaseValidator<unknown>>(validator: (value: unknown) => T): LazyValidator<T, Unwrap<T>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 };
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@ -1,127 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
@ -1,263 +0,0 @@
|
||||
# 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))
|
@ -1,234 +0,0 @@
|
||||
<div align="center">
|
||||
|
||||
![Sapphire Logo](https://cdn.skyra.pw/gh-assets/sapphire-banner.png)
|
||||
|
||||
# @sapphire/snowflake
|
||||
|
||||
**Deconstruct and generate snowflake IDs using BigInts.**
|
||||
|
||||
[![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/snowflake?logo=webpack&style=flat-square)](https://bundlephobia.com/result?p=@sapphire/snowflake)
|
||||
[![npm](https://img.shields.io/npm/v/@sapphire/snowflake?color=crimson&logo=npm&style=flat-square)](https://www.npmjs.com/package/@sapphire/snowflake)
|
||||
|
||||
</div>
|
||||
|
||||
**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)):
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
|
||||
<!-- prettier-ignore-start -->
|
||||
<!-- markdownlint-disable -->
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center"><a href="https://favware.tech/"><img src="https://avatars3.githubusercontent.com/u/4019718?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jeroen Claassens</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=favna" title="Code">💻</a> <a href="#infra-favna" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#projectManagement-favna" title="Project Management">📆</a> <a href="https://github.com/sapphiredev/utilities/commits?author=favna" title="Documentation">📖</a> <a href="https://github.com/sapphiredev/utilities/commits?author=favna" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/kyranet"><img src="https://avatars0.githubusercontent.com/u/24852502?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aura Román</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=kyranet" title="Code">💻</a> <a href="#projectManagement-kyranet" title="Project Management">📆</a> <a href="https://github.com/sapphiredev/utilities/pulls?q=is%3Apr+reviewed-by%3Akyranet" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/sapphiredev/utilities/commits?author=kyranet" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/PyroTechniac"><img src="https://avatars2.githubusercontent.com/u/39341355?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Gryffon Bellish</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=PyroTechniac" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/pulls?q=is%3Apr+reviewed-by%3APyroTechniac" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/sapphiredev/utilities/commits?author=PyroTechniac" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/vladfrangu"><img src="https://avatars3.githubusercontent.com/u/17960496?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vlad Frangu</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=vladfrangu" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/issues?q=author%3Avladfrangu" title="Bug reports">🐛</a> <a href="https://github.com/sapphiredev/utilities/pulls?q=is%3Apr+reviewed-by%3Avladfrangu" title="Reviewed Pull Requests">👀</a> <a href="#userTesting-vladfrangu" title="User Testing">📓</a> <a href="https://github.com/sapphiredev/utilities/commits?author=vladfrangu" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/Stitch07"><img src="https://avatars0.githubusercontent.com/u/29275227?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stitch07</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Stitch07" title="Code">💻</a> <a href="#projectManagement-Stitch07" title="Project Management">📆</a> <a href="https://github.com/sapphiredev/utilities/commits?author=Stitch07" title="Tests">⚠️</a></td>
|
||||
<td align="center"><a href="https://github.com/apps/depfu"><img src="https://avatars3.githubusercontent.com/in/715?v=4?s=100" width="100px;" alt=""/><br /><sub><b>depfu[bot]</b></sub></a><br /><a href="#maintenance-depfu[bot]" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://github.com/apps/allcontributors"><img src="https://avatars0.githubusercontent.com/in/23186?v=4?s=100" width="100px;" alt=""/><br /><sub><b>allcontributors[bot]</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=allcontributors[bot]" title="Documentation">📖</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/Nytelife26"><img src="https://avatars1.githubusercontent.com/u/22531310?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tyler J Russell</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Nytelife26" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/Alcremie"><img src="https://avatars0.githubusercontent.com/u/54785334?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ivan Lieder</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Alcremie" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/issues?q=author%3AAlcremie" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/RealShadowNova"><img src="https://avatars3.githubusercontent.com/u/46537907?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Hezekiah Hendry</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=RealShadowNova" title="Code">💻</a> <a href="#tool-RealShadowNova" title="Tools">🔧</a></td>
|
||||
<td align="center"><a href="https://github.com/Vetlix"><img src="https://avatars.githubusercontent.com/u/31412314?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vetlix</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Vetlix" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/ethamitc"><img src="https://avatars.githubusercontent.com/u/27776796?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ethan Mitchell</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=ethamitc" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/noftaly"><img src="https://avatars.githubusercontent.com/u/34779161?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Elliot</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=noftaly" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://jurien.dev"><img src="https://avatars.githubusercontent.com/u/5418114?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jurien Hamaker</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=jurienhamaker" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://fanoulis.dev/"><img src="https://avatars.githubusercontent.com/u/38255093?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Charalampos Fanoulis</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=cfanoulis" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/apps/dependabot"><img src="https://avatars.githubusercontent.com/in/29110?v=4?s=100" width="100px;" alt=""/><br /><sub><b>dependabot[bot]</b></sub></a><br /><a href="#maintenance-dependabot[bot]" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://kaname.netlify.app/"><img src="https://avatars.githubusercontent.com/u/56084970?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kaname</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=kaname-png" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/nandhagk"><img src="https://avatars.githubusercontent.com/u/62976649?v=4?s=100" width="100px;" alt=""/><br /><sub><b>nandhagk</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/issues?q=author%3Anandhagk" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://megatank58.me/"><img src="https://avatars.githubusercontent.com/u/51410502?v=4?s=100" width="100px;" alt=""/><br /><sub><b>megatank58</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=megatank58" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/UndiedGamer"><img src="https://avatars.githubusercontent.com/u/84702365?v=4?s=100" width="100px;" alt=""/><br /><sub><b>UndiedGamer</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=UndiedGamer" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/Lioness100"><img src="https://avatars.githubusercontent.com/u/65814829?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Lioness100</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Lioness100" title="Documentation">📖</a> <a href="https://github.com/sapphiredev/utilities/commits?author=Lioness100" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://gitlab.com/DavidPH/"><img src="https://avatars.githubusercontent.com/u/44669930?v=4?s=100" width="100px;" alt=""/><br /><sub><b>David</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=DavidPHH" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/apps/renovate"><img src="https://avatars.githubusercontent.com/in/2740?v=4?s=100" width="100px;" alt=""/><br /><sub><b>renovate[bot]</b></sub></a><br /><a href="#maintenance-renovate[bot]" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://renovate.whitesourcesoftware.com/"><img src="https://avatars.githubusercontent.com/u/25180681?v=4?s=100" width="100px;" alt=""/><br /><sub><b>WhiteSource Renovate</b></sub></a><br /><a href="#maintenance-renovate-bot" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://fc5570.me/"><img src="https://avatars.githubusercontent.com/u/68158483?v=4?s=100" width="100px;" alt=""/><br /><sub><b>FC</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=FC5570" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/Tokipudi"><img src="https://avatars.githubusercontent.com/u/29551076?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jérémy de Saint Denis</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Tokipudi" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/ItsMrCube"><img src="https://avatars.githubusercontent.com/u/25201357?v=4?s=100" width="100px;" alt=""/><br /><sub><b>MrCube</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=ItsMrCube" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/bitomic"><img src="https://avatars.githubusercontent.com/u/35199700?v=4?s=100" width="100px;" alt=""/><br /><sub><b>bitomic</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=bitomic" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://c43721.dev/"><img src="https://avatars.githubusercontent.com/u/55610086?v=4?s=100" width="100px;" alt=""/><br /><sub><b>c43721</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=c43721" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://commandtechno.com/"><img src="https://avatars.githubusercontent.com/u/68407783?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Commandtechno</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Commandtechno" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/dhruv-kaushikk"><img src="https://avatars.githubusercontent.com/u/73697546?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aura</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=dhruv-kaushikk" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://axis.moe/"><img src="https://avatars.githubusercontent.com/u/54381371?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jonathan</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=axisiscool" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/imranbarbhuiya"><img src="https://avatars.githubusercontent.com/u/74945038?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Parbez</b></sub></a><br /><a href="#maintenance-imranbarbhuiya" title="Maintenance">🚧</a></td>
|
||||
<td align="center"><a href="https://github.com/NotKaskus"><img src="https://avatars.githubusercontent.com/u/75168528?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Paul Andrew</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=NotKaskus" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://linktr.ee/mzato0001"><img src="https://avatars.githubusercontent.com/u/62367547?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mzato</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Mzato0001" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/issues?q=author%3AMzato0001" title="Bug reports">🐛</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/MajesticString"><img src="https://avatars.githubusercontent.com/u/66224939?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Harry Allen</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=MajesticString" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/EvolutionX-10"><img src="https://avatars.githubusercontent.com/u/85353424?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Evo</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=EvolutionX-10" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://enes.ovh/"><img src="https://avatars.githubusercontent.com/u/61084101?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Enes Genç</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=enxg" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/muchnameless"><img src="https://avatars.githubusercontent.com/u/12682826?v=4?s=100" width="100px;" alt=""/><br /><sub><b>muchnameless</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=muchnameless" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/r-priyam"><img src="https://avatars.githubusercontent.com/u/50884372?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Priyam</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=r-priyam" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/legendhimslef"><img src="https://avatars.githubusercontent.com/u/69213593?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Voxelli</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=legendhimslef" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/CitTheDev"><img src="https://avatars.githubusercontent.com/u/94020875?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Cit The Dev</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=CitTheDev" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://www.goestav.com/"><img src="https://avatars.githubusercontent.com/u/27970303?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Goestav</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=goestav" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/didinele"><img src="https://avatars.githubusercontent.com/u/27137376?v=4?s=100" width="100px;" alt=""/><br /><sub><b>DD</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=didinele" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://steamcommunity.com/id/06000208"><img src="https://avatars.githubusercontent.com/u/52764066?v=4?s=100" width="100px;" alt=""/><br /><sub><b>amber</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=06000208" title="Code">💻</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<!-- markdownlint-restore -->
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
||||
|
||||
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
|
@ -1,149 +0,0 @@
|
||||
/**
|
||||
* 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 };
|
@ -1,112 +0,0 @@
|
||||
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
|
File diff suppressed because one or more lines are too long
@ -1,107 +0,0 @@
|
||||
'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
|
File diff suppressed because one or more lines are too long
@ -1,103 +0,0 @@
|
||||
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
|
File diff suppressed because one or more lines are too long
@ -1,67 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
[![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.
|
||||
|
@ -1,30 +0,0 @@
|
||||
/**
|
||||
* Read-only token
|
||||
* See https://github.com/Borewit/strtok3 for more information
|
||||
*/
|
||||
export interface IGetToken<Value, Array extends Uint8Array = Uint8Array> {
|
||||
|
||||
/**
|
||||
* 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<Value, Array extends Uint8Array = Uint8Array> extends IGetToken<Value, Array> {
|
||||
/**
|
||||
* 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
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
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
|
@ -1,16 +0,0 @@
|
||||
# Installation
|
||||
> `npm install --save @types/node`
|
||||
|
||||
# Summary
|
||||
This package contains type definitions for Node.js (https://nodejs.org/).
|
||||
|
||||
# Details
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
|
||||
|
||||
### Additional Details
|
||||
* Last updated: Tue, 28 Mar 2023 21:33:10 GMT
|
||||
* Dependencies: none
|
||||
* Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require`, `structuredClone`
|
||||
|
||||
# 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), [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), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky).
|
@ -1,961 +0,0 @@
|
||||
/**
|
||||
* The `assert` module provides a set of assertion functions for verifying
|
||||
* invariants.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v18.0.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<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func;
|
||||
/**
|
||||
* Example:
|
||||
*
|
||||
* ```js
|
||||
* import assert from 'node:assert';
|
||||
*
|
||||
* const tracker = new assert.CallTracker();
|
||||
*
|
||||
* function func() {}
|
||||
* const callsfunc = tracker.calls(func);
|
||||
* callsfunc(1, 2, 3);
|
||||
*
|
||||
* assert.deepStrictEqual(tracker.getCalls(callsfunc),
|
||||
* [{ thisArg: this, arguments: [1, 2, 3 ] }]);
|
||||
* ```
|
||||
*
|
||||
* @since v18.8.0, v16.18.0
|
||||
* @params fn
|
||||
* @returns An Array with the calls to a tracked function.
|
||||
*/
|
||||
getCalls(fn: Function): CallTrackerCall[];
|
||||
/**
|
||||
* 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[];
|
||||
/**
|
||||
* Reset calls of the call tracker.
|
||||
* If a tracked function is passed as an argument, the calls will be reset for it.
|
||||
* If no arguments are passed, all tracked functions will be reset.
|
||||
*
|
||||
* ```js
|
||||
* import assert from 'node:assert';
|
||||
*
|
||||
* const tracker = new assert.CallTracker();
|
||||
*
|
||||
* function func() {}
|
||||
* const callsfunc = tracker.calls(func);
|
||||
*
|
||||
* callsfunc();
|
||||
* // Tracker was called once
|
||||
* tracker.getCalls(callsfunc).length === 1;
|
||||
*
|
||||
* tracker.reset(callsfunc);
|
||||
* tracker.getCalls(callsfunc).length === 0;
|
||||
* ```
|
||||
*
|
||||
* @since v18.8.0, v16.18.0
|
||||
* @param fn a tracked function to reset.
|
||||
*/
|
||||
reset(fn?: Function): void;
|
||||
/**
|
||||
* 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 CallTrackerCall {
|
||||
thisArg: object;
|
||||
arguments: unknown[];
|
||||
}
|
||||
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 [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled
|
||||
* and treated as being identical if 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 [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is
|
||||
* specially handled and treated as being identical if 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 [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
|
||||
*
|
||||
* ```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<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
|
||||
/**
|
||||
* Tests strict inequality between the `actual` and `expected` parameters as
|
||||
* determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
|
||||
*
|
||||
* ```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<T>(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<unknown>) | Promise<unknown>, message?: string | Error): Promise<void>;
|
||||
function rejects(block: (() => Promise<unknown>) | Promise<unknown>, error: AssertPredicate, message?: string | Error): Promise<void>;
|
||||
/**
|
||||
* 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<unknown>) | Promise<unknown>, message?: string | Error): Promise<void>;
|
||||
function doesNotReject(block: (() => Promise<unknown>) | Promise<unknown>, error: AssertPredicate, message?: string | Error): Promise<void>;
|
||||
/**
|
||||
* 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<typeof assert, 'equal' | 'notEqual' | 'deepEqual' | 'notDeepEqual' | 'ok' | 'strictEqual' | 'deepStrictEqual' | 'ifError' | 'strict'> & {
|
||||
(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;
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
declare module 'assert/strict' {
|
||||
import { strict } from 'node:assert';
|
||||
export = strict;
|
||||
}
|
||||
declare module 'node:assert/strict' {
|
||||
import { strict } from 'node:assert';
|
||||
export = strict;
|
||||
}
|
@ -1,513 +0,0 @@
|
||||
/**
|
||||
* 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/v18.0.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 v9.3.0)
|
||||
*/
|
||||
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<Func extends (this: ThisArg, ...args: any[]) => 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<Func extends (...args: any[]) => 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<This, Result>(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;
|
||||
}
|
||||
interface AsyncLocalStorageOptions<T> {
|
||||
/**
|
||||
* Optional callback invoked before a store is propagated to a new async resource.
|
||||
* Returning `true` allows propagation, returning `false` avoids it. Default is to propagate always.
|
||||
* @param type The type of async event.
|
||||
* @param store The current store.
|
||||
* @since v18.13.0
|
||||
*/
|
||||
onPropagate?: ((type: string, store: T) => boolean) | undefined;
|
||||
}
|
||||
/**
|
||||
* 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's data.
|
||||
* @since v13.10.0, v12.17.0
|
||||
*/
|
||||
class AsyncLocalStorage<T> {
|
||||
constructor(options?: AsyncLocalStorageOptions<T>);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* The store is accessible to any 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
|
||||
* setTimeout(() => {
|
||||
* asyncLocalStorage.getStore(); // Returns the store object
|
||||
* }, 200);
|
||||
* throw new Error();
|
||||
* });
|
||||
* } catch (e) {
|
||||
* asyncLocalStorage.getStore(); // Returns undefined
|
||||
* // The error will be caught here
|
||||
* }
|
||||
* ```
|
||||
* @since v13.10.0, v12.17.0
|
||||
*/
|
||||
run<R, TArgs extends any[]>(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<R, TArgs extends any[]>(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';
|
||||
}
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,18 +0,0 @@
|
||||
/** @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;
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -1,545 +0,0 @@
|
||||
/**
|
||||
* 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/v18.0.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): this;
|
||||
bind(port?: number, callback?: () => void): this;
|
||||
bind(callback?: () => void): this;
|
||||
bind(options: BindOptions, callback?: () => void): this;
|
||||
/**
|
||||
* 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): this;
|
||||
/**
|
||||
* 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 nullish, `'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<any>, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
|
||||
send(msg: string | Uint8Array | ReadonlyArray<any>, port?: number, callback?: (error: Error | null, bytes: number) => void): void;
|
||||
send(msg: string | Uint8Array | ReadonlyArray<any>, 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): boolean;
|
||||
/**
|
||||
* 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): number;
|
||||
/**
|
||||
* 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 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): 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, 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';
|
||||
}
|
@ -1,192 +0,0 @@
|
||||
/**
|
||||
* 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/v18.0.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
|
||||
* }
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param name The channel name
|
||||
* @return If there are active subscribers
|
||||
*/
|
||||
function hasSubscribers(name: string | symbol): 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');
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param name The channel name
|
||||
* @return The named channel object
|
||||
*/
|
||||
function channel(name: string | symbol): Channel;
|
||||
type ChannelListener = (message: unknown, name: string | symbol) => void;
|
||||
/**
|
||||
* 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';
|
||||
*
|
||||
* diagnostics_channel.subscribe('my-channel', (message, name) => {
|
||||
* // Received data
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @since v18.7.0, v16.17.0
|
||||
* @param name The channel name
|
||||
* @param onMessage The handler to receive channel messages
|
||||
*/
|
||||
function subscribe(name: string | symbol, onMessage: ChannelListener): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with diagnostics_channel.subscribe(name, onMessage).
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'diagnostics_channel';
|
||||
*
|
||||
* function onMessage(message, name) {
|
||||
* // Received data
|
||||
* }
|
||||
*
|
||||
* diagnostics_channel.subscribe('my-channel', onMessage);
|
||||
*
|
||||
* diagnostics_channel.unsubscribe('my-channel', onMessage);
|
||||
* ```
|
||||
*
|
||||
* @since v18.7.0, v16.17.0
|
||||
* @param name The channel name
|
||||
* @param onMessage The previous subscribed handler to remove
|
||||
* @returns `true` if the handler was found, `false` otherwise
|
||||
*/
|
||||
function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean;
|
||||
/**
|
||||
* 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.
|
||||
* @since v15.1.0, v14.17.0
|
||||
*/
|
||||
class Channel {
|
||||
readonly name: string | symbol;
|
||||
/**
|
||||
* 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
|
||||
* }
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
*/
|
||||
readonly hasSubscribers: boolean;
|
||||
private constructor(name: string | symbol);
|
||||
/**
|
||||
* Publish a message to any subscribers to the channel. This will
|
||||
* trigger message handlers synchronously so they will execute within
|
||||
* the same context.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.publish({
|
||||
* some: 'message'
|
||||
* });
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param message The message to send to the channel subscribers
|
||||
*/
|
||||
publish(message: unknown): void;
|
||||
/**
|
||||
* 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
|
||||
* });
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @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);
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param onMessage The previous subscribed handler to remove
|
||||
* @return `true` if the handler was found, `false` otherwise.
|
||||
*/
|
||||
unsubscribe(onMessage: ChannelListener): void;
|
||||
}
|
||||
}
|
||||
declare module 'node:diagnostics_channel' {
|
||||
export * from 'diagnostics_channel';
|
||||
}
|
@ -1,126 +0,0 @@
|
||||
export {}; // Don't export anything!
|
||||
|
||||
//// DOM-like Events
|
||||
// NB: The Event / EventTarget / EventListener implementations below were copied
|
||||
// from lib.dom.d.ts, then edited to reflect Node's documentation at
|
||||
// https://nodejs.org/api/events.html#class-eventtarget.
|
||||
// Please read that link to understand important implementation differences.
|
||||
|
||||
// This conditional type will be the existing global Event in a browser, or
|
||||
// the copy below in a Node environment.
|
||||
type __Event = typeof globalThis extends { onmessage: any, Event: any }
|
||||
? {}
|
||||
: {
|
||||
/** This is not used in Node.js and is provided purely for completeness. */
|
||||
readonly bubbles: boolean;
|
||||
/** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */
|
||||
cancelBubble: () => void;
|
||||
/** True if the event was created with the cancelable option */
|
||||
readonly cancelable: boolean;
|
||||
/** This is not used in Node.js and is provided purely for completeness. */
|
||||
readonly composed: boolean;
|
||||
/** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */
|
||||
composedPath(): [EventTarget?]
|
||||
/** Alias for event.target. */
|
||||
readonly currentTarget: EventTarget | null;
|
||||
/** Is true if cancelable is true and event.preventDefault() has been called. */
|
||||
readonly defaultPrevented: boolean;
|
||||
/** This is not used in Node.js and is provided purely for completeness. */
|
||||
readonly eventPhase: 0 | 2;
|
||||
/** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */
|
||||
readonly isTrusted: boolean;
|
||||
/** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */
|
||||
preventDefault(): void;
|
||||
/** This is not used in Node.js and is provided purely for completeness. */
|
||||
returnValue: boolean;
|
||||
/** Alias for event.target. */
|
||||
readonly srcElement: EventTarget | null;
|
||||
/** Stops the invocation of event listeners after the current one completes. */
|
||||
stopImmediatePropagation(): void;
|
||||
/** This is not used in Node.js and is provided purely for completeness. */
|
||||
stopPropagation(): void;
|
||||
/** The `EventTarget` dispatching the event */
|
||||
readonly target: EventTarget | null;
|
||||
/** The millisecond timestamp when the Event object was created. */
|
||||
readonly timeStamp: number;
|
||||
/** Returns the type of event, e.g. "click", "hashchange", or "submit". */
|
||||
readonly type: string;
|
||||
};
|
||||
|
||||
// See comment above explaining conditional type
|
||||
type __EventTarget = typeof globalThis extends { onmessage: any, EventTarget: any }
|
||||
? {}
|
||||
: {
|
||||
/**
|
||||
* Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value.
|
||||
*
|
||||
* If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched.
|
||||
*
|
||||
* The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification.
|
||||
* Specifically, the `capture` option is used as part of the key when registering a `listener`.
|
||||
* Any individual `listener` may be added once with `capture = false`, and once with `capture = true`.
|
||||
*/
|
||||
addEventListener(
|
||||
type: string,
|
||||
listener: EventListener | EventListenerObject,
|
||||
options?: AddEventListenerOptions | boolean,
|
||||
): void;
|
||||
/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */
|
||||
dispatchEvent(event: Event): boolean;
|
||||
/** Removes the event listener in target's event listener list with the same type, callback, and options. */
|
||||
removeEventListener(
|
||||
type: string,
|
||||
listener: EventListener | EventListenerObject,
|
||||
options?: EventListenerOptions | boolean,
|
||||
): void;
|
||||
};
|
||||
|
||||
interface EventInit {
|
||||
bubbles?: boolean;
|
||||
cancelable?: boolean;
|
||||
composed?: boolean;
|
||||
}
|
||||
|
||||
interface EventListenerOptions {
|
||||
/** Not directly used by Node.js. Added for API completeness. Default: `false`. */
|
||||
capture?: boolean;
|
||||
}
|
||||
|
||||
interface AddEventListenerOptions extends EventListenerOptions {
|
||||
/** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */
|
||||
once?: boolean;
|
||||
/** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */
|
||||
passive?: boolean;
|
||||
}
|
||||
|
||||
interface EventListener {
|
||||
(evt: Event): void;
|
||||
}
|
||||
|
||||
interface EventListenerObject {
|
||||
handleEvent(object: Event): void;
|
||||
}
|
||||
|
||||
import {} from 'events'; // Make this an ambient declaration
|
||||
declare global {
|
||||
/** An event which takes place in the DOM. */
|
||||
interface Event extends __Event {}
|
||||
var Event: typeof globalThis extends { onmessage: any, Event: infer T }
|
||||
? T
|
||||
: {
|
||||
prototype: __Event;
|
||||
new (type: string, eventInitDict?: EventInit): __Event;
|
||||
};
|
||||
|
||||
/**
|
||||
* EventTarget is a DOM interface implemented by objects that can
|
||||
* receive events and may have listeners for them.
|
||||
*/
|
||||
interface EventTarget extends __EventTarget {}
|
||||
var EventTarget: typeof globalThis extends { onmessage: any, EventTarget: infer T }
|
||||
? T
|
||||
: {
|
||||
prototype: __EventTarget;
|
||||
new (): __EventTarget;
|
||||
};
|
||||
}
|
@ -1,170 +0,0 @@
|
||||
/**
|
||||
* **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/v18.0.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<EventEmitter | NodeJS.Timer>;
|
||||
/**
|
||||
* 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<T>(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<T extends Function>(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<T extends Function>(callback: T): T;
|
||||
}
|
||||
function create(): Domain;
|
||||
}
|
||||
declare module 'node:domain' {
|
||||
export * from 'domain';
|
||||
}
|
@ -1,678 +0,0 @@
|
||||
/**
|
||||
* 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/v18.0.0/lib/events.js)
|
||||
*/
|
||||
declare module 'events' {
|
||||
// NOTE: This class is in the docs but is **not actually exported** by Node.
|
||||
// If https://github.com/nodejs/node/issues/39903 gets resolved and Node
|
||||
// actually starts exporting the class, uncomment below.
|
||||
|
||||
// import { EventListener, EventListenerObject } from '__dom-events';
|
||||
// /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */
|
||||
// interface NodeEventTarget extends EventTarget {
|
||||
// /**
|
||||
// * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API.
|
||||
// * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget.
|
||||
// */
|
||||
// addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
|
||||
// /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */
|
||||
// eventNames(): string[];
|
||||
// /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */
|
||||
// listenerCount(type: string): number;
|
||||
// /** Node.js-specific alias for `eventTarget.removeListener()`. */
|
||||
// off(type: string, listener: EventListener | EventListenerObject): this;
|
||||
// /** Node.js-specific alias for `eventTarget.addListener()`. */
|
||||
// on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
|
||||
// /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */
|
||||
// once(type: string, listener: EventListener | EventListenerObject): this;
|
||||
// /**
|
||||
// * Node.js-specific extension to the `EventTarget` class.
|
||||
// * If `type` is specified, removes all registered listeners for `type`,
|
||||
// * otherwise removes all registered listeners.
|
||||
// */
|
||||
// removeAllListeners(type: string): this;
|
||||
// /**
|
||||
// * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`.
|
||||
// * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`.
|
||||
// */
|
||||
// removeListener(type: string, listener: EventListener | EventListenerObject): this;
|
||||
// }
|
||||
|
||||
interface EventEmitterOptions {
|
||||
/**
|
||||
* Enables automatic capturing of promise rejection.
|
||||
*/
|
||||
captureRejections?: boolean | undefined;
|
||||
}
|
||||
// Any EventTarget with a Node-style `once` function
|
||||
interface _NodeEventTarget {
|
||||
once(eventName: string | symbol, listener: (...args: any[]) => void): this;
|
||||
}
|
||||
// Any EventTarget with a DOM-style `addEventListener`
|
||||
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);
|
||||
/**
|
||||
* Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
|
||||
* event or that is rejected if the `EventEmitter` emits `'error'` while waiting.
|
||||
* The `Promise` will resolve with an array of all the arguments emitted to the
|
||||
* given event.
|
||||
*
|
||||
* This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event
|
||||
* semantics and does not listen to the `'error'` event.
|
||||
*
|
||||
* ```js
|
||||
* const { once, EventEmitter } = require('events');
|
||||
*
|
||||
* async function run() {
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('myevent', 42);
|
||||
* });
|
||||
*
|
||||
* const [value] = await once(ee, 'myevent');
|
||||
* console.log(value);
|
||||
*
|
||||
* const err = new Error('kaboom');
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('error', err);
|
||||
* });
|
||||
*
|
||||
* try {
|
||||
* await once(ee, 'myevent');
|
||||
* } catch (err) {
|
||||
* console.log('error happened', err);
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* run();
|
||||
* ```
|
||||
*
|
||||
* The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the
|
||||
* '`error'` event itself, then it is treated as any other kind of event without
|
||||
* special handling:
|
||||
*
|
||||
* ```js
|
||||
* const { EventEmitter, once } = require('events');
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* once(ee, 'error')
|
||||
* .then(([err]) => console.log('ok', err.message))
|
||||
* .catch((err) => console.log('error', err.message));
|
||||
*
|
||||
* ee.emit('error', new Error('boom'));
|
||||
*
|
||||
* // Prints: ok boom
|
||||
* ```
|
||||
*
|
||||
* An `AbortSignal` can be used to cancel waiting for the event:
|
||||
*
|
||||
* ```js
|
||||
* const { EventEmitter, once } = require('events');
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
* const ac = new AbortController();
|
||||
*
|
||||
* async function foo(emitter, event, signal) {
|
||||
* try {
|
||||
* await once(emitter, event, { signal });
|
||||
* console.log('event emitted!');
|
||||
* } catch (error) {
|
||||
* if (error.name === 'AbortError') {
|
||||
* console.error('Waiting for the event was canceled!');
|
||||
* } else {
|
||||
* console.error('There was an error', error.message);
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* foo(ee, 'foo', ac.signal);
|
||||
* ac.abort(); // Abort waiting for the event
|
||||
* ee.emit('foo'); // Prints: Waiting for the event was canceled!
|
||||
* ```
|
||||
* @since v11.13.0, v10.16.0
|
||||
*/
|
||||
static once(emitter: _NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise<any[]>;
|
||||
static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
|
||||
/**
|
||||
* ```js
|
||||
* const { on, EventEmitter } = require('events');
|
||||
*
|
||||
* (async () => {
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* // Emit later on
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('foo', 'bar');
|
||||
* ee.emit('foo', 42);
|
||||
* });
|
||||
*
|
||||
* for await (const event of on(ee, 'foo')) {
|
||||
* // The execution of this inner block is synchronous and it
|
||||
* // processes one event at a time (even with await). Do not use
|
||||
* // if concurrent execution is required.
|
||||
* console.log(event); // prints ['bar'] [42]
|
||||
* }
|
||||
* // Unreachable here
|
||||
* })();
|
||||
* ```
|
||||
*
|
||||
* Returns an `AsyncIterator` that iterates `eventName` events. It will throw
|
||||
* if the `EventEmitter` emits `'error'`. It removes all listeners when
|
||||
* exiting the loop. The `value` returned by each iteration is an array
|
||||
* composed of the emitted event arguments.
|
||||
*
|
||||
* An `AbortSignal` can be used to cancel waiting on events:
|
||||
*
|
||||
* ```js
|
||||
* const { on, EventEmitter } = require('events');
|
||||
* const ac = new AbortController();
|
||||
*
|
||||
* (async () => {
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* // Emit later on
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('foo', 'bar');
|
||||
* ee.emit('foo', 42);
|
||||
* });
|
||||
*
|
||||
* for await (const event of on(ee, 'foo', { signal: ac.signal })) {
|
||||
* // The execution of this inner block is synchronous and it
|
||||
* // processes one event at a time (even with await). Do not use
|
||||
* // if concurrent execution is required.
|
||||
* console.log(event); // prints ['bar'] [42]
|
||||
* }
|
||||
* // Unreachable here
|
||||
* })();
|
||||
*
|
||||
* process.nextTick(() => ac.abort());
|
||||
* ```
|
||||
* @since v13.6.0, v12.16.0
|
||||
* @param eventName The name of the event being listened for
|
||||
* @return that iterates `eventName` events emitted by the `emitter`
|
||||
*/
|
||||
static on(emitter: NodeJS.EventEmitter, eventName: string, options?: StaticEventEmitterOptions): AsyncIterableIterator<any>;
|
||||
/**
|
||||
* A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`.
|
||||
*
|
||||
* ```js
|
||||
* const { EventEmitter, listenerCount } = require('events');
|
||||
* const myEmitter = new EventEmitter();
|
||||
* myEmitter.on('event', () => {});
|
||||
* myEmitter.on('event', () => {});
|
||||
* console.log(listenerCount(myEmitter, 'event'));
|
||||
* // Prints: 2
|
||||
* ```
|
||||
* @since v0.9.12
|
||||
* @deprecated Since v3.2.0 - Use `listenerCount` instead.
|
||||
* @param emitter The emitter to query
|
||||
* @param eventName The event name
|
||||
*/
|
||||
static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
|
||||
/**
|
||||
* Returns a copy of the array of listeners for the event named `eventName`.
|
||||
*
|
||||
* For `EventEmitter`s this behaves exactly the same as calling `.listeners` on
|
||||
* the emitter.
|
||||
*
|
||||
* For `EventTarget`s this is the only way to get the event listeners for the
|
||||
* event target. This is useful for debugging and diagnostic purposes.
|
||||
*
|
||||
* ```js
|
||||
* const { getEventListeners, EventEmitter } = require('events');
|
||||
*
|
||||
* {
|
||||
* const ee = new EventEmitter();
|
||||
* const listener = () => console.log('Events are fun');
|
||||
* ee.on('foo', listener);
|
||||
* getEventListeners(ee, 'foo'); // [listener]
|
||||
* }
|
||||
* {
|
||||
* const et = new EventTarget();
|
||||
* const listener = () => console.log('Events are fun');
|
||||
* et.addEventListener('foo', listener);
|
||||
* getEventListeners(et, 'foo'); // [listener]
|
||||
* }
|
||||
* ```
|
||||
* @since v15.2.0, v14.17.0
|
||||
*/
|
||||
static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
|
||||
/**
|
||||
* ```js
|
||||
* const {
|
||||
* setMaxListeners,
|
||||
* EventEmitter
|
||||
* } = require('events');
|
||||
*
|
||||
* const target = new EventTarget();
|
||||
* const emitter = new EventEmitter();
|
||||
*
|
||||
* setMaxListeners(5, target, emitter);
|
||||
* ```
|
||||
* @since v15.4.0
|
||||
* @param n A non-negative number. The maximum number of listeners per `EventTarget` event.
|
||||
* @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter}
|
||||
* objects.
|
||||
*/
|
||||
static setMaxListeners(n?: number, ...eventTargets: Array<_DOMEventTarget | NodeJS.EventEmitter>): void;
|
||||
/**
|
||||
* 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<string | symbol>;
|
||||
}
|
||||
}
|
||||
}
|
||||
export = EventEmitter;
|
||||
}
|
||||
declare module 'node:events' {
|
||||
import events = require('events');
|
||||
export = events;
|
||||
}
|
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue