From 41ae7ff4bd63ddda773656be3ed65dfe080c2d29 Mon Sep 17 00:00:00 2001 From: Lukian Date: Tue, 20 Jun 2023 15:28:07 +0200 Subject: [PATCH] commit --- node_modules/.package-lock.json | 291 +- node_modules/@discordjs/builders/CHANGELOG.md | 64 + node_modules/@discordjs/builders/README.md | 19 +- .../@discordjs/builders/dist/index.d.ts | 1469 +++++---- .../@discordjs/builders/dist/index.js | 1275 ++++++-- .../@discordjs/builders/dist/index.js.map | 2 +- .../@discordjs/builders/dist/index.mjs | 1247 +++++++- .../@discordjs/builders/dist/index.mjs.map | 2 +- node_modules/@discordjs/builders/package.json | 48 +- .../@discordjs/collection/CHANGELOG.md | 38 + node_modules/@discordjs/collection/README.md | 11 +- .../@discordjs/collection/dist/index.js | 262 +- .../@discordjs/collection/dist/index.js.map | 2 +- .../@discordjs/collection/dist/index.mjs | 262 +- .../@discordjs/collection/dist/index.mjs.map | 2 +- .../@discordjs/collection/package.json | 36 +- .../@discordjs/formatters/CHANGELOG.md | 42 + node_modules/@discordjs/formatters/LICENSE | 191 ++ node_modules/@discordjs/formatters/README.md | 80 + .../@discordjs/formatters/dist/index.d.ts | 511 +++ .../@discordjs/formatters/dist/index.js | 393 +++ .../@discordjs/formatters/dist/index.js.map | 1 + .../@discordjs/formatters/dist/index.mjs | 335 ++ .../@discordjs/formatters/dist/index.mjs.map | 1 + .../@discordjs/formatters/package.json | 71 + node_modules/@discordjs/rest/CHANGELOG.md | 44 + node_modules/@discordjs/rest/README.md | 17 +- node_modules/@discordjs/rest/dist/index.d.ts | 30 +- node_modules/@discordjs/rest/dist/index.js | 737 ++++- .../@discordjs/rest/dist/index.js.map | 2 +- node_modules/@discordjs/rest/dist/index.mjs | 730 ++++- .../@discordjs/rest/dist/index.mjs.map | 2 +- node_modules/@discordjs/rest/package.json | 50 +- node_modules/@discordjs/util/CHANGELOG.md | 48 + node_modules/@discordjs/util/README.md | 51 +- node_modules/@discordjs/util/dist/index.d.ts | 52 +- node_modules/@discordjs/util/dist/index.js | 24 +- .../@discordjs/util/dist/index.js.map | 2 +- node_modules/@discordjs/util/dist/index.mjs | 23 +- .../@discordjs/util/dist/index.mjs.map | 2 +- node_modules/@discordjs/util/package.json | 40 +- node_modules/@discordjs/ws/CHANGELOG.md | 193 ++ node_modules/@discordjs/ws/LICENSE | 191 ++ node_modules/@discordjs/ws/README.md | 196 ++ .../@discordjs/ws/dist/defaultWorker.d.ts | 2 + .../@discordjs/ws/dist/defaultWorker.js | 982 ++++++ .../@discordjs/ws/dist/defaultWorker.js.map | 1 + .../@discordjs/ws/dist/defaultWorker.mjs | 964 ++++++ .../@discordjs/ws/dist/defaultWorker.mjs.map | 1 + node_modules/@discordjs/ws/dist/index.d.ts | 667 ++++ node_modules/@discordjs/ws/dist/index.js | 1409 +++++++++ node_modules/@discordjs/ws/dist/index.js.map | 1 + node_modules/@discordjs/ws/dist/index.mjs | 1373 ++++++++ node_modules/@discordjs/ws/dist/index.mjs.map | 1 + node_modules/@discordjs/ws/package.json | 99 + .../@sapphire/shapeshift/CHANGELOG.md | 29 + node_modules/@sapphire/shapeshift/README.md | 35 +- .../@sapphire/shapeshift/dist/index.d.ts | 8 +- .../@sapphire/shapeshift/dist/index.global.js | 40 +- .../shapeshift/dist/index.global.js.map | 2 +- .../@sapphire/shapeshift/dist/index.js | 42 +- .../@sapphire/shapeshift/dist/index.js.map | 2 +- .../@sapphire/shapeshift/dist/index.mjs | 34 +- .../@sapphire/shapeshift/dist/index.mjs.map | 2 +- .../@sapphire/shapeshift/package.json | 70 +- node_modules/@sapphire/snowflake/CHANGELOG.md | 31 + node_modules/@sapphire/snowflake/README.md | 80 +- .../@sapphire/snowflake/dist/index.d.ts | 59 +- .../@sapphire/snowflake/dist/index.global.js | 200 +- .../snowflake/dist/index.global.js.map | 2 +- .../@sapphire/snowflake/dist/index.js | 200 +- .../@sapphire/snowflake/dist/index.js.map | 2 +- .../@sapphire/snowflake/dist/index.mjs | 199 +- .../@sapphire/snowflake/dist/index.mjs.map | 2 +- node_modules/@sapphire/snowflake/package.json | 16 +- node_modules/@types/node/README.md | 2 +- node_modules/@types/node/assert.d.ts | 161 +- node_modules/@types/node/async_hooks.d.ts | 103 +- node_modules/@types/node/buffer.d.ts | 302 +- node_modules/@types/node/child_process.d.ts | 136 +- node_modules/@types/node/cluster.d.ts | 28 +- node_modules/@types/node/console.d.ts | 10 +- node_modules/@types/node/crypto.d.ts | 478 +-- node_modules/@types/node/dgram.d.ts | 30 +- .../@types/node/diagnostics_channel.d.ts | 70 +- node_modules/@types/node/dns.d.ts | 43 +- node_modules/@types/node/dns/promises.d.ts | 56 +- node_modules/@types/node/domain.d.ts | 8 +- node_modules/@types/node/events.d.ts | 174 +- node_modules/@types/node/fs.d.ts | 326 +- node_modules/@types/node/fs/promises.d.ts | 146 +- node_modules/@types/node/globals.d.ts | 7 +- node_modules/@types/node/http.d.ts | 331 +- node_modules/@types/node/http2.d.ts | 89 +- node_modules/@types/node/https.d.ts | 205 +- node_modules/@types/node/index.d.ts | 2 +- node_modules/@types/node/inspector.d.ts | 13 +- node_modules/@types/node/module.d.ts | 10 +- node_modules/@types/node/net.d.ts | 61 +- node_modules/@types/node/os.d.ts | 43 +- node_modules/@types/node/package.json | 6 +- node_modules/@types/node/path.d.ts | 8 +- node_modules/@types/node/perf_hooks.d.ts | 43 +- node_modules/@types/node/process.d.ts | 146 +- node_modules/@types/node/punycode.d.ts | 2 +- node_modules/@types/node/querystring.d.ts | 10 +- node_modules/@types/node/readline.d.ts | 191 +- .../@types/node/readline/promises.d.ts | 128 +- node_modules/@types/node/repl.d.ts | 40 +- node_modules/@types/node/stream.d.ts | 1789 ++++++----- .../@types/node/stream/consumers.d.ts | 2 +- node_modules/@types/node/string_decoder.d.ts | 12 +- node_modules/@types/node/test.d.ts | 948 +++++- node_modules/@types/node/timers.d.ts | 129 +- node_modules/@types/node/timers/promises.d.ts | 6 +- node_modules/@types/node/tls.d.ts | 159 +- node_modules/@types/node/trace_events.d.ts | 29 +- node_modules/@types/node/ts4.8/assert.d.ts | 161 +- .../@types/node/ts4.8/async_hooks.d.ts | 103 +- node_modules/@types/node/ts4.8/buffer.d.ts | 303 +- .../@types/node/ts4.8/child_process.d.ts | 136 +- node_modules/@types/node/ts4.8/cluster.d.ts | 28 +- node_modules/@types/node/ts4.8/console.d.ts | 10 +- node_modules/@types/node/ts4.8/crypto.d.ts | 473 +-- node_modules/@types/node/ts4.8/dgram.d.ts | 30 +- .../node/ts4.8/diagnostics_channel.d.ts | 70 +- node_modules/@types/node/ts4.8/dns.d.ts | 43 +- .../@types/node/ts4.8/dns/promises.d.ts | 56 +- node_modules/@types/node/ts4.8/domain.d.ts | 8 +- node_modules/@types/node/ts4.8/events.d.ts | 174 +- node_modules/@types/node/ts4.8/fs.d.ts | 326 +- .../@types/node/ts4.8/fs/promises.d.ts | 143 +- node_modules/@types/node/ts4.8/globals.d.ts | 31 +- node_modules/@types/node/ts4.8/http.d.ts | 331 +- node_modules/@types/node/ts4.8/http2.d.ts | 89 +- node_modules/@types/node/ts4.8/https.d.ts | 205 +- node_modules/@types/node/ts4.8/inspector.d.ts | 13 +- node_modules/@types/node/ts4.8/module.d.ts | 10 +- node_modules/@types/node/ts4.8/net.d.ts | 63 +- node_modules/@types/node/ts4.8/os.d.ts | 43 +- node_modules/@types/node/ts4.8/path.d.ts | 8 +- .../@types/node/ts4.8/perf_hooks.d.ts | 43 +- node_modules/@types/node/ts4.8/process.d.ts | 146 +- node_modules/@types/node/ts4.8/punycode.d.ts | 2 +- .../@types/node/ts4.8/querystring.d.ts | 10 +- node_modules/@types/node/ts4.8/readline.d.ts | 191 +- .../@types/node/ts4.8/readline/promises.d.ts | 128 +- node_modules/@types/node/ts4.8/repl.d.ts | 40 +- node_modules/@types/node/ts4.8/stream.d.ts | 332 +- .../@types/node/ts4.8/stream/consumers.d.ts | 2 +- .../@types/node/ts4.8/string_decoder.d.ts | 12 +- node_modules/@types/node/ts4.8/test.d.ts | 948 +++++- node_modules/@types/node/ts4.8/timers.d.ts | 129 +- .../@types/node/ts4.8/timers/promises.d.ts | 6 +- node_modules/@types/node/ts4.8/tls.d.ts | 159 +- .../@types/node/ts4.8/trace_events.d.ts | 29 +- node_modules/@types/node/ts4.8/tty.d.ts | 14 +- node_modules/@types/node/ts4.8/url.d.ts | 88 +- node_modules/@types/node/ts4.8/util.d.ts | 330 +- node_modules/@types/node/ts4.8/v8.d.ts | 267 +- node_modules/@types/node/ts4.8/vm.d.ts | 449 ++- node_modules/@types/node/ts4.8/wasi.d.ts | 36 +- .../@types/node/ts4.8/worker_threads.d.ts | 72 +- node_modules/@types/node/ts4.8/zlib.d.ts | 22 +- node_modules/@types/node/tty.d.ts | 14 +- node_modules/@types/node/url.d.ts | 88 +- node_modules/@types/node/util.d.ts | 330 +- node_modules/@types/node/v8.d.ts | 267 +- node_modules/@types/node/vm.d.ts | 449 ++- node_modules/@types/node/wasi.d.ts | 36 +- node_modules/@types/node/worker_threads.d.ts | 72 +- node_modules/@types/node/zlib.d.ts | 22 +- node_modules/@types/ws/README.md | 2 +- node_modules/@types/ws/index.d.ts | 63 +- node_modules/@types/ws/package.json | 6 +- .../async_event_emitter/CHANGELOG.md | 63 + .../async_event_emitter/LICENSE.md | 24 + .../@vladfrangu/async_event_emitter/README.md | 51 + .../THIRD_PARTY_LICENSE.md} | 20 +- .../async_event_emitter/dist/index.d.ts | 57 + .../async_event_emitter/dist/index.global.js | 568 ++++ .../dist/index.global.js.map | 1 + .../async_event_emitter/dist/index.js | 571 ++++ .../async_event_emitter/dist/index.js.map | 1 + .../async_event_emitter/dist/index.mjs | 547 ++++ .../async_event_emitter/dist/index.mjs.map | 1 + .../async_event_emitter/package.json | 107 + .../node_modules => }/axios/CHANGELOG.md | 0 .../{openai/node_modules => }/axios/LICENSE | 0 .../{openai/node_modules => }/axios/README.md | 0 .../node_modules => }/axios/SECURITY.md | 0 .../node_modules => }/axios/UPGRADE_GUIDE.md | 0 .../node_modules => }/axios/dist/axios.js | 0 .../node_modules => }/axios/dist/axios.map | 0 .../node_modules => }/axios/dist/axios.min.js | 0 .../axios/dist/axios.min.map | 0 .../node_modules => }/axios/index.d.ts | 0 .../{openai/node_modules => }/axios/index.js | 0 .../axios/lib/adapters/README.md | 0 .../axios/lib/adapters/http.js | 0 .../axios/lib/adapters/xhr.js | 0 .../node_modules => }/axios/lib/axios.js | 0 .../axios/lib/cancel/Cancel.js | 0 .../axios/lib/cancel/CancelToken.js | 0 .../axios/lib/cancel/isCancel.js | 0 .../node_modules => }/axios/lib/core/Axios.js | 0 .../axios/lib/core/InterceptorManager.js | 0 .../axios/lib/core/README.md | 0 .../axios/lib/core/buildFullPath.js | 0 .../axios/lib/core/createError.js | 0 .../axios/lib/core/dispatchRequest.js | 0 .../axios/lib/core/enhanceError.js | 0 .../axios/lib/core/mergeConfig.js | 0 .../axios/lib/core/settle.js | 0 .../axios/lib/core/transformData.js | 0 .../axios/lib/defaults/index.js | 0 .../axios/lib/defaults/transitional.js | 0 .../node_modules => }/axios/lib/env/README.md | 0 .../node_modules => }/axios/lib/env/data.js | 0 .../axios/lib/helpers/README.md | 0 .../axios/lib/helpers/bind.js | 0 .../axios/lib/helpers/buildURL.js | 0 .../axios/lib/helpers/combineURLs.js | 0 .../axios/lib/helpers/cookies.js | 0 .../axios/lib/helpers/deprecatedMethod.js | 0 .../axios/lib/helpers/isAbsoluteURL.js | 0 .../axios/lib/helpers/isAxiosError.js | 0 .../axios/lib/helpers/isURLSameOrigin.js | 0 .../axios/lib/helpers/normalizeHeaderName.js | 0 .../axios/lib/helpers/parseHeaders.js | 0 .../axios/lib/helpers/spread.js | 0 .../axios/lib/helpers/toFormData.js | 0 .../axios/lib/helpers/validator.js | 0 .../node_modules => }/axios/lib/utils.js | 0 .../node_modules => }/axios/package.json | 0 .../node_modules => }/axios/tsconfig.json | 0 .../node_modules => }/axios/tslint.json | 0 node_modules/core-util-is/float.patch | 604 ---- node_modules/core-util-is/lib/util.js | 2 +- node_modules/core-util-is/package.json | 12 +- node_modules/core-util-is/test.js | 68 - .../discord-api-types/gateway/v10.d.ts | 234 +- .../discord-api-types/gateway/v10.d.ts.map | 2 +- .../discord-api-types/gateway/v10.js.map | 2 +- .../discord-api-types/gateway/v6.d.ts | 140 +- .../discord-api-types/gateway/v6.d.ts.map | 2 +- node_modules/discord-api-types/gateway/v6.js | 6 + .../discord-api-types/gateway/v6.js.map | 2 +- .../discord-api-types/gateway/v8.d.ts | 302 +- .../discord-api-types/gateway/v8.d.ts.map | 2 +- node_modules/discord-api-types/gateway/v8.js | 4 + .../discord-api-types/gateway/v8.js.map | 2 +- .../discord-api-types/gateway/v9.d.ts | 234 +- .../discord-api-types/gateway/v9.d.ts.map | 2 +- .../discord-api-types/gateway/v9.js.map | 2 +- node_modules/discord-api-types/globals.d.ts | 7 +- .../discord-api-types/globals.d.ts.map | 2 +- node_modules/discord-api-types/globals.js | 12 +- node_modules/discord-api-types/globals.js.map | 2 +- node_modules/discord-api-types/package.json | 92 +- .../discord-api-types/payloads/common.d.ts | 220 +- .../payloads/common.d.ts.map | 2 +- .../discord-api-types/payloads/common.js | 218 ++ .../discord-api-types/payloads/common.js.map | 2 +- .../discord-api-types/payloads/index.mjs | 1 + .../_chatInput/attachment.d.ts | 6 +- .../_chatInput/attachment.d.ts.map | 2 +- .../_applicationCommands/_chatInput/base.d.ts | 5 +- .../_chatInput/base.d.ts.map | 2 +- .../_chatInput/boolean.d.ts | 4 +- .../_chatInput/boolean.d.ts.map | 2 +- .../_chatInput/channel.d.ts | 6 +- .../_chatInput/channel.d.ts.map | 2 +- .../_chatInput/integer.d.ts | 2 +- .../_chatInput/integer.d.ts.map | 2 +- .../_chatInput/mentionable.d.ts | 6 +- .../_chatInput/mentionable.d.ts.map | 2 +- .../_chatInput/number.d.ts | 2 +- .../_chatInput/number.d.ts.map | 2 +- .../_applicationCommands/_chatInput/role.d.ts | 6 +- .../_chatInput/role.d.ts.map | 2 +- .../_chatInput/string.d.ts | 2 +- .../_chatInput/string.d.ts.map | 2 +- .../_chatInput/subcommand.d.ts | 2 +- .../_chatInput/subcommand.d.ts.map | 2 +- .../_applicationCommands/_chatInput/user.d.ts | 6 +- .../_chatInput/user.d.ts.map | 2 +- .../_applicationCommands/chatInput.d.ts | 20 +- .../_applicationCommands/chatInput.d.ts.map | 2 +- .../_applicationCommands/contextMenu.d.ts | 22 +- .../_applicationCommands/contextMenu.d.ts.map | 2 +- .../_applicationCommands/permissions.d.ts.map | 2 +- .../_applicationCommands/permissions.js | 1 + .../_applicationCommands/permissions.js.map | 2 +- .../_interactions/applicationCommands.d.ts | 15 +- .../applicationCommands.d.ts.map | 2 +- .../_interactions/applicationCommands.js.map | 2 +- .../v10/_interactions/autocomplete.d.ts | 6 +- .../v10/_interactions/autocomplete.d.ts.map | 2 +- .../payloads/v10/_interactions/base.d.ts | 22 +- .../payloads/v10/_interactions/base.d.ts.map | 2 +- .../v10/_interactions/messageComponents.d.ts | 18 +- .../_interactions/messageComponents.d.ts.map | 2 +- .../v10/_interactions/modalSubmit.d.ts | 6 +- .../v10/_interactions/modalSubmit.d.ts.map | 2 +- .../payloads/v10/_interactions/ping.d.ts | 2 +- .../payloads/v10/_interactions/ping.d.ts.map | 2 +- .../payloads/v10/_interactions/responses.d.ts | 6 +- .../v10/_interactions/responses.d.ts.map | 2 +- .../payloads/v10/application.d.ts | 22 +- .../payloads/v10/application.d.ts.map | 2 +- .../payloads/v10/application.js | 18 +- .../payloads/v10/application.js.map | 2 +- .../payloads/v10/auditLog.d.ts | 160 +- .../payloads/v10/auditLog.d.ts.map | 2 +- .../payloads/v10/autoModeration.d.ts | 17 +- .../payloads/v10/autoModeration.d.ts.map | 2 +- .../payloads/v10/autoModeration.js | 5 +- .../payloads/v10/autoModeration.js.map | 2 +- .../payloads/v10/channel.d.ts | 133 +- .../payloads/v10/channel.d.ts.map | 2 +- .../discord-api-types/payloads/v10/channel.js | 68 +- .../payloads/v10/channel.js.map | 2 +- .../discord-api-types/payloads/v10/emoji.d.ts | 2 +- .../payloads/v10/emoji.d.ts.map | 2 +- .../payloads/v10/gateway.d.ts | 11 +- .../payloads/v10/gateway.d.ts.map | 2 +- .../payloads/v10/gateway.js.map | 2 +- .../discord-api-types/payloads/v10/guild.d.ts | 130 +- .../payloads/v10/guild.d.ts.map | 2 +- .../discord-api-types/payloads/v10/guild.js | 28 +- .../payloads/v10/guild.js.map | 2 +- .../payloads/v10/guildScheduledEvent.d.ts | 4 +- .../payloads/v10/guildScheduledEvent.d.ts.map | 2 +- .../discord-api-types/payloads/v10/index.mjs | 1 + .../payloads/v10/interactions.d.ts | 6 +- .../payloads/v10/interactions.d.ts.map | 2 +- .../payloads/v10/invite.d.ts | 3 +- .../payloads/v10/invite.d.ts.map | 2 +- .../payloads/v10/invite.js.map | 2 +- .../payloads/v10/stageInstance.d.ts | 3 +- .../payloads/v10/stageInstance.d.ts.map | 2 +- .../payloads/v10/stageInstance.js.map | 2 +- .../payloads/v10/sticker.d.ts | 5 +- .../payloads/v10/sticker.d.ts.map | 2 +- .../payloads/v10/sticker.js.map | 2 +- .../discord-api-types/payloads/v10/teams.d.ts | 2 +- .../payloads/v10/teams.d.ts.map | 2 +- .../payloads/v10/template.d.ts | 2 +- .../payloads/v10/template.d.ts.map | 2 +- .../discord-api-types/payloads/v10/user.d.ts | 42 +- .../payloads/v10/user.d.ts.map | 2 +- .../discord-api-types/payloads/v10/user.js | 32 +- .../payloads/v10/user.js.map | 2 +- .../discord-api-types/payloads/v10/voice.d.ts | 2 +- .../payloads/v10/voice.d.ts.map | 2 +- .../payloads/v10/webhook.d.ts | 2 +- .../payloads/v10/webhook.d.ts.map | 2 +- .../payloads/v6/auditLog.d.ts | 155 +- .../payloads/v6/auditLog.d.ts.map | 2 +- .../discord-api-types/payloads/v6/auditLog.js | 1 + .../payloads/v6/auditLog.js.map | 2 +- .../payloads/v6/channel.d.ts | 23 + .../payloads/v6/channel.d.ts.map | 2 +- .../discord-api-types/payloads/v6/channel.js | 5 + .../payloads/v6/channel.js.map | 2 +- .../discord-api-types/payloads/v6/emoji.d.ts | 2 + .../payloads/v6/emoji.d.ts.map | 2 +- .../payloads/v6/gateway.d.ts | 21 +- .../payloads/v6/gateway.d.ts.map | 2 +- .../discord-api-types/payloads/v6/gateway.js | 2 + .../payloads/v6/gateway.js.map | 2 +- .../discord-api-types/payloads/v6/guild.d.ts | 19 +- .../payloads/v6/guild.d.ts.map | 2 +- .../discord-api-types/payloads/v6/guild.js | 9 + .../payloads/v6/guild.js.map | 2 +- .../discord-api-types/payloads/v6/invite.d.ts | 3 + .../payloads/v6/invite.d.ts.map | 2 +- .../discord-api-types/payloads/v6/invite.js | 1 + .../payloads/v6/invite.js.map | 2 +- .../discord-api-types/payloads/v6/oauth2.d.ts | 1 + .../payloads/v6/oauth2.d.ts.map | 2 +- .../payloads/v6/permissions.d.ts | 2 + .../payloads/v6/permissions.d.ts.map | 2 +- .../payloads/v6/permissions.js | 2 + .../payloads/v6/permissions.js.map | 2 +- .../discord-api-types/payloads/v6/teams.d.ts | 3 + .../payloads/v6/teams.d.ts.map | 2 +- .../discord-api-types/payloads/v6/teams.js | 1 + .../payloads/v6/teams.js.map | 2 +- .../discord-api-types/payloads/v6/user.d.ts | 4 + .../payloads/v6/user.d.ts.map | 2 +- .../discord-api-types/payloads/v6/user.js | 2 + .../discord-api-types/payloads/v6/user.js.map | 2 +- .../discord-api-types/payloads/v6/voice.d.ts | 2 + .../payloads/v6/voice.d.ts.map | 2 +- .../payloads/v6/webhook.d.ts | 1 + .../payloads/v6/webhook.d.ts.map | 2 +- .../payloads/v6/webhook.js.map | 2 +- .../_chatInput/attachment.d.ts | 6 +- .../_chatInput/attachment.d.ts.map | 2 +- .../_applicationCommands/_chatInput/base.d.ts | 2 +- .../_chatInput/base.d.ts.map | 2 +- .../_chatInput/boolean.d.ts | 4 +- .../_chatInput/boolean.d.ts.map | 2 +- .../_chatInput/channel.d.ts | 6 +- .../_chatInput/channel.d.ts.map | 2 +- .../_chatInput/integer.d.ts | 2 +- .../_chatInput/integer.d.ts.map | 2 +- .../_chatInput/mentionable.d.ts | 6 +- .../_chatInput/mentionable.d.ts.map | 2 +- .../_chatInput/number.d.ts | 2 +- .../_chatInput/number.d.ts.map | 2 +- .../_applicationCommands/_chatInput/role.d.ts | 6 +- .../_chatInput/role.d.ts.map | 2 +- .../_chatInput/shared.d.ts | 2 + .../_chatInput/shared.d.ts.map | 2 +- .../_applicationCommands/_chatInput/shared.js | 1 + .../_chatInput/shared.js.map | 2 +- .../_chatInput/string.d.ts | 2 +- .../_chatInput/string.d.ts.map | 2 +- .../_chatInput/subcommand.d.ts | 2 +- .../_chatInput/subcommand.d.ts.map | 2 +- .../_applicationCommands/_chatInput/user.d.ts | 6 +- .../_chatInput/user.d.ts.map | 2 +- .../_applicationCommands/chatInput.d.ts | 30 +- .../_applicationCommands/chatInput.d.ts.map | 2 +- .../_applicationCommands/contextMenu.d.ts | 36 +- .../_applicationCommands/contextMenu.d.ts.map | 2 +- .../_applicationCommands/permissions.d.ts | 3 + .../_applicationCommands/permissions.d.ts.map | 2 +- .../_applicationCommands/permissions.js | 1 + .../_applicationCommands/permissions.js.map | 2 +- .../v8/_interactions/applicationCommands.d.ts | 25 +- .../applicationCommands.d.ts.map | 2 +- .../v8/_interactions/applicationCommands.js | 1 + .../_interactions/applicationCommands.js.map | 2 +- .../v8/_interactions/autocomplete.d.ts | 8 +- .../v8/_interactions/autocomplete.d.ts.map | 2 +- .../payloads/v8/_interactions/base.d.ts | 11 +- .../payloads/v8/_interactions/base.d.ts.map | 2 +- .../v8/_interactions/messageComponents.d.ts | 12 +- .../_interactions/messageComponents.d.ts.map | 2 +- .../v8/_interactions/modalSubmit.d.ts | 9 +- .../v8/_interactions/modalSubmit.d.ts.map | 2 +- .../payloads/v8/_interactions/ping.d.ts | 2 +- .../payloads/v8/_interactions/ping.d.ts.map | 2 +- .../payloads/v8/_interactions/responses.d.ts | 11 +- .../v8/_interactions/responses.d.ts.map | 2 +- .../payloads/v8/_interactions/responses.js | 2 + .../v8/_interactions/responses.js.map | 2 +- .../payloads/v8/application.d.ts | 4 +- .../payloads/v8/application.d.ts.map | 2 +- .../payloads/v8/application.js | 1 + .../payloads/v8/application.js.map | 2 +- .../payloads/v8/auditLog.d.ts | 201 +- .../payloads/v8/auditLog.d.ts.map | 2 +- .../discord-api-types/payloads/v8/auditLog.js | 1 + .../payloads/v8/auditLog.js.map | 2 +- .../payloads/v8/channel.d.ts | 67 +- .../payloads/v8/channel.d.ts.map | 2 +- .../discord-api-types/payloads/v8/channel.js | 9 + .../payloads/v8/channel.js.map | 2 +- .../discord-api-types/payloads/v8/emoji.d.ts | 4 +- .../payloads/v8/emoji.d.ts.map | 2 +- .../payloads/v8/gateway.d.ts | 21 +- .../payloads/v8/gateway.d.ts.map | 2 +- .../discord-api-types/payloads/v8/gateway.js | 2 + .../payloads/v8/gateway.js.map | 2 +- .../discord-api-types/payloads/v8/guild.d.ts | 30 +- .../payloads/v8/guild.d.ts.map | 2 +- .../discord-api-types/payloads/v8/guild.js | 10 + .../payloads/v8/guild.js.map | 2 +- .../payloads/v8/guildScheduledEvent.d.ts | 10 +- .../payloads/v8/guildScheduledEvent.d.ts.map | 2 +- .../payloads/v8/guildScheduledEvent.js | 3 + .../payloads/v8/guildScheduledEvent.js.map | 2 +- .../payloads/v8/interactions.d.ts | 9 +- .../payloads/v8/interactions.d.ts.map | 2 +- .../discord-api-types/payloads/v8/invite.d.ts | 5 +- .../payloads/v8/invite.d.ts.map | 2 +- .../discord-api-types/payloads/v8/invite.js | 1 + .../payloads/v8/invite.js.map | 2 +- .../payloads/v8/permissions.d.ts | 2 + .../payloads/v8/permissions.d.ts.map | 2 +- .../payloads/v8/stageInstance.d.ts | 5 +- .../payloads/v8/stageInstance.d.ts.map | 2 +- .../payloads/v8/stageInstance.js | 1 + .../payloads/v8/stageInstance.js.map | 2 +- .../payloads/v8/sticker.d.ts | 10 +- .../payloads/v8/sticker.d.ts.map | 2 +- .../discord-api-types/payloads/v8/sticker.js | 2 + .../payloads/v8/sticker.js.map | 2 +- .../discord-api-types/payloads/v8/teams.d.ts | 5 +- .../payloads/v8/teams.d.ts.map | 2 +- .../discord-api-types/payloads/v8/teams.js | 1 + .../payloads/v8/teams.js.map | 2 +- .../payloads/v8/template.d.ts | 3 +- .../payloads/v8/template.d.ts.map | 2 +- .../discord-api-types/payloads/v8/user.d.ts | 8 +- .../payloads/v8/user.d.ts.map | 2 +- .../discord-api-types/payloads/v8/user.js | 4 +- .../discord-api-types/payloads/v8/user.js.map | 2 +- .../discord-api-types/payloads/v8/voice.d.ts | 4 +- .../payloads/v8/voice.d.ts.map | 2 +- .../payloads/v8/webhook.d.ts | 3 +- .../payloads/v8/webhook.d.ts.map | 2 +- .../payloads/v8/webhook.js.map | 2 +- .../_chatInput/attachment.d.ts | 6 +- .../_chatInput/attachment.d.ts.map | 2 +- .../_applicationCommands/_chatInput/base.d.ts | 5 +- .../_chatInput/base.d.ts.map | 2 +- .../_chatInput/boolean.d.ts | 4 +- .../_chatInput/boolean.d.ts.map | 2 +- .../_chatInput/channel.d.ts | 6 +- .../_chatInput/channel.d.ts.map | 2 +- .../_chatInput/integer.d.ts | 2 +- .../_chatInput/integer.d.ts.map | 2 +- .../_chatInput/mentionable.d.ts | 6 +- .../_chatInput/mentionable.d.ts.map | 2 +- .../_chatInput/number.d.ts | 2 +- .../_chatInput/number.d.ts.map | 2 +- .../_applicationCommands/_chatInput/role.d.ts | 6 +- .../_chatInput/role.d.ts.map | 2 +- .../_chatInput/string.d.ts | 2 +- .../_chatInput/string.d.ts.map | 2 +- .../_chatInput/subcommand.d.ts | 2 +- .../_chatInput/subcommand.d.ts.map | 2 +- .../_applicationCommands/_chatInput/user.d.ts | 6 +- .../_chatInput/user.d.ts.map | 2 +- .../_applicationCommands/chatInput.d.ts | 20 +- .../_applicationCommands/chatInput.d.ts.map | 2 +- .../_applicationCommands/contextMenu.d.ts | 22 +- .../_applicationCommands/contextMenu.d.ts.map | 2 +- .../_applicationCommands/permissions.d.ts.map | 2 +- .../_applicationCommands/permissions.js | 1 + .../_applicationCommands/permissions.js.map | 2 +- .../v9/_interactions/applicationCommands.d.ts | 15 +- .../applicationCommands.d.ts.map | 2 +- .../_interactions/applicationCommands.js.map | 2 +- .../v9/_interactions/autocomplete.d.ts | 6 +- .../v9/_interactions/autocomplete.d.ts.map | 2 +- .../payloads/v9/_interactions/base.d.ts | 22 +- .../payloads/v9/_interactions/base.d.ts.map | 2 +- .../v9/_interactions/messageComponents.d.ts | 18 +- .../_interactions/messageComponents.d.ts.map | 2 +- .../v9/_interactions/modalSubmit.d.ts | 6 +- .../v9/_interactions/modalSubmit.d.ts.map | 2 +- .../payloads/v9/_interactions/ping.d.ts | 2 +- .../payloads/v9/_interactions/ping.d.ts.map | 2 +- .../payloads/v9/_interactions/responses.d.ts | 6 +- .../v9/_interactions/responses.d.ts.map | 2 +- .../payloads/v9/application.d.ts | 22 +- .../payloads/v9/application.d.ts.map | 2 +- .../payloads/v9/application.js | 18 +- .../payloads/v9/application.js.map | 2 +- .../payloads/v9/auditLog.d.ts | 160 +- .../payloads/v9/auditLog.d.ts.map | 2 +- .../payloads/v9/autoModeration.d.ts | 17 +- .../payloads/v9/autoModeration.d.ts.map | 2 +- .../payloads/v9/autoModeration.js | 5 +- .../payloads/v9/autoModeration.js.map | 2 +- .../payloads/v9/channel.d.ts | 133 +- .../payloads/v9/channel.d.ts.map | 2 +- .../discord-api-types/payloads/v9/channel.js | 68 +- .../payloads/v9/channel.js.map | 2 +- .../discord-api-types/payloads/v9/emoji.d.ts | 2 +- .../payloads/v9/emoji.d.ts.map | 2 +- .../payloads/v9/gateway.d.ts | 8 +- .../payloads/v9/gateway.d.ts.map | 2 +- .../discord-api-types/payloads/v9/guild.d.ts | 128 +- .../payloads/v9/guild.d.ts.map | 2 +- .../discord-api-types/payloads/v9/guild.js | 26 +- .../payloads/v9/guild.js.map | 2 +- .../payloads/v9/guildScheduledEvent.d.ts | 4 +- .../payloads/v9/guildScheduledEvent.d.ts.map | 2 +- .../discord-api-types/payloads/v9/index.mjs | 1 + .../payloads/v9/interactions.d.ts | 6 +- .../payloads/v9/interactions.d.ts.map | 2 +- .../discord-api-types/payloads/v9/invite.d.ts | 3 +- .../payloads/v9/invite.d.ts.map | 2 +- .../payloads/v9/invite.js.map | 2 +- .../payloads/v9/stageInstance.d.ts | 5 +- .../payloads/v9/stageInstance.d.ts.map | 2 +- .../payloads/v9/stageInstance.js | 1 + .../payloads/v9/stageInstance.js.map | 2 +- .../payloads/v9/sticker.d.ts | 5 +- .../payloads/v9/sticker.d.ts.map | 2 +- .../payloads/v9/sticker.js.map | 2 +- .../discord-api-types/payloads/v9/teams.d.ts | 2 +- .../payloads/v9/teams.d.ts.map | 2 +- .../payloads/v9/template.d.ts | 2 +- .../payloads/v9/template.d.ts.map | 2 +- .../discord-api-types/payloads/v9/user.d.ts | 42 +- .../payloads/v9/user.d.ts.map | 2 +- .../discord-api-types/payloads/v9/user.js | 32 +- .../discord-api-types/payloads/v9/user.js.map | 2 +- .../discord-api-types/payloads/v9/voice.d.ts | 2 +- .../payloads/v9/voice.d.ts.map | 2 +- .../payloads/v9/webhook.d.ts | 2 +- .../payloads/v9/webhook.d.ts.map | 2 +- .../discord-api-types/rest/common.d.ts | 13 +- .../discord-api-types/rest/common.d.ts.map | 2 +- node_modules/discord-api-types/rest/common.js | 11 + .../discord-api-types/rest/common.js.map | 2 +- .../rest/v10/application.d.ts | 6 +- .../rest/v10/application.d.ts.map | 2 +- .../discord-api-types/rest/v10/auditLog.d.ts | 2 +- .../rest/v10/auditLog.d.ts.map | 2 +- .../rest/v10/autoModeration.d.ts | 25 +- .../rest/v10/autoModeration.d.ts.map | 2 +- .../discord-api-types/rest/v10/channel.d.ts | 222 +- .../rest/v10/channel.d.ts.map | 2 +- .../discord-api-types/rest/v10/emoji.d.ts | 25 +- .../discord-api-types/rest/v10/emoji.d.ts.map | 2 +- .../discord-api-types/rest/v10/gateway.d.ts | 4 +- .../rest/v10/gateway.d.ts.map | 2 +- .../discord-api-types/rest/v10/guild.d.ts | 338 +- .../discord-api-types/rest/v10/guild.d.ts.map | 2 +- .../rest/v10/guildScheduledEvent.d.ts | 40 +- .../rest/v10/guildScheduledEvent.d.ts.map | 2 +- .../discord-api-types/rest/v10/index.d.ts | 75 +- .../discord-api-types/rest/v10/index.d.ts.map | 2 +- .../discord-api-types/rest/v10/index.js | 35 +- .../discord-api-types/rest/v10/index.js.map | 2 +- .../rest/v10/interactions.d.ts | 88 +- .../rest/v10/interactions.d.ts.map | 2 +- .../discord-api-types/rest/v10/invite.d.ts | 4 +- .../rest/v10/invite.d.ts.map | 2 +- .../discord-api-types/rest/v10/oauth2.d.ts | 10 +- .../rest/v10/oauth2.d.ts.map | 2 +- .../rest/v10/stageInstance.d.ts | 21 +- .../rest/v10/stageInstance.d.ts.map | 2 +- .../discord-api-types/rest/v10/sticker.d.ts | 27 +- .../rest/v10/sticker.d.ts.map | 2 +- .../discord-api-types/rest/v10/template.d.ts | 30 +- .../rest/v10/template.d.ts.map | 2 +- .../discord-api-types/rest/v10/user.d.ts | 43 +- .../discord-api-types/rest/v10/user.d.ts.map | 2 +- .../discord-api-types/rest/v10/voice.d.ts | 4 +- .../discord-api-types/rest/v10/voice.d.ts.map | 2 +- .../discord-api-types/rest/v10/webhook.d.ts | 102 +- .../rest/v10/webhook.d.ts.map | 2 +- .../discord-api-types/rest/v6/auditLog.d.ts | 3 +- .../rest/v6/auditLog.d.ts.map | 2 +- .../discord-api-types/rest/v6/channel.d.ts | 132 +- .../rest/v6/channel.d.ts.map | 2 +- .../discord-api-types/rest/v6/channel.js | 1 + .../discord-api-types/rest/v6/channel.js.map | 2 +- .../discord-api-types/rest/v6/emoji.d.ts | 21 +- .../discord-api-types/rest/v6/emoji.d.ts.map | 2 +- .../discord-api-types/rest/v6/gateway.d.ts | 6 +- .../rest/v6/gateway.d.ts.map | 2 +- .../discord-api-types/rest/v6/guild.d.ts | 257 +- .../discord-api-types/rest/v6/guild.d.ts.map | 2 +- .../discord-api-types/rest/v6/index.d.ts | 2 +- .../discord-api-types/rest/v6/index.d.ts.map | 2 +- .../discord-api-types/rest/v6/invite.d.ts | 6 +- .../discord-api-types/rest/v6/invite.d.ts.map | 2 +- .../discord-api-types/rest/v6/oauth2.d.ts | 23 +- .../discord-api-types/rest/v6/oauth2.d.ts.map | 2 +- .../discord-api-types/rest/v6/user.d.ts | 25 +- .../discord-api-types/rest/v6/user.d.ts.map | 2 +- .../discord-api-types/rest/v6/voice.d.ts | 3 +- .../discord-api-types/rest/v6/voice.d.ts.map | 2 +- .../discord-api-types/rest/v6/webhook.d.ts | 67 +- .../rest/v6/webhook.d.ts.map | 2 +- .../discord-api-types/rest/v8/auditLog.d.ts | 3 +- .../rest/v8/auditLog.d.ts.map | 2 +- .../discord-api-types/rest/v8/channel.d.ts | 214 +- .../rest/v8/channel.d.ts.map | 2 +- .../discord-api-types/rest/v8/emoji.d.ts | 32 +- .../discord-api-types/rest/v8/emoji.d.ts.map | 2 +- .../discord-api-types/rest/v8/gateway.d.ts | 6 +- .../rest/v8/gateway.d.ts.map | 2 +- .../discord-api-types/rest/v8/guild.d.ts | 374 ++- .../discord-api-types/rest/v8/guild.d.ts.map | 2 +- .../rest/v8/guildScheduledEvent.d.ts | 47 +- .../rest/v8/guildScheduledEvent.d.ts.map | 2 +- .../discord-api-types/rest/v8/index.d.ts | 7 +- .../discord-api-types/rest/v8/index.d.ts.map | 2 +- .../discord-api-types/rest/v8/index.js | 5 +- .../discord-api-types/rest/v8/index.js.map | 2 +- .../rest/v8/interactions.d.ts | 125 +- .../rest/v8/interactions.d.ts.map | 2 +- .../discord-api-types/rest/v8/invite.d.ts | 6 +- .../discord-api-types/rest/v8/invite.d.ts.map | 2 +- .../discord-api-types/rest/v8/oauth2.d.ts | 24 +- .../discord-api-types/rest/v8/oauth2.d.ts.map | 2 +- .../rest/v8/stageInstance.d.ts | 25 +- .../rest/v8/stageInstance.d.ts.map | 2 +- .../discord-api-types/rest/v8/sticker.d.ts | 23 +- .../rest/v8/sticker.d.ts.map | 2 +- .../discord-api-types/rest/v8/template.d.ts | 40 +- .../rest/v8/template.d.ts.map | 2 +- .../discord-api-types/rest/v8/user.d.ts | 36 +- .../discord-api-types/rest/v8/user.d.ts.map | 2 +- .../discord-api-types/rest/v8/voice.d.ts | 3 +- .../discord-api-types/rest/v8/voice.d.ts.map | 2 +- .../discord-api-types/rest/v8/webhook.d.ts | 122 +- .../rest/v8/webhook.d.ts.map | 2 +- .../rest/v9/application.d.ts | 6 +- .../rest/v9/application.d.ts.map | 2 +- .../discord-api-types/rest/v9/auditLog.d.ts | 2 +- .../rest/v9/auditLog.d.ts.map | 2 +- .../rest/v9/autoModeration.d.ts | 25 +- .../rest/v9/autoModeration.d.ts.map | 2 +- .../discord-api-types/rest/v9/channel.d.ts | 232 +- .../rest/v9/channel.d.ts.map | 2 +- .../discord-api-types/rest/v9/emoji.d.ts | 25 +- .../discord-api-types/rest/v9/emoji.d.ts.map | 2 +- .../discord-api-types/rest/v9/gateway.d.ts | 4 +- .../rest/v9/gateway.d.ts.map | 2 +- .../discord-api-types/rest/v9/guild.d.ts | 338 +- .../discord-api-types/rest/v9/guild.d.ts.map | 2 +- .../rest/v9/guildScheduledEvent.d.ts | 40 +- .../rest/v9/guildScheduledEvent.d.ts.map | 2 +- .../discord-api-types/rest/v9/index.d.ts | 77 +- .../discord-api-types/rest/v9/index.d.ts.map | 2 +- .../discord-api-types/rest/v9/index.js | 35 +- .../discord-api-types/rest/v9/index.js.map | 2 +- .../rest/v9/interactions.d.ts | 88 +- .../rest/v9/interactions.d.ts.map | 2 +- .../discord-api-types/rest/v9/invite.d.ts | 4 +- .../discord-api-types/rest/v9/invite.d.ts.map | 2 +- .../discord-api-types/rest/v9/oauth2.d.ts | 10 +- .../discord-api-types/rest/v9/oauth2.d.ts.map | 2 +- .../rest/v9/stageInstance.d.ts | 21 +- .../rest/v9/stageInstance.d.ts.map | 2 +- .../discord-api-types/rest/v9/sticker.d.ts | 27 +- .../rest/v9/sticker.d.ts.map | 2 +- .../discord-api-types/rest/v9/template.d.ts | 30 +- .../rest/v9/template.d.ts.map | 2 +- .../discord-api-types/rest/v9/user.d.ts | 43 +- .../discord-api-types/rest/v9/user.d.ts.map | 2 +- .../discord-api-types/rest/v9/voice.d.ts | 4 +- .../discord-api-types/rest/v9/voice.d.ts.map | 2 +- .../discord-api-types/rest/v9/webhook.d.ts | 102 +- .../rest/v9/webhook.d.ts.map | 2 +- .../discord-api-types/rpc/common.d.ts.map | 2 +- .../discord-api-types/rpc/common.js.map | 2 +- .../discord-api-types/utils/internals.d.ts | 26 +- .../utils/internals.d.ts.map | 2 +- node_modules/discord-api-types/utils/v10.d.ts | 17 +- .../discord-api-types/utils/v10.d.ts.map | 2 +- node_modules/discord-api-types/utils/v10.js | 15 +- .../discord-api-types/utils/v10.js.map | 2 +- node_modules/discord-api-types/utils/v8.d.ts | 12 +- .../discord-api-types/utils/v8.d.ts.map | 2 +- node_modules/discord-api-types/utils/v8.js | 10 +- .../discord-api-types/utils/v8.js.map | 2 +- node_modules/discord-api-types/utils/v9.d.ts | 17 +- .../discord-api-types/utils/v9.d.ts.map | 2 +- node_modules/discord-api-types/utils/v9.js | 15 +- .../discord-api-types/utils/v9.js.map | 2 +- node_modules/discord-api-types/v10.mjs | 1 + node_modules/discord-api-types/v9.mjs | 1 + .../discord-api-types/voice/v4.d.ts.map | 2 +- .../discord-api-types/voice/v4.js.map | 2 +- node_modules/discord.js/CHANGELOG.md | 2818 ++++++++++++++++- node_modules/discord.js/README.md | 35 +- node_modules/discord.js/package.json | 44 +- node_modules/discord.js/src/WebSocket.js | 39 - .../discord.js/src/client/BaseClient.js | 12 +- node_modules/discord.js/src/client/Client.js | 45 +- .../discord.js/src/client/WebhookClient.js | 4 +- .../discord.js/src/client/actions/Action.js | 6 +- .../src/client/actions/ActionsManager.js | 8 + .../actions/GuildAuditLogEntryCreate.js | 29 + .../src/client/actions/InteractionCreate.js | 2 +- .../src/client/actions/WebhooksUpdate.js | 3 +- .../src/client/websocket/WebSocketManager.js | 340 +- .../src/client/websocket/WebSocketShard.js | 751 +---- .../handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js | 5 + .../websocket/handlers/GUILD_MEMBERS_CHUNK.js | 5 +- .../src/client/websocket/handlers/RESUMED.js | 2 +- .../src/client/websocket/handlers/index.js | 1 + .../discord.js/src/errors/ErrorCodes.js | 16 + .../discord.js/src/errors/Messages.js | 6 + node_modules/discord.js/src/index.js | 7 +- .../src/managers/ApplicationCommandManager.js | 7 +- .../ApplicationCommandPermissionsManager.js | 6 +- .../src/managers/AutoModerationRuleManager.js | 42 +- .../src/managers/BaseGuildEmojiManager.js | 4 +- .../discord.js/src/managers/CachedManager.js | 7 + .../managers/CategoryChannelChildManager.js | 1 + .../discord.js/src/managers/ChannelManager.js | 6 +- .../src/managers/GuildBanManager.js | 6 +- .../src/managers/GuildChannelManager.js | 66 +- .../src/managers/GuildEmojiManager.js | 14 +- .../src/managers/GuildForumThreadManager.js | 3 +- .../src/managers/GuildInviteManager.js | 2 +- .../discord.js/src/managers/GuildManager.js | 129 +- .../src/managers/GuildMemberManager.js | 194 +- .../managers/GuildScheduledEventManager.js | 6 +- .../src/managers/GuildStickerManager.js | 10 +- .../discord.js/src/managers/MessageManager.js | 3 +- .../src/managers/ReactionManager.js | 1 + .../discord.js/src/managers/RoleManager.js | 39 +- .../discord.js/src/managers/ThreadManager.js | 53 +- .../src/managers/ThreadMemberManager.js | 47 +- node_modules/discord.js/src/sharding/Shard.js | 37 +- .../src/sharding/ShardClientUtil.js | 71 +- .../discord.js/src/structures/ActionRow.js | 20 +- .../src/structures/ActionRowBuilder.js | 13 +- .../src/structures/ApplicationCommand.js | 17 +- .../ApplicationRoleConnectionMetadata.js | 46 + .../discord.js/src/structures/Attachment.js | 22 + .../src/structures/AttachmentBuilder.js | 2 +- .../AutoModerationActionExecution.js | 33 +- .../src/structures/AutoModerationRule.js | 45 +- .../src/structures/AutocompleteInteraction.js | 4 +- .../src/structures/BaseGuildTextChannel.js | 4 +- .../src/structures/BaseGuildVoiceChannel.js | 138 +- .../src/structures/BaseInteraction.js | 8 +- .../src/structures/BaseSelectMenuComponent.js | 4 +- .../src/structures/ButtonBuilder.js | 12 +- .../src/structures/ButtonComponent.js | 4 +- .../src/structures/CategoryChannel.js | 25 +- .../structures/ChannelSelectMenuBuilder.js | 14 +- .../src/structures/ClientApplication.js | 51 + .../src/structures/ClientPresence.js | 2 +- .../discord.js/src/structures/ClientUser.js | 18 +- .../CommandInteractionOptionResolver.js | 63 +- .../discord.js/src/structures/DMChannel.js | 2 +- .../discord.js/src/structures/EmbedBuilder.js | 12 +- .../discord.js/src/structures/ForumChannel.js | 18 +- .../discord.js/src/structures/Guild.js | 209 +- .../src/structures/GuildAuditLogs.js | 2 +- .../src/structures/GuildAuditLogsEntry.js | 28 +- .../discord.js/src/structures/GuildChannel.js | 16 +- .../discord.js/src/structures/GuildEmoji.js | 10 +- .../discord.js/src/structures/GuildMember.js | 68 +- .../src/structures/GuildScheduledEvent.js | 4 +- .../src/structures/GuildTemplate.js | 4 +- .../discord.js/src/structures/Integration.js | 1 + .../src/structures/InteractionCollector.js | 2 +- .../src/structures/InteractionResponse.js | 44 + .../src/structures/InteractionWebhook.js | 2 +- .../discord.js/src/structures/InviteGuild.js | 3 +- .../MentionableSelectMenuBuilder.js | 15 +- .../discord.js/src/structures/Message.js | 59 +- .../src/structures/MessagePayload.js | 25 +- .../src/structures/MessageReaction.js | 4 + .../discord.js/src/structures/ModalBuilder.js | 12 +- .../src/structures/ModalSubmitFields.js | 4 +- .../discord.js/src/structures/Presence.js | 12 + .../discord.js/src/structures/Role.js | 32 +- .../src/structures/RoleSelectMenuBuilder.js | 14 +- .../src/structures/SelectMenuBuilder.js | 2 +- .../src/structures/SelectMenuComponent.js | 2 +- .../src/structures/SelectMenuInteraction.js | 2 +- .../src/structures/SelectMenuOptionBuilder.js | 2 +- .../discord.js/src/structures/StageChannel.js | 46 +- .../discord.js/src/structures/Sticker.js | 13 +- .../src/structures/StringSelectMenuBuilder.js | 9 +- .../StringSelectMenuOptionBuilder.js | 12 +- .../src/structures/TextInputBuilder.js | 12 +- .../src/structures/ThreadChannel.js | 36 +- .../discord.js/src/structures/ThreadMember.js | 19 +- .../discord.js/src/structures/User.js | 18 +- .../src/structures/UserSelectMenuBuilder.js | 14 +- .../discord.js/src/structures/VoiceChannel.js | 154 +- .../discord.js/src/structures/VoiceState.js | 18 +- .../discord.js/src/structures/Webhook.js | 14 +- .../src/structures/interfaces/Collector.js | 15 + .../interfaces/InteractionResponses.js | 7 +- .../structures/interfaces/TextBasedChannel.js | 38 +- node_modules/discord.js/src/util/APITypes.js | 51 +- node_modules/discord.js/src/util/BitField.js | 14 +- node_modules/discord.js/src/util/Channels.js | 4 +- .../discord.js/src/util/Components.js | 5 - node_modules/discord.js/src/util/Constants.js | 102 +- node_modules/discord.js/src/util/Events.js | 6 + .../discord.js/src/util/Formatters.js | 4 +- .../src/util/GuildMemberFlagsBitField.js | 41 + node_modules/discord.js/src/util/Options.js | 52 +- node_modules/discord.js/src/util/Partials.js | 2 +- node_modules/discord.js/src/util/Sweepers.js | 2 +- .../discord.js/src/util/Transformers.js | 19 +- .../discord.js/src/util/UserFlagsBitField.js | 1 + node_modules/discord.js/src/util/Util.js | 240 +- node_modules/discord.js/typings/index.d.ts | 548 ++-- .../discord.js/typings/index.test-d.ts | 115 +- node_modules/dotenv/CHANGELOG.md | 21 +- node_modules/dotenv/README.md | 59 +- node_modules/dotenv/lib/cli-options.js | 2 +- node_modules/dotenv/lib/env-options.js | 4 + node_modules/dotenv/lib/main.d.ts | 19 + node_modules/dotenv/lib/main.js | 27 +- node_modules/dotenv/package.json | 2 +- node_modules/file-type/browser.d.ts | 21 +- node_modules/file-type/browser.js | 38 +- node_modules/file-type/core.d.ts | 38 +- node_modules/file-type/core.js | 91 +- node_modules/file-type/package.json | 19 +- node_modules/file-type/readme.md | 39 +- node_modules/file-type/supported.js | 14 + .../node_modules/readable-stream/README.md | 58 - .../lib/internal/streams/destroy.js | 74 - .../node_modules/readable-stream/package.json | 52 - .../mysql/node_modules/safe-buffer/README.md | 584 ---- .../mysql/node_modules/safe-buffer/index.d.ts | 187 -- .../mysql/node_modules/safe-buffer/index.js | 62 - .../node_modules/safe-buffer/package.json | 37 - .../mysql/node_modules/string_decoder/LICENSE | 48 - .../node_modules/string_decoder/README.md | 47 - .../string_decoder/lib/string_decoder.js | 296 -- .../node_modules/string_decoder/package.json | 31 - .../openai/.openapi-generator/VERSION | 2 +- node_modules/openai/README.md | 17 +- node_modules/openai/api.ts | 204 +- node_modules/openai/base.ts | 2 +- node_modules/openai/common.ts | 2 +- node_modules/openai/configuration.ts | 2 +- node_modules/openai/dist/api.d.ts | 201 +- node_modules/openai/dist/api.js | 40 +- node_modules/openai/dist/base.d.ts | 2 +- node_modules/openai/dist/base.js | 2 +- node_modules/openai/dist/common.d.ts | 2 +- node_modules/openai/dist/common.js | 2 +- node_modules/openai/dist/configuration.d.ts | 2 +- node_modules/openai/dist/configuration.js | 2 +- node_modules/openai/dist/index.d.ts | 2 +- node_modules/openai/dist/index.js | 2 +- node_modules/openai/index.ts | 2 +- node_modules/openai/package.json | 2 +- .../readable-stream/.travis.yml | 0 node_modules/readable-stream/README.md | 74 +- .../doc/wg-meetings/2015-01-30.md | 0 .../readable-stream/duplex-browser.js | 0 .../readable-stream/duplex.js | 0 .../readable-stream/lib/_stream_duplex.js | 96 +- .../lib/_stream_passthrough.js | 10 +- .../readable-stream/lib/_stream_readable.js | 795 ++--- .../readable-stream/lib/_stream_transform.js | 71 +- .../readable-stream/lib/_stream_writable.js | 398 ++- .../lib/internal/streams/BufferList.js | 0 .../lib/internal/streams/destroy.js | 65 +- node_modules/readable-stream/package.json | 54 +- .../readable-stream/passthrough.js | 0 .../readable-stream/readable-browser.js | 2 - node_modules/readable-stream/readable.js | 13 +- .../readable-stream/transform.js | 0 .../readable-stream/writable-browser.js | 0 .../readable-stream/writable.js | 0 .../readable-stream/CONTRIBUTING.md | 0 .../readable-stream/GOVERNANCE.md | 0 .../node_modules/readable-stream/LICENSE | 0 .../node_modules/readable-stream/README.md | 106 + .../readable-stream/errors-browser.js | 0 .../node_modules}/readable-stream/errors.js | 0 .../readable-stream/experimentalWarning.js | 0 .../readable-stream/lib/_stream_duplex.js | 87 +- .../lib/_stream_passthrough.js | 12 +- .../readable-stream/lib/_stream_readable.js | 534 ++-- .../readable-stream/lib/_stream_transform.js | 60 +- .../readable-stream/lib/_stream_writable.js | 248 +- .../lib/internal/streams/async_iterator.js | 47 +- .../lib/internal/streams/buffer_list.js | 67 +- .../lib/internal/streams/destroy.js | 96 + .../lib/internal/streams/end-of-stream.js | 20 +- .../lib/internal/streams/from-browser.js | 0 .../lib/internal/streams/from.js | 36 +- .../lib/internal/streams/pipeline.js | 21 +- .../lib/internal/streams/state.js | 9 +- .../lib/internal/streams/stream-browser.js | 0 .../lib/internal/streams/stream.js | 0 .../node_modules/readable-stream/package.json | 68 + .../readable-stream/readable-browser.js | 2 + .../node_modules/readable-stream/readable.js | 13 +- node_modules/safe-buffer/index.js | 3 - node_modules/safe-buffer/package.json | 22 +- .../string_decoder/.travis.yml | 0 node_modules/string_decoder/package.json | 7 +- node_modules/ts-mixer/CHANGELOG.md | 9 + node_modules/ts-mixer/LICENSE | 2 +- node_modules/ts-mixer/README.md | 6 +- node_modules/ts-mixer/dist/cjs/decorator.js | 39 +- .../ts-mixer/dist/cjs/mixin-tracking.js | 2 +- node_modules/ts-mixer/dist/cjs/mixins.js | 16 +- node_modules/ts-mixer/dist/cjs/proxy.js | 12 +- node_modules/ts-mixer/dist/cjs/util.js | 12 +- node_modules/ts-mixer/dist/esm/decorator.d.ts | 18 + node_modules/ts-mixer/dist/esm/index.d.ts | 4 + node_modules/ts-mixer/dist/esm/index.js | 23 +- node_modules/ts-mixer/dist/esm/index.min.js | 2 +- .../ts-mixer/dist/esm/mixin-tracking.d.ts | 4 + node_modules/ts-mixer/dist/esm/mixins.d.ts | 16 + node_modules/ts-mixer/dist/esm/proxy.d.ts | 16 + node_modules/ts-mixer/dist/esm/settings.d.ts | 7 + node_modules/ts-mixer/dist/esm/types.d.ts | 13 + node_modules/ts-mixer/dist/esm/util.d.ts | 27 + .../ts-mixer/dist/types/decorator.d.ts | 6 +- .../ts-mixer/dist/types/mixin-tracking.d.ts | 2 +- .../ts-mixer/dist/types/settings.d.ts | 2 +- node_modules/ts-mixer/dist/types/types.d.ts | 6 +- node_modules/ts-mixer/package.json | 2 +- node_modules/tslib/README.md | 2 +- node_modules/tslib/modules/index.d.ts | 35 + node_modules/tslib/modules/index.js | 9 + node_modules/tslib/package.json | 15 +- node_modules/tslib/tslib.d.ts | 32 + node_modules/tslib/tslib.es6.js | 75 +- node_modules/tslib/tslib.es6.mjs | 321 ++ node_modules/tslib/tslib.js | 55 +- node_modules/ws/README.md | 36 + node_modules/ws/lib/websocket.js | 6 +- node_modules/ws/package.json | 3 +- package-lock.json | 665 +--- 1010 files changed, 38622 insertions(+), 17071 deletions(-) create mode 100644 node_modules/@discordjs/formatters/CHANGELOG.md create mode 100644 node_modules/@discordjs/formatters/LICENSE create mode 100644 node_modules/@discordjs/formatters/README.md create mode 100644 node_modules/@discordjs/formatters/dist/index.d.ts create mode 100644 node_modules/@discordjs/formatters/dist/index.js create mode 100644 node_modules/@discordjs/formatters/dist/index.js.map create mode 100644 node_modules/@discordjs/formatters/dist/index.mjs create mode 100644 node_modules/@discordjs/formatters/dist/index.mjs.map create mode 100644 node_modules/@discordjs/formatters/package.json create mode 100644 node_modules/@discordjs/ws/CHANGELOG.md create mode 100644 node_modules/@discordjs/ws/LICENSE create mode 100644 node_modules/@discordjs/ws/README.md create mode 100644 node_modules/@discordjs/ws/dist/defaultWorker.d.ts create mode 100644 node_modules/@discordjs/ws/dist/defaultWorker.js create mode 100644 node_modules/@discordjs/ws/dist/defaultWorker.js.map create mode 100644 node_modules/@discordjs/ws/dist/defaultWorker.mjs create mode 100644 node_modules/@discordjs/ws/dist/defaultWorker.mjs.map create mode 100644 node_modules/@discordjs/ws/dist/index.d.ts create mode 100644 node_modules/@discordjs/ws/dist/index.js create mode 100644 node_modules/@discordjs/ws/dist/index.js.map create mode 100644 node_modules/@discordjs/ws/dist/index.mjs create mode 100644 node_modules/@discordjs/ws/dist/index.mjs.map create mode 100644 node_modules/@discordjs/ws/package.json create mode 100644 node_modules/@vladfrangu/async_event_emitter/CHANGELOG.md create mode 100644 node_modules/@vladfrangu/async_event_emitter/LICENSE.md create mode 100644 node_modules/@vladfrangu/async_event_emitter/README.md rename node_modules/{mysql/node_modules/safe-buffer/LICENSE => @vladfrangu/async_event_emitter/THIRD_PARTY_LICENSE.md} (54%) create mode 100644 node_modules/@vladfrangu/async_event_emitter/dist/index.d.ts create mode 100644 node_modules/@vladfrangu/async_event_emitter/dist/index.global.js create mode 100644 node_modules/@vladfrangu/async_event_emitter/dist/index.global.js.map create mode 100644 node_modules/@vladfrangu/async_event_emitter/dist/index.js create mode 100644 node_modules/@vladfrangu/async_event_emitter/dist/index.js.map create mode 100644 node_modules/@vladfrangu/async_event_emitter/dist/index.mjs create mode 100644 node_modules/@vladfrangu/async_event_emitter/dist/index.mjs.map create mode 100644 node_modules/@vladfrangu/async_event_emitter/package.json rename node_modules/{openai/node_modules => }/axios/CHANGELOG.md (100%) rename node_modules/{openai/node_modules => }/axios/LICENSE (100%) rename node_modules/{openai/node_modules => }/axios/README.md (100%) rename node_modules/{openai/node_modules => }/axios/SECURITY.md (100%) rename node_modules/{openai/node_modules => }/axios/UPGRADE_GUIDE.md (100%) rename node_modules/{openai/node_modules => }/axios/dist/axios.js (100%) rename node_modules/{openai/node_modules => }/axios/dist/axios.map (100%) rename node_modules/{openai/node_modules => }/axios/dist/axios.min.js (100%) rename node_modules/{openai/node_modules => }/axios/dist/axios.min.map (100%) rename node_modules/{openai/node_modules => }/axios/index.d.ts (100%) rename node_modules/{openai/node_modules => }/axios/index.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/adapters/README.md (100%) rename node_modules/{openai/node_modules => }/axios/lib/adapters/http.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/adapters/xhr.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/axios.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/cancel/Cancel.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/cancel/CancelToken.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/cancel/isCancel.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/Axios.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/InterceptorManager.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/README.md (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/buildFullPath.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/createError.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/dispatchRequest.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/enhanceError.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/mergeConfig.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/settle.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/core/transformData.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/defaults/index.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/defaults/transitional.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/env/README.md (100%) rename node_modules/{openai/node_modules => }/axios/lib/env/data.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/README.md (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/bind.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/buildURL.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/combineURLs.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/cookies.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/deprecatedMethod.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/isAbsoluteURL.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/isAxiosError.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/isURLSameOrigin.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/normalizeHeaderName.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/parseHeaders.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/spread.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/toFormData.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/helpers/validator.js (100%) rename node_modules/{openai/node_modules => }/axios/lib/utils.js (100%) rename node_modules/{openai/node_modules => }/axios/package.json (100%) rename node_modules/{openai/node_modules => }/axios/tsconfig.json (100%) rename node_modules/{openai/node_modules => }/axios/tslint.json (100%) delete mode 100644 node_modules/core-util-is/float.patch delete mode 100644 node_modules/core-util-is/test.js delete mode 100644 node_modules/discord.js/src/WebSocket.js create mode 100644 node_modules/discord.js/src/client/actions/GuildAuditLogEntryCreate.js create mode 100644 node_modules/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js create mode 100644 node_modules/discord.js/src/structures/ApplicationRoleConnectionMetadata.js create mode 100644 node_modules/discord.js/src/util/GuildMemberFlagsBitField.js delete mode 100644 node_modules/mysql/node_modules/readable-stream/README.md delete mode 100644 node_modules/mysql/node_modules/readable-stream/lib/internal/streams/destroy.js delete mode 100644 node_modules/mysql/node_modules/readable-stream/package.json delete mode 100644 node_modules/mysql/node_modules/safe-buffer/README.md delete mode 100644 node_modules/mysql/node_modules/safe-buffer/index.d.ts delete mode 100644 node_modules/mysql/node_modules/safe-buffer/index.js delete mode 100644 node_modules/mysql/node_modules/safe-buffer/package.json delete mode 100644 node_modules/mysql/node_modules/string_decoder/LICENSE delete mode 100644 node_modules/mysql/node_modules/string_decoder/README.md delete mode 100644 node_modules/mysql/node_modules/string_decoder/lib/string_decoder.js delete mode 100644 node_modules/mysql/node_modules/string_decoder/package.json rename node_modules/{mysql/node_modules => }/readable-stream/.travis.yml (100%) rename node_modules/{mysql/node_modules => }/readable-stream/doc/wg-meetings/2015-01-30.md (100%) rename node_modules/{mysql/node_modules => }/readable-stream/duplex-browser.js (100%) rename node_modules/{mysql/node_modules => }/readable-stream/duplex.js (100%) rename node_modules/{mysql/node_modules => }/readable-stream/lib/internal/streams/BufferList.js (100%) rename node_modules/{mysql/node_modules => }/readable-stream/passthrough.js (100%) rename node_modules/{mysql/node_modules => }/readable-stream/transform.js (100%) rename node_modules/{mysql/node_modules => }/readable-stream/writable-browser.js (100%) rename node_modules/{mysql/node_modules => }/readable-stream/writable.js (100%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/CONTRIBUTING.md (100%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/GOVERNANCE.md (100%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/LICENSE (100%) create mode 100644 node_modules/readable-web-to-node-stream/node_modules/readable-stream/README.md rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/errors-browser.js (100%) rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/errors.js (100%) rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/experimentalWarning.js (100%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/lib/_stream_duplex.js (69%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/lib/_stream_passthrough.js (90%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/lib/_stream_readable.js (67%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/lib/_stream_transform.js (86%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/lib/_stream_writable.js (77%) rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/lib/internal/streams/async_iterator.js (85%) rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/lib/internal/streams/buffer_list.js (69%) create mode 100644 node_modules/readable-web-to-node-stream/node_modules/readable-stream/lib/internal/streams/destroy.js rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/lib/internal/streams/end-of-stream.js (99%) rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/lib/internal/streams/from-browser.js (100%) rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/lib/internal/streams/from.js (54%) rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/lib/internal/streams/pipeline.js (91%) rename node_modules/{ => readable-web-to-node-stream/node_modules}/readable-stream/lib/internal/streams/state.js (96%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/lib/internal/streams/stream-browser.js (100%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/lib/internal/streams/stream.js (100%) create mode 100644 node_modules/readable-web-to-node-stream/node_modules/readable-stream/package.json rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/readable-browser.js (71%) rename node_modules/{mysql => readable-web-to-node-stream}/node_modules/readable-stream/readable.js (61%) rename node_modules/{mysql/node_modules => }/string_decoder/.travis.yml (100%) create mode 100644 node_modules/ts-mixer/dist/esm/decorator.d.ts create mode 100644 node_modules/ts-mixer/dist/esm/index.d.ts create mode 100644 node_modules/ts-mixer/dist/esm/mixin-tracking.d.ts create mode 100644 node_modules/ts-mixer/dist/esm/mixins.d.ts create mode 100644 node_modules/ts-mixer/dist/esm/proxy.d.ts create mode 100644 node_modules/ts-mixer/dist/esm/settings.d.ts create mode 100644 node_modules/ts-mixer/dist/esm/types.d.ts create mode 100644 node_modules/ts-mixer/dist/esm/util.d.ts create mode 100644 node_modules/tslib/modules/index.d.ts create mode 100644 node_modules/tslib/tslib.es6.mjs diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 26ddb1a..f904e84 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -5,51 +5,82 @@ "requires": true, "packages": { "node_modules/@discordjs/builders": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.4.0.tgz", - "integrity": "sha512-nEeTCheTTDw5kO93faM1j8ZJPonAX86qpq/QVoznnSa8WWcCgJpjlu6GylfINTDW6o7zZY0my2SYdxx2mfNwGA==", + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.6.3.tgz", + "integrity": "sha512-CTCh8NqED3iecTNuiz49mwSsrc2iQb4d0MjMdmS/8pb69Y4IlzJ/DIy/p5GFlgOrFbNO2WzMHkWKQSiJ3VNXaw==", "dependencies": { - "@discordjs/util": "^0.1.0", - "@sapphire/shapeshift": "^3.7.1", - "discord-api-types": "^0.37.20", + "@discordjs/formatters": "^0.3.1", + "@discordjs/util": "^0.3.1", + "@sapphire/shapeshift": "^3.8.2", + "discord-api-types": "^0.37.41", "fast-deep-equal": "^3.1.3", - "ts-mixer": "^6.0.2", - "tslib": "^2.4.1" + "ts-mixer": "^6.0.3", + "tslib": "^2.5.0" }, "engines": { "node": ">=16.9.0" } }, "node_modules/@discordjs/collection": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.3.0.tgz", - "integrity": "sha512-ylt2NyZ77bJbRij4h9u/wVy7qYw/aDqQLWnadjvDqW/WoWCxrsX6M3CIw9GVP5xcGCDxsrKj5e0r5evuFYwrKg==", + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.1.tgz", + "integrity": "sha512-aWEc9DCf3TMDe9iaJoOnO2+JVAjeRNuRxPZQA6GVvBf+Z3gqUuWYBy2NWh4+5CLYq5uoc3MOvUQ5H5m8CJBqOA==", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.3.1.tgz", + "integrity": "sha512-M7X4IGiSeh4znwcRGcs+49B5tBkNDn4k5bmhxJDAUhRxRHTiFAOTVUNQ6yAKySu5jZTnCbSvTYHW3w0rAzV1MA==", + "dependencies": { + "discord-api-types": "^0.37.41" + }, "engines": { "node": ">=16.9.0" } }, "node_modules/@discordjs/rest": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-1.5.0.tgz", - "integrity": "sha512-lXgNFqHnbmzp5u81W0+frdXN6Etf4EUi8FAPcWpSykKd8hmlWh1xy6BmE0bsJypU1pxohaA8lQCgp70NUI3uzA==", + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-1.7.1.tgz", + "integrity": "sha512-Ofa9UqT0U45G/eX86cURQnX7gzOJLG2oC28VhIk/G6IliYgQF7jFByBJEykPSHE4MxPhqCleYvmsrtfKh1nYmQ==", "dependencies": { - "@discordjs/collection": "^1.3.0", - "@discordjs/util": "^0.1.0", + "@discordjs/collection": "^1.5.1", + "@discordjs/util": "^0.3.0", "@sapphire/async-queue": "^1.5.0", - "@sapphire/snowflake": "^3.2.2", - "discord-api-types": "^0.37.23", - "file-type": "^18.0.0", - "tslib": "^2.4.1", - "undici": "^5.13.0" + "@sapphire/snowflake": "^3.4.2", + "discord-api-types": "^0.37.41", + "file-type": "^18.3.0", + "tslib": "^2.5.0", + "undici": "^5.22.0" }, "engines": { "node": ">=16.9.0" } }, "node_modules/@discordjs/util": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-0.1.0.tgz", - "integrity": "sha512-e7d+PaTLVQav6rOc2tojh2y6FE8S7REkqLldq1XF4soCx74XB/DIjbVbVLtBemf0nLW77ntz0v+o5DytKwFNLQ==", + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-0.3.1.tgz", + "integrity": "sha512-HxXKYKg7vohx2/OupUN/4Sd02Ev3PBJ5q0gtjdcvXb0ErCva8jNHWfe/v5sU3UKjIB/uxOhc+TDOnhqffj9pRA==", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/ws": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-0.8.3.tgz", + "integrity": "sha512-hcYtppanjHecbdNyCKQNH2I4RP9UrphDgmRgLYrATEQF1oo4sYSve7ZmGsBEXSzH72MO2tBPdWSThunbxUVk0g==", + "dependencies": { + "@discordjs/collection": "^1.5.1", + "@discordjs/rest": "^1.7.1", + "@discordjs/util": "^0.3.1", + "@sapphire/async-queue": "^1.5.0", + "@types/ws": "^8.5.4", + "@vladfrangu/async_event_emitter": "^2.2.1", + "discord-api-types": "^0.37.41", + "tslib": "^2.5.0", + "ws": "^8.13.0" + }, "engines": { "node": ">=16.9.0" } @@ -64,9 +95,9 @@ } }, "node_modules/@sapphire/shapeshift": { - "version": "3.8.1", - "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.8.1.tgz", - "integrity": "sha512-xG1oXXBhCjPKbxrRTlox9ddaZTvVpOhYLmKmApD/vIWOV1xEYXnpoFs68zHIZBGbqztq6FrUPNPerIrO1Hqeaw==", + "version": "3.9.2", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.9.2.tgz", + "integrity": "sha512-YRbCXWy969oGIdqR/wha62eX8GNHsvyYi0Rfd4rNW6tSVVa8p0ELiMEuOH/k8rgtvRoM+EMV7Csqz77YdwiDpA==", "dependencies": { "fast-deep-equal": "^3.1.3", "lodash": "^4.17.21" @@ -77,9 +108,9 @@ } }, "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==", + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.1.tgz", + "integrity": "sha512-BxcYGzgEsdlG0dKAyOm0ehLGm2CafIrfQTZGWgkfKYbj+pNNsorZ7EotuZukc2MT70E0UbppVbtpBrqpzVzjNA==", "engines": { "node": ">=v14.0.0", "npm": ">=7.0.0" @@ -91,23 +122,40 @@ "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==" }, "node_modules/@types/node": { - "version": "18.11.18", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", - "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==" + "version": "20.3.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.1.tgz", + "integrity": "sha512-EhcH/wvidPy1WeML3TtYFGR83UzjxeWRen9V402T8aUGYsCHOmfoisV3ZSg03gAFIbLq8TnWOJ0f4cALtnSEUg==" }, "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==", + "version": "8.5.5", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz", + "integrity": "sha512-lwhs8hktwxSjf9UaZ9tG5M03PGogvFaH8gUgLNbN9HKIg0dvv6q+gkSuJ8HN4/VbyxkuLzCjlN7GquQ0gUJfIg==", "dependencies": { "@types/node": "*" } }, + "node_modules/@vladfrangu/async_event_emitter": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.2.2.tgz", + "integrity": "sha512-HIzRG7sy88UZjBJamssEczH5q7t5+axva19UbZLO6u0ySbYPrwzWiXBcC0WuHyhKKoeCyneH+FvYzKQq/zTtkQ==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" }, + "node_modules/axios": { + "version": "0.26.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz", + "integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==", + "dependencies": { + "follow-redirects": "^1.14.8" + } + }, "node_modules/bignumber.js": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz", @@ -139,9 +187,9 @@ } }, "node_modules/core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" }, "node_modules/delayed-stream": { "version": "1.0.0", @@ -152,36 +200,38 @@ } }, "node_modules/discord-api-types": { - "version": "0.37.30", - "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.30.tgz", - "integrity": "sha512-TzNF28zWV63clYW1+rbKT2+2qSI+lw/aNG3lyP2fIj5NioGPz4C+bCSvwhP3Ly3uLwL7v8FxIiu8XKGDsvuwWA==" + "version": "0.37.46", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.46.tgz", + "integrity": "sha512-DeSi5WSWYTeXJJhdwACtpQycY3g4vLRvE2Ol5IlC0o//P2W+8jXPF447PuJn2fRH1nD7JGEJ3YMb0NB9+OQ7BQ==" }, "node_modules/discord.js": { - "version": "14.7.1", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.7.1.tgz", - "integrity": "sha512-1FECvqJJjjeYcjSm0IGMnPxLqja/pmG1B0W2l3lUY2Gi4KXiyTeQmU1IxWcbXHn2k+ytP587mMWqva2IA87EbA==", + "version": "14.11.0", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.11.0.tgz", + "integrity": "sha512-CkueWYFQ28U38YPR8HgsBR/QT35oPpMbEsTNM30Fs8loBIhnA4s70AwQEoy6JvLcpWWJO7GY0y2BUzZmuBMepQ==", "dependencies": { - "@discordjs/builders": "^1.4.0", - "@discordjs/collection": "^1.3.0", - "@discordjs/rest": "^1.4.0", - "@discordjs/util": "^0.1.0", - "@sapphire/snowflake": "^3.2.2", - "@types/ws": "^8.5.3", - "discord-api-types": "^0.37.20", + "@discordjs/builders": "^1.6.3", + "@discordjs/collection": "^1.5.1", + "@discordjs/formatters": "^0.3.1", + "@discordjs/rest": "^1.7.1", + "@discordjs/util": "^0.3.1", + "@discordjs/ws": "^0.8.3", + "@sapphire/snowflake": "^3.4.2", + "@types/ws": "^8.5.4", + "discord-api-types": "^0.37.41", "fast-deep-equal": "^3.1.3", "lodash.snakecase": "^4.1.1", - "tslib": "^2.4.1", - "undici": "^5.13.0", - "ws": "^8.11.0" + "tslib": "^2.5.0", + "undici": "^5.22.0", + "ws": "^8.13.0" }, "engines": { "node": ">=16.9.0" } }, "node_modules/dotenv": { - "version": "16.1.4", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.1.4.tgz", - "integrity": "sha512-m55RtE8AsPeJBpOIFKihEmqUcoVncQIwo7x9U8ZwLEZw9ZpXboz2c+rvog+jUaJvVrZ5kBOeYQBX5+8Aa/OZQw==", + "version": "16.3.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz", + "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==", "engines": { "node": ">=12" }, @@ -195,9 +245,9 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" }, "node_modules/file-type": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/file-type/-/file-type-18.2.0.tgz", - "integrity": "sha512-M3RQMWY3F2ykyWZ+IHwNCjpnUmukYhtdkGGC1ZVEUb0ve5REGF7NNJ4Q9ehCUabtQKtSVFOMbFTXgJlFb0DQIg==", + "version": "18.5.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-18.5.0.tgz", + "integrity": "sha512-yvpl5U868+V6PqXHMmsESpg6unQ5GfnPssl4dxdJudBrr9qy7Fddt7EVX1VLlddFfe8Gj9N7goCZH22FXuSQXQ==", "dependencies": { "readable-web-to-node-stream": "^3.0.2", "strtok3": "^7.0.0", @@ -319,50 +369,15 @@ "node": ">= 0.6" } }, - "node_modules/mysql/node_modules/readable-stream": { - "version": "2.3.7", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", - "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "node_modules/mysql/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" - }, - "node_modules/mysql/node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, "node_modules/openai": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/openai/-/openai-3.2.1.tgz", - "integrity": "sha512-762C9BNlJPbjjlWZi4WYK9iM2tAVAv0uUp1UmI34vb0CN5T2mjB/qM6RYBmNKMh/dN9fC+bxqPwWJZUTWW052A==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-3.3.0.tgz", + "integrity": "sha512-uqxI/Au+aPRnsaQRe8CojU0eCR7I0mBiKjD3sNMzY6DaC1ZVrc85u98mtJW6voDug8fgGN+DIZmTDxTthxb7dQ==", "dependencies": { "axios": "^0.26.0", "form-data": "^4.0.0" } }, - "node_modules/openai/node_modules/axios": { - "version": "0.26.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz", - "integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==", - "dependencies": { - "follow-redirects": "^1.14.8" - } - }, "node_modules/peek-readable": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-5.0.0.tgz", @@ -381,16 +396,17 @@ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" }, "node_modules/readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" } }, "node_modules/readable-web-to-node-stream": { @@ -408,24 +424,23 @@ "url": "https://github.com/sponsors/Borewit" } }, + "node_modules/readable-web-to-node-stream/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/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" - } - ] + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" }, "node_modules/sqlstring": { "version": "2.3.1", @@ -444,11 +459,11 @@ } }, "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==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dependencies": { - "safe-buffer": "~5.2.0" + "safe-buffer": "~5.1.0" } }, "node_modules/strtok3": { @@ -484,14 +499,14 @@ } }, "node_modules/ts-mixer": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.2.tgz", - "integrity": "sha512-zvHx3VM83m2WYCE8XL99uaM7mFwYSkjR2OZti98fabHrwkjsCvgwChda5xctein3xGOyaQhtTeDq/1H/GNvF3A==" + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.3.tgz", + "integrity": "sha512-k43M7uCG1AkTyxgnmI5MPwKoUvS/bRvLvUb7+Pgpdlmok8AoqmUaZxUUw8zKM5B1lqZrt41GjYgnvAi0fppqgQ==" }, "node_modules/tslib": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", - "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==" + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", + "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==" }, "node_modules/undici": { "version": "5.22.1", @@ -510,9 +525,9 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" }, "node_modules/ws": { - "version": "8.12.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.12.0.tgz", - "integrity": "sha512-kU62emKIdKVeEIOIKVegvqpXMSTAMLJozpHZaJNDYqBjzlSYXQGviYwN1osDLJ9av68qHd4a2oSjd7yD4pacig==", + "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" }, diff --git a/node_modules/@discordjs/builders/CHANGELOG.md b/node_modules/@discordjs/builders/CHANGELOG.md index 0ab0974..de5bb4f 100644 --- a/node_modules/@discordjs/builders/CHANGELOG.md +++ b/node_modules/@discordjs/builders/CHANGELOG.md @@ -2,6 +2,70 @@ All notable changes to this project will be documented in this file. +# [@discordjs/builders@1.6.3](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.2...@discordjs/builders@1.6.3) - (2023-05-01) + +## Refactor + +- Remove `@discordjs/util` re-export (#9488) ([54ceedf](https://github.com/discordjs/discord.js/commit/54ceedf6c535d4641643d4106b6286cbef09de4a)) + +# [@discordjs/builders@1.6.2](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.1...@discordjs/builders@1.6.2) - (2023-05-01) + +## Bug Fixes + +- **BaseSelectMenuBuilder:** Modify class to be `abstract` (#9358) ([ca4de2d](https://github.com/discordjs/discord.js/commit/ca4de2d9c6bc204e85d1b7eae7eabd23dbeb4475)) +- Correct `@link` tags that involve parents (#9351) ([fbbce3e](https://github.com/discordjs/discord.js/commit/fbbce3eb4ba20bc0c4806ca2259d1f86001594be)) +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Reference package names properly (#9426) ([d6bca9b](https://github.com/discordjs/discord.js/commit/d6bca9bb4d976dc069a5039250db7d5b3e9142ef)) +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) +- **builders:** Add some basic documentation (#9359) ([8073561](https://github.com/discordjs/discord.js/commit/8073561824f911d1a18d0b4f1de39f452bc69fa9)) +- Use `@link` in `@see` (#9348) ([d66d113](https://github.com/discordjs/discord.js/commit/d66d1133331b81563588db4500c63a18c3c3dfae)) + +# [@discordjs/builders@1.6.2](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.1...@discordjs/builders@1.6.2) - (2023-05-01) + +## Bug Fixes + +- **BaseSelectMenuBuilder:** Modify class to be `abstract` (#9358) ([ca4de2d](https://github.com/discordjs/discord.js/commit/ca4de2d9c6bc204e85d1b7eae7eabd23dbeb4475)) +- Correct `@link` tags that involve parents (#9351) ([fbbce3e](https://github.com/discordjs/discord.js/commit/fbbce3eb4ba20bc0c4806ca2259d1f86001594be)) +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Reference package names properly (#9426) ([d6bca9b](https://github.com/discordjs/discord.js/commit/d6bca9bb4d976dc069a5039250db7d5b3e9142ef)) +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) +- **builders:** Add some basic documentation (#9359) ([8073561](https://github.com/discordjs/discord.js/commit/8073561824f911d1a18d0b4f1de39f452bc69fa9)) +- Use `@link` in `@see` (#9348) ([d66d113](https://github.com/discordjs/discord.js/commit/d66d1133331b81563588db4500c63a18c3c3dfae)) + +# [@discordjs/builders@1.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.5.0...@discordjs/builders@1.6.0) - (2023-04-01) + +## Bug Fixes + +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/builders@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.4.0...@discordjs/builders@1.5.0) - (2023-03-12) + +## Documentation + +- **EmbedBuilder#spliceFields:** Fix a typo (#9159) ([4367ab9](https://github.com/discordjs/discord.js/commit/4367ab930227048868db3ed8437f6c4507ff32e1)) +- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28)) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) +- **StringSelectMenu:** Add `spliceOptions()` (#8937) ([a6941d5](https://github.com/discordjs/discord.js/commit/a6941d536ce24ed2b5446a154cbc886b2b97c63a)) +- Add support for nsfw commands (#7976) ([7a51344](https://github.com/discordjs/discord.js/commit/7a5134459c5f06864bf74631d83b96d9c21b72d8)) +- Add `@discordjs/formatters` (#8889) ([3fca638](https://github.com/discordjs/discord.js/commit/3fca638a8470dcea2f79ddb9f18526dbc0017c88)) + +## Styling + +- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b)) + # [@discordjs/builders@1.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.3.0...@discordjs/builders@1.4.0) - (2022-11-28) ## Bug Fixes diff --git a/node_modules/@discordjs/builders/README.md b/node_modules/@discordjs/builders/README.md index 59508dd..2981f19 100644 --- a/node_modules/@discordjs/builders/README.md +++ b/node_modules/@discordjs/builders/README.md @@ -16,11 +16,15 @@

+## About + +`@discordjs/builders` is a utility package for easily building Discord API payloads. + ## Installation **Node.js 16.9.0 or newer is required.** -```sh-session +```sh npm install @discordjs/builders yarn add @discordjs/builders pnpm add @discordjs/builders @@ -28,16 +32,14 @@ pnpm add @discordjs/builders ## Examples -Here are some examples for the builders and utilities you can find in this package: - -- [Slash Command Builders][example] +You can find examples of how to use the builders in the [Slash Command Builders][example] examples. ## Links - [Website][website] ([source][website-source]) - [Documentation][documentation] - [Guide][guide] ([source][guide-source]) - See also the [Update Guide][guide-update], including updated and removed items in the library. + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. - [discord.js Discord server][discord] - [Discord API Discord server][discord-api] - [GitHub][source] @@ -52,13 +54,12 @@ See [the contribution guide][contributing] if you'd like to submit a PR. ## Help -If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle -nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. [example]: https://github.com/discordjs/discord.js/blob/main/packages/builders/docs/examples/Slash%20Command%20Builders.md -[website]: https://discord.js.org/ +[website]: https://discord.js.org [website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website -[documentation]: https://discord.js.org/#/docs/builders +[documentation]: https://discord.js.org/docs/packages/builders/stable [guide]: https://discordjs.guide/ [guide-source]: https://github.com/discordjs/guide [guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html diff --git a/node_modules/@discordjs/builders/dist/index.d.ts b/node_modules/@discordjs/builders/dist/index.d.ts index f5df124..5237d9b 100644 --- a/node_modules/@discordjs/builders/dist/index.d.ts +++ b/node_modules/@discordjs/builders/dist/index.d.ts @@ -1,9 +1,7 @@ import * as _sapphire_shapeshift from '@sapphire/shapeshift'; -import { APIEmbedField, APIEmbedAuthor, APIEmbedFooter, APIEmbedImage, APIEmbed, APISelectMenuOption, APIMessageComponentEmoji, ButtonStyle, ChannelType, APIActionRowComponent, APIActionRowComponentTypes, APIBaseComponent, ComponentType, APIButtonComponent, APISelectMenuComponent, APIChannelSelectComponent, APIMentionableSelectComponent, APIRoleSelectComponent, APIStringSelectComponent, APIUserSelectComponent, APITextInputComponent, TextInputStyle, APIMessageActionRowComponent, APIModalActionRowComponent, APIModalComponent, APIMessageComponent, APIModalInteractionResponseCallbackData, LocalizationMap, LocaleString, ApplicationCommandOptionType, APIApplicationCommandBasicOption, APIApplicationCommandAttachmentOption, APIApplicationCommandBooleanOption, APIApplicationCommandChannelOption, APIApplicationCommandOptionChoice, APIApplicationCommandIntegerOption, APIApplicationCommandMentionableOption, APIApplicationCommandNumberOption, APIApplicationCommandRoleOption, APIApplicationCommandStringOption, APIApplicationCommandUserOption, APIApplicationCommandSubcommandGroupOption, APIApplicationCommandSubcommandOption, Permissions, RESTPostAPIChatInputApplicationCommandsJSONBody, APIApplicationCommandOption, Locale, RESTPostAPIContextMenuApplicationCommandsJSONBody, ApplicationCommandType } from 'discord-api-types/v10'; -import { URL } from 'node:url'; -import { Snowflake } from 'discord-api-types/globals'; +import { APIEmbedField, APIEmbedAuthor, APIEmbedFooter, APIEmbedImage, APIEmbed, APISelectMenuOption, APIMessageComponentEmoji, ButtonStyle, ChannelType, APIActionRowComponent, APIActionRowComponentTypes, APIBaseComponent, ComponentType, APIButtonComponent, APISelectMenuComponent, APIChannelSelectComponent, APIMentionableSelectComponent, APIRoleSelectComponent, APIStringSelectComponent, APIUserSelectComponent, APITextInputComponent, TextInputStyle, APIMessageActionRowComponent, APIModalActionRowComponent, APIModalComponent, APIMessageComponent, APIModalInteractionResponseCallbackData, LocalizationMap, LocaleString, ApplicationCommandOptionType, APIApplicationCommandBasicOption, APIApplicationCommandAttachmentOption, APIApplicationCommandBooleanOption, APIApplicationCommandChannelOption, APIApplicationCommandOptionChoice, APIApplicationCommandIntegerOption, APIApplicationCommandMentionableOption, APIApplicationCommandNumberOption, APIApplicationCommandRoleOption, APIApplicationCommandStringOption, APIApplicationCommandUserOption, APIApplicationCommandSubcommandGroupOption, APIApplicationCommandSubcommandOption, Permissions, RESTPostAPIChatInputApplicationCommandsJSONBody, APIApplicationCommandOption, Locale, ApplicationCommandType, RESTPostAPIContextMenuApplicationCommandsJSONBody } from 'discord-api-types/v10'; +export * from '@discordjs/formatters'; import { JSONEncodable, Equatable } from '@discordjs/util'; -export * from '@discordjs/util'; declare const fieldNamePredicate: _sapphire_shapeshift.StringValidator; declare const fieldValuePredicate: _sapphire_shapeshift.StringValidator; @@ -54,92 +52,136 @@ declare const embedFooterPredicate: _sapphire_shapeshift.ObjectValidator<{ declare const timestampPredicate: _sapphire_shapeshift.UnionValidator; declare const titlePredicate: _sapphire_shapeshift.UnionValidator; -declare const Assertions$5_fieldNamePredicate: typeof fieldNamePredicate; -declare const Assertions$5_fieldValuePredicate: typeof fieldValuePredicate; -declare const Assertions$5_fieldInlinePredicate: typeof fieldInlinePredicate; -declare const Assertions$5_embedFieldPredicate: typeof embedFieldPredicate; -declare const Assertions$5_embedFieldsArrayPredicate: typeof embedFieldsArrayPredicate; -declare const Assertions$5_fieldLengthPredicate: typeof fieldLengthPredicate; -declare const Assertions$5_validateFieldLength: typeof validateFieldLength; -declare const Assertions$5_authorNamePredicate: typeof authorNamePredicate; -declare const Assertions$5_imageURLPredicate: typeof imageURLPredicate; -declare const Assertions$5_urlPredicate: typeof urlPredicate; -declare const Assertions$5_embedAuthorPredicate: typeof embedAuthorPredicate; declare const Assertions$5_RGBPredicate: typeof RGBPredicate; +declare const Assertions$5_authorNamePredicate: typeof authorNamePredicate; declare const Assertions$5_colorPredicate: typeof colorPredicate; declare const Assertions$5_descriptionPredicate: typeof descriptionPredicate; -declare const Assertions$5_footerTextPredicate: typeof footerTextPredicate; +declare const Assertions$5_embedAuthorPredicate: typeof embedAuthorPredicate; +declare const Assertions$5_embedFieldPredicate: typeof embedFieldPredicate; +declare const Assertions$5_embedFieldsArrayPredicate: typeof embedFieldsArrayPredicate; declare const Assertions$5_embedFooterPredicate: typeof embedFooterPredicate; +declare const Assertions$5_fieldInlinePredicate: typeof fieldInlinePredicate; +declare const Assertions$5_fieldLengthPredicate: typeof fieldLengthPredicate; +declare const Assertions$5_fieldNamePredicate: typeof fieldNamePredicate; +declare const Assertions$5_fieldValuePredicate: typeof fieldValuePredicate; +declare const Assertions$5_footerTextPredicate: typeof footerTextPredicate; +declare const Assertions$5_imageURLPredicate: typeof imageURLPredicate; declare const Assertions$5_timestampPredicate: typeof timestampPredicate; declare const Assertions$5_titlePredicate: typeof titlePredicate; +declare const Assertions$5_urlPredicate: typeof urlPredicate; +declare const Assertions$5_validateFieldLength: typeof validateFieldLength; declare namespace Assertions$5 { export { - Assertions$5_fieldNamePredicate as fieldNamePredicate, - Assertions$5_fieldValuePredicate as fieldValuePredicate, - Assertions$5_fieldInlinePredicate as fieldInlinePredicate, - Assertions$5_embedFieldPredicate as embedFieldPredicate, - Assertions$5_embedFieldsArrayPredicate as embedFieldsArrayPredicate, - Assertions$5_fieldLengthPredicate as fieldLengthPredicate, - Assertions$5_validateFieldLength as validateFieldLength, - Assertions$5_authorNamePredicate as authorNamePredicate, - Assertions$5_imageURLPredicate as imageURLPredicate, - Assertions$5_urlPredicate as urlPredicate, - Assertions$5_embedAuthorPredicate as embedAuthorPredicate, Assertions$5_RGBPredicate as RGBPredicate, + Assertions$5_authorNamePredicate as authorNamePredicate, Assertions$5_colorPredicate as colorPredicate, Assertions$5_descriptionPredicate as descriptionPredicate, - Assertions$5_footerTextPredicate as footerTextPredicate, + Assertions$5_embedAuthorPredicate as embedAuthorPredicate, + Assertions$5_embedFieldPredicate as embedFieldPredicate, + Assertions$5_embedFieldsArrayPredicate as embedFieldsArrayPredicate, Assertions$5_embedFooterPredicate as embedFooterPredicate, + Assertions$5_fieldInlinePredicate as fieldInlinePredicate, + Assertions$5_fieldLengthPredicate as fieldLengthPredicate, + Assertions$5_fieldNamePredicate as fieldNamePredicate, + Assertions$5_fieldValuePredicate as fieldValuePredicate, + Assertions$5_footerTextPredicate as footerTextPredicate, + Assertions$5_imageURLPredicate as imageURLPredicate, Assertions$5_timestampPredicate as timestampPredicate, Assertions$5_titlePredicate as titlePredicate, + Assertions$5_urlPredicate as urlPredicate, + Assertions$5_validateFieldLength as validateFieldLength, }; } +/** + * Normalizes data that is a rest parameter or an array into an array with a depth of 1. + * + * @typeParam T - The data that must satisfy {@link RestOrArray}. + * @param arr - The (possibly variadic) data to normalize + */ declare function normalizeArray(arr: RestOrArray): T[]; +/** + * Represents data that may be an array or came from a rest parameter. + * + * @remarks + * This type is used throughout builders to ensure both an array and variadic arguments + * may be used. It is normalized with {@link normalizeArray}. + */ type RestOrArray = T[] | [T[]]; +/** + * A tuple satisfying the RGB color model. + * + * @see {@link https://developer.mozilla.org/docs/Glossary/RGB} + */ type RGBTuple = [red: number, green: number, blue: number]; +/** + * The base icon data typically used in payloads. + */ interface IconData { /** - * The URL of the icon + * The URL of the icon. */ iconURL?: string; /** - * The proxy URL of the icon + * The proxy URL of the icon. */ proxyIconURL?: string; } +/** + * Represents the author data of an embed. + */ type EmbedAuthorData = IconData & Omit; +/** + * Represents the author options of an embed. + */ type EmbedAuthorOptions = Omit; +/** + * Represents the footer data of an embed. + */ type EmbedFooterData = IconData & Omit; +/** + * Represents the footer options of an embed. + */ type EmbedFooterOptions = Omit; +/** + * Represents the image data of an embed. + */ interface EmbedImageData extends Omit { /** - * The proxy URL for the image + * The proxy URL for the image. */ proxyURL?: string; } /** - * Represents a embed in a message (image/video preview, rich embed, etc.) + * A builder that creates API-compatible JSON data for embeds. */ declare class EmbedBuilder { + /** + * The API data associated with this embed. + */ readonly data: APIEmbed; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ constructor(data?: APIEmbed); /** - * Appends fields to the embed + * Appends fields to the embed. * * @remarks * This method accepts either an array of fields or a variable number of field parameters. * The maximum amount of fields that can be added is 25. * @example - * Using an array + * Using an array: * ```ts * const fields: APIEmbedField[] = ...; * const embed = new EmbedBuilder() * .addFields(fields); * ``` * @example - * Using rest parameters (variadic) + * Using rest parameters (variadic): * ```ts * const embed = new EmbedBuilder() * .addFields( @@ -151,27 +193,27 @@ declare class EmbedBuilder { */ addFields(...fields: RestOrArray): this; /** - * Removes, replaces, or inserts fields in the embed. + * Removes, replaces, or inserts fields for this embed. * * @remarks * This method behaves similarly - * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice}. + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. * The maximum amount of fields that can be added is 25. * * It's useful for modifying and adjusting order of the already-existing fields of an embed. * @example - * Remove the first field + * Remove the first field: * ```ts * embed.spliceFields(0, 1); * ``` * @example - * Remove the first n fields + * Remove the first n fields: * ```ts - * const n = 4 + * const n = 4; * embed.spliceFields(0, n); * ``` * @example - * Remove the last field + * Remove the last field: * ```ts * embed.spliceFields(-1, 1); * ``` @@ -181,7 +223,7 @@ declare class EmbedBuilder { */ spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this; /** - * Sets the embed's fields + * Sets the fields for this embed. * * @remarks * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, @@ -192,350 +234,80 @@ declare class EmbedBuilder { */ setFields(...fields: RestOrArray): this; /** - * Sets the author of this embed + * Sets the author of this embed. * - * @param options - The options for the author + * @param options - The options to use */ setAuthor(options: EmbedAuthorOptions | null): this; /** - * Sets the color of this embed + * Sets the color of this embed. * - * @param color - The color of the embed + * @param color - The color to use */ setColor(color: RGBTuple | number | null): this; /** - * Sets the description of this embed + * Sets the description of this embed. * - * @param description - The description + * @param description - The description to use */ setDescription(description: string | null): this; /** - * Sets the footer of this embed + * Sets the footer of this embed. * - * @param options - The options for the footer + * @param options - The footer to use */ setFooter(options: EmbedFooterOptions | null): this; /** - * Sets the image of this embed + * Sets the image of this embed. * - * @param url - The URL of the image + * @param url - The image URL to use */ setImage(url: string | null): this; /** - * Sets the thumbnail of this embed + * Sets the thumbnail of this embed. * - * @param url - The URL of the thumbnail + * @param url - The thumbnail URL to use */ setThumbnail(url: string | null): this; /** - * Sets the timestamp of this embed + * Sets the timestamp of this embed. * - * @param timestamp - The timestamp or date + * @param timestamp - The timestamp or date to use */ setTimestamp(timestamp?: Date | number | null): this; /** - * Sets the title of this embed + * Sets the title for this embed. * - * @param title - The title + * @param title - The title to use */ setTitle(title: string | null): this; /** - * Sets the URL of this embed + * Sets the URL of this embed. * - * @param url - The URL + * @param url - The URL to use */ setURL(url: string | null): this; /** - * Transforms the embed to a plain object + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. */ toJSON(): APIEmbed; } /** - * Wraps the content inside a codeblock with no language - * - * @param content - The content to wrap - */ -declare function codeBlock(content: C): `\`\`\`\n${C}\n\`\`\``; -/** - * Wraps the content inside a codeblock with the specified language - * - * @param language - The language for the codeblock - * @param content - The content to wrap - */ -declare function codeBlock(language: L, content: C): `\`\`\`${L}\n${C}\n\`\`\``; -/** - * Wraps the content inside \`backticks\`, which formats it as inline code - * - * @param content - The content to wrap - */ -declare function inlineCode(content: C): `\`${C}\``; -/** - * Formats the content into italic text - * - * @param content - The content to wrap - */ -declare function italic(content: C): `_${C}_`; -/** - * Formats the content into bold text - * - * @param content - The content to wrap - */ -declare function bold(content: C): `**${C}**`; -/** - * Formats the content into underscored text - * - * @param content - The content to wrap - */ -declare function underscore(content: C): `__${C}__`; -/** - * Formats the content into strike-through text - * - * @param content - The content to wrap - */ -declare function strikethrough(content: C): `~~${C}~~`; -/** - * Formats the content into a quote. This needs to be at the start of the line for Discord to format it - * - * @param content - The content to wrap - */ -declare function quote(content: C): `> ${C}`; -/** - * Formats the content into a block quote. This needs to be at the start of the line for Discord to format it - * - * @param content - The content to wrap - */ -declare function blockQuote(content: C): `>>> ${C}`; -/** - * Wraps the URL into `<>`, which stops it from embedding - * - * @param url - The URL to wrap - */ -declare function hideLinkEmbed(url: C): `<${C}>`; -/** - * Wraps the URL into `<>`, which stops it from embedding - * - * @param url - The URL to wrap - */ -declare function hideLinkEmbed(url: URL): `<${string}>`; -/** - * Formats the content and the URL into a masked URL - * - * @param content - The content to display - * @param url - The URL the content links to - */ -declare function hyperlink(content: C, url: URL): `[${C}](${string})`; -/** - * Formats the content and the URL into a masked URL - * - * @param content - The content to display - * @param url - The URL the content links to - */ -declare function hyperlink(content: C, url: U): `[${C}](${U})`; -/** - * Formats the content and the URL into a masked URL - * - * @param content - The content to display - * @param url - The URL the content links to - * @param title - The title shown when hovering on the masked link - */ -declare function hyperlink(content: C, url: URL, title: T): `[${C}](${string} "${T}")`; -/** - * Formats the content and the URL into a masked URL - * - * @param content - The content to display - * @param url - The URL the content links to - * @param title - The title shown when hovering on the masked link - */ -declare function hyperlink(content: C, url: U, title: T): `[${C}](${U} "${T}")`; -/** - * Wraps the content inside spoiler (hidden text) - * - * @param content - The content to wrap - */ -declare function spoiler(content: C): `||${C}||`; -/** - * Formats a user ID into a user mention - * - * @param userId - The user ID to format - */ -declare function userMention(userId: C): `<@${C}>`; -/** - * Formats a channel ID into a channel mention - * - * @param channelId - The channel ID to format - */ -declare function channelMention(channelId: C): `<#${C}>`; -/** - * Formats a role ID into a role mention - * - * @param roleId - The role ID to format - */ -declare function roleMention(roleId: C): `<@&${C}>`; -/** - * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention - * - * @param commandName - The application command name to format - * @param subcommandGroupName - The subcommand group name to format - * @param subcommandName - The subcommand name to format - * @param commandId - The application command ID to format - */ -declare function chatInputApplicationCommandMention(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): ``; -/** - * Formats an application command name, subcommand name, and ID into an application command mention - * - * @param commandName - The application command name to format - * @param subcommandName - The subcommand name to format - * @param commandId - The application command ID to format - */ -declare function chatInputApplicationCommandMention(commandName: N, subcommandName: S, commandId: I): ``; -/** - * Formats an application command name and ID into an application command mention - * - * @param commandName - The application command name to format - * @param commandId - The application command ID to format - */ -declare function chatInputApplicationCommandMention(commandName: N, commandId: I): ``; -/** - * Formats an emoji ID into a fully qualified emoji identifier - * - * @param emojiId - The emoji ID to format - */ -declare function formatEmoji(emojiId: C, animated?: false): `<:_:${C}>`; -/** - * Formats an emoji ID into a fully qualified emoji identifier - * - * @param emojiId - The emoji ID to format - * @param animated - Whether the emoji is animated or not. Defaults to `false` - */ -declare function formatEmoji(emojiId: C, animated?: true): ``; -/** - * Formats an emoji ID into a fully qualified emoji identifier - * - * @param emojiId - The emoji ID to format - * @param animated - Whether the emoji is animated or not. Defaults to `false` - */ -declare function formatEmoji(emojiId: C, animated?: boolean): `<:_:${C}>` | ``; -/** - * Formats a channel link for a direct message channel. - * - * @param channelId - The channel's id - */ -declare function channelLink(channelId: C): `https://discord.com/channels/@me/${C}`; -/** - * Formats a channel link for a guild channel. - * - * @param channelId - The channel's id - * @param guildId - The guild's id - */ -declare function channelLink(channelId: C, guildId: G): `https://discord.com/channels/${G}/${C}`; -/** - * Formats a message link for a direct message channel. - * - * @param channelId - The channel's id - * @param messageId - The message's id - */ -declare function messageLink(channelId: C, messageId: M): `https://discord.com/channels/@me/${C}/${M}`; -/** - * Formats a message link for a guild channel. - * - * @param channelId - The channel's id - * @param messageId - The message's id - * @param guildId - The guild's id - */ -declare function messageLink(channelId: C, messageId: M, guildId: G): `https://discord.com/channels/${G}/${C}/${M}`; -/** - * Formats a date into a short date-time string - * - * @param date - The date to format, defaults to the current time - */ -declare function time(date?: Date): ``; -/** - * Formats a date given a format style - * - * @param date - The date to format - * @param style - The style to use - */ -declare function time(date: Date, style: S): ``; -/** - * Formats the given timestamp into a short date-time string - * - * @param seconds - The time to format, represents an UNIX timestamp in seconds - */ -declare function time(seconds: C): ``; -/** - * Formats the given timestamp into a short date-time string - * - * @param seconds - The time to format, represents an UNIX timestamp in seconds - * @param style - The style to use - */ -declare function time(seconds: C, style: S): ``; -/** - * The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles} supported by Discord - */ -declare const TimestampStyles: { - /** - * Short time format, consisting of hours and minutes, e.g. 16:20 - */ - readonly ShortTime: "t"; - /** - * Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30 - */ - readonly LongTime: "T"; - /** - * Short date format, consisting of day, month, and year, e.g. 20/04/2021 - */ - readonly ShortDate: "d"; - /** - * Long date format, consisting of day, month, and year, e.g. 20 April 2021 - */ - readonly LongDate: "D"; - /** - * Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20 - */ - readonly ShortDateTime: "f"; - /** - * Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20 - */ - readonly LongDateTime: "F"; - /** - * Relative time format, consisting of a relative duration format, e.g. 2 months ago - */ - readonly RelativeTime: "R"; -}; -/** - * The possible values, see {@link TimestampStyles} for more information - */ -type TimestampStylesString = typeof TimestampStyles[keyof typeof TimestampStyles]; -/** - * An enum with all the available faces from Discord's native slash commands - */ -declare enum Faces { - /** - * ¯\\_(ツ)\\_/¯ - */ - Shrug = "\u00AF\\_(\u30C4)\\_/\u00AF", - /** - * (╯°□°)╯︵ ┻━┻ - */ - Tableflip = "(\u256F\u00B0\u25A1\u00B0\uFF09\u256F\uFE35 \u253B\u2501\u253B", - /** - * ┬─┬ ノ( ゜-゜ノ) - */ - Unflip = "\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)" -} - -/** - * Represents an option within a string select menu component + * A builder that creates API-compatible JSON data for string select menu options. */ declare class StringSelectMenuOptionBuilder implements JSONEncodable { data: Partial; /** - * Creates a new string select menu option from API data + * Creates a new string select menu option from API data. * * @param data - The API data to create this string select menu option with * @example - * Creating a string select menu option from an API data object + * Creating a string select menu option from an API data object: * ```ts * const selectMenuOption = new SelectMenuOptionBuilder({ * label: 'catchy label', @@ -543,48 +315,48 @@ declare class StringSelectMenuOptionBuilder implements JSONEncodable); /** - * Sets the label of this option + * Sets the label for this option. * - * @param label - The label to show on this option + * @param label - The label to use */ setLabel(label: string): this; /** - * Sets the value of this option + * Sets the value for this option. * - * @param value - The value of this option + * @param value - The value to use */ setValue(value: string): this; /** - * Sets the description of this option + * Sets the description for this option. * - * @param description - The description of this option + * @param description - The description to use */ setDescription(description: string): this; /** - * Sets whether this option is selected by default + * Sets whether this option is selected by default. * * @param isDefault - Whether this option is selected by default */ setDefault(isDefault?: boolean): this; /** - * Sets the emoji to display on this option + * Sets the emoji to display for this option. * - * @param emoji - The emoji to display on this option + * @param emoji - The emoji to use */ setEmoji(emoji: APIMessageComponentEmoji): this; /** - * {@inheritDoc ComponentBuilder.toJSON} + * {@inheritDoc BaseSelectMenuBuilder.toJSON} */ toJSON(): APISelectMenuOption; } @@ -636,78 +408,86 @@ declare const channelTypesValidator: _sapphire_shapeshift.ArrayValidator; declare function validateRequiredButtonParameters(style?: ButtonStyle, label?: string, emoji?: APIMessageComponentEmoji, customId?: string, url?: string): void; -declare const Assertions$4_customIdValidator: typeof customIdValidator; -declare const Assertions$4_emojiValidator: typeof emojiValidator; -declare const Assertions$4_disabledValidator: typeof disabledValidator; declare const Assertions$4_buttonLabelValidator: typeof buttonLabelValidator; declare const Assertions$4_buttonStyleValidator: typeof buttonStyleValidator; -declare const Assertions$4_minMaxValidator: typeof minMaxValidator; -declare const Assertions$4_labelValueDescriptionValidator: typeof labelValueDescriptionValidator; -declare const Assertions$4_jsonOptionValidator: typeof jsonOptionValidator; -declare const Assertions$4_optionValidator: typeof optionValidator; -declare const Assertions$4_optionsValidator: typeof optionsValidator; -declare const Assertions$4_optionsLengthValidator: typeof optionsLengthValidator; -declare const Assertions$4_validateRequiredSelectMenuParameters: typeof validateRequiredSelectMenuParameters; -declare const Assertions$4_defaultValidator: typeof defaultValidator; -declare const Assertions$4_validateRequiredSelectMenuOptionParameters: typeof validateRequiredSelectMenuOptionParameters; declare const Assertions$4_channelTypesValidator: typeof channelTypesValidator; +declare const Assertions$4_customIdValidator: typeof customIdValidator; +declare const Assertions$4_defaultValidator: typeof defaultValidator; +declare const Assertions$4_disabledValidator: typeof disabledValidator; +declare const Assertions$4_emojiValidator: typeof emojiValidator; +declare const Assertions$4_jsonOptionValidator: typeof jsonOptionValidator; +declare const Assertions$4_labelValueDescriptionValidator: typeof labelValueDescriptionValidator; +declare const Assertions$4_minMaxValidator: typeof minMaxValidator; +declare const Assertions$4_optionValidator: typeof optionValidator; +declare const Assertions$4_optionsLengthValidator: typeof optionsLengthValidator; +declare const Assertions$4_optionsValidator: typeof optionsValidator; declare const Assertions$4_urlValidator: typeof urlValidator; declare const Assertions$4_validateRequiredButtonParameters: typeof validateRequiredButtonParameters; +declare const Assertions$4_validateRequiredSelectMenuOptionParameters: typeof validateRequiredSelectMenuOptionParameters; +declare const Assertions$4_validateRequiredSelectMenuParameters: typeof validateRequiredSelectMenuParameters; declare namespace Assertions$4 { export { - Assertions$4_customIdValidator as customIdValidator, - Assertions$4_emojiValidator as emojiValidator, - Assertions$4_disabledValidator as disabledValidator, Assertions$4_buttonLabelValidator as buttonLabelValidator, Assertions$4_buttonStyleValidator as buttonStyleValidator, - placeholderValidator$1 as placeholderValidator, - Assertions$4_minMaxValidator as minMaxValidator, - Assertions$4_labelValueDescriptionValidator as labelValueDescriptionValidator, - Assertions$4_jsonOptionValidator as jsonOptionValidator, - Assertions$4_optionValidator as optionValidator, - Assertions$4_optionsValidator as optionsValidator, - Assertions$4_optionsLengthValidator as optionsLengthValidator, - Assertions$4_validateRequiredSelectMenuParameters as validateRequiredSelectMenuParameters, - Assertions$4_defaultValidator as defaultValidator, - Assertions$4_validateRequiredSelectMenuOptionParameters as validateRequiredSelectMenuOptionParameters, Assertions$4_channelTypesValidator as channelTypesValidator, + Assertions$4_customIdValidator as customIdValidator, + Assertions$4_defaultValidator as defaultValidator, + Assertions$4_disabledValidator as disabledValidator, + Assertions$4_emojiValidator as emojiValidator, + Assertions$4_jsonOptionValidator as jsonOptionValidator, + Assertions$4_labelValueDescriptionValidator as labelValueDescriptionValidator, + Assertions$4_minMaxValidator as minMaxValidator, + Assertions$4_optionValidator as optionValidator, + Assertions$4_optionsLengthValidator as optionsLengthValidator, + Assertions$4_optionsValidator as optionsValidator, + placeholderValidator$1 as placeholderValidator, Assertions$4_urlValidator as urlValidator, Assertions$4_validateRequiredButtonParameters as validateRequiredButtonParameters, + Assertions$4_validateRequiredSelectMenuOptionParameters as validateRequiredSelectMenuOptionParameters, + Assertions$4_validateRequiredSelectMenuParameters as validateRequiredSelectMenuParameters, }; } +/** + * Any action row component data represented as an object. + */ type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes; /** - * Represents a discord component + * The base component builder that contains common symbols for all sorts of components. * * @typeParam DataType - The type of internal API data that is stored within the component */ declare abstract class ComponentBuilder> = APIBaseComponent> implements JSONEncodable { /** - * The API data associated with this component + * The API data associated with this component. */ readonly data: Partial; /** - * Serializes this component to an API-compatible JSON object + * Serializes this builder to API-compatible JSON data. * * @remarks * This method runs validations on the data before serializing it. * As such, it may throw an error if the data is invalid. */ abstract toJSON(): AnyAPIActionRowComponent; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ constructor(data: Partial); } /** - * Represents a button component + * A builder that creates API-compatible JSON data for buttons. */ declare class ButtonBuilder extends ComponentBuilder { /** - * Creates a new button from API data + * Creates a new button from API data. * * @param data - The API data to create this button with * @example - * Creating a button from an API data object + * Creating a button from an API data object: * ```ts * const button = new ButtonBuilder({ * custom_id: 'a cool button', @@ -720,7 +500,7 @@ declare class ButtonBuilder extends ComponentBuilder { * }); * ``` * @example - * Creating a button using setters and API data + * Creating a button using setters and API data: * ```ts * const button = new ButtonBuilder({ * style: ButtonStyle.Secondary, @@ -732,44 +512,44 @@ declare class ButtonBuilder extends ComponentBuilder { */ constructor(data?: Partial); /** - * Sets the style of this button + * Sets the style of this button. * - * @param style - The style of the button + * @param style - The style to use */ setStyle(style: ButtonStyle): this; /** - * Sets the URL for this button + * Sets the URL for this button. * * @remarks * This method is only available to buttons using the `Link` button style. - * Only three types of URL schemes are currently supported: `https://`, `http://` and `discord://` - * @param url - The URL to open when this button is clicked + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use */ setURL(url: string): this; /** - * Sets the custom id for this button + * Sets the custom id for this button. * * @remarks * This method is only applicable to buttons that are not using the `Link` button style. - * @param customId - The custom id to use for this button + * @param customId - The custom id to use */ setCustomId(customId: string): this; /** - * Sets the emoji to display on this button + * Sets the emoji to display on this button. * - * @param emoji - The emoji to display on this button + * @param emoji - The emoji to use */ setEmoji(emoji: APIMessageComponentEmoji): this; /** - * Sets whether this button is disabled + * Sets whether this button is disabled. * * @param disabled - Whether to disable this button */ setDisabled(disabled?: boolean): this; /** - * Sets the label for this button + * Sets the label for this button. * - * @param label - The label to display on this button + * @param label - The label to use */ setLabel(label: string): this; /** @@ -778,47 +558,58 @@ declare class ButtonBuilder extends ComponentBuilder { toJSON(): APIButtonComponent; } -declare class BaseSelectMenuBuilder extends ComponentBuilder { +/** + * The base select menu builder that contains common symbols for select menu builders. + * + * @typeParam SelectMenuType - The type of select menu this would be instantiated for. + */ +declare abstract class BaseSelectMenuBuilder extends ComponentBuilder { /** - * Sets the placeholder for this select menu + * Sets the placeholder for this select menu. * - * @param placeholder - The placeholder to use for this select menu + * @param placeholder - The placeholder to use */ setPlaceholder(placeholder: string): this; /** - * Sets the minimum values that must be selected in the select menu + * Sets the minimum values that must be selected in the select menu. * * @param minValues - The minimum values that must be selected */ setMinValues(minValues: number): this; /** - * Sets the maximum values that must be selected in the select menu + * Sets the maximum values that must be selected in the select menu. * * @param maxValues - The maximum values that must be selected */ setMaxValues(maxValues: number): this; /** - * Sets the custom id for this select menu + * Sets the custom id for this select menu. * - * @param customId - The custom id to use for this select menu + * @param customId - The custom id to use */ setCustomId(customId: string): this; /** - * Sets whether this select menu is disabled + * Sets whether this select menu is disabled. * * @param disabled - Whether this select menu is disabled */ setDisabled(disabled?: boolean): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON(): SelectMenuType; } +/** + * A builder that creates API-compatible JSON data for channel select menus. + */ declare class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new ChannelSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -827,31 +618,44 @@ declare class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder); + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ addChannelTypes(...types: RestOrArray): this; + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ setChannelTypes(...types: RestOrArray): this; /** - * {@inheritDoc ComponentBuilder.toJSON} + * {@inheritDoc BaseSelectMenuBuilder.toJSON} */ toJSON(): APIChannelSelectComponent; } +/** + * A builder that creates API-compatible JSON data for mentionable select menus. + */ declare class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new MentionableSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -860,24 +664,27 @@ declare class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder); } +/** + * A builder that creates API-compatible JSON data for role select menus. + */ declare class RoleSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new RoleSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -886,31 +693,31 @@ declare class RoleSelectMenuBuilder extends BaseSelectMenuBuilder); } /** - * Represents a string select menu component + * A builder that creates API-compatible JSON data for string select menus. */ declare class StringSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * The options within this select menu + * The options within this select menu. */ readonly options: StringSelectMenuOptionBuilder[]; /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new StringSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -924,7 +731,7 @@ declare class StringSelectMenuBuilder extends BaseSelectMenuBuilder); /** - * Adds options to this select menu + * Adds options to this select menu. * - * @param options - The options to add to this select menu - * @returns + * @param options - The options to add */ addOptions(...options: RestOrArray): this; /** - * Sets the options on this select menu + * Sets the options for this select menu. * - * @param options - The options to set on this select menu + * @param options - The options to set */ setOptions(...options: RestOrArray): this; /** - * {@inheritDoc ComponentBuilder.toJSON} + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index: number, deleteCount: number, ...options: RestOrArray): this; + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} */ toJSON(): APIStringSelectComponent; } +/** + * A builder that creates API-compatible JSON data for user select menus. + */ declare class UserSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new UserSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -971,24 +808,27 @@ declare class UserSelectMenuBuilder extends BaseSelectMenuBuilder); } +/** + * A builder that creates API-compatible JSON data for text inputs. + */ declare class TextInputBuilder extends ComponentBuilder implements Equatable> { /** - * Creates a new text input from API data + * Creates a new text input from API data. * * @param data - The API data to create this text input with * @example - * Creating a select menu option from an API data object + * Creating a select menu option from an API data object: * ```ts * const textInput = new TextInputBuilder({ * custom_id: 'a cool select menu', @@ -997,7 +837,7 @@ declare class TextInputBuilder extends ComponentBuilder i * }); * ``` * @example - * Creating a select menu option using setters and API data + * Creating a select menu option using setters and API data: * ```ts * const textInput = new TextInputBuilder({ * label: 'Type something else', @@ -1010,49 +850,49 @@ declare class TextInputBuilder extends ComponentBuilder i type?: ComponentType.TextInput; }); /** - * Sets the custom id for this text input + * Sets the custom id for this text input. * - * @param customId - The custom id of this text input + * @param customId - The custom id to use */ setCustomId(customId: string): this; /** - * Sets the label for this text input + * Sets the label for this text input. * - * @param label - The label for this text input + * @param label - The label to use */ setLabel(label: string): this; /** - * Sets the style for this text input + * Sets the style for this text input. * - * @param style - The style for this text input + * @param style - The style to use */ setStyle(style: TextInputStyle): this; /** - * Sets the minimum length of text for this text input + * Sets the minimum length of text for this text input. * * @param minLength - The minimum length of text for this text input */ setMinLength(minLength: number): this; /** - * Sets the maximum length of text for this text input + * Sets the maximum length of text for this text input. * * @param maxLength - The maximum length of text for this text input */ setMaxLength(maxLength: number): this; /** - * Sets the placeholder of this text input + * Sets the placeholder for this text input. * - * @param placeholder - The placeholder of this text input + * @param placeholder - The placeholder to use */ setPlaceholder(placeholder: string): this; /** - * Sets the value of this text input + * Sets the value for this text input. * - * @param value - The value for this text input + * @param value - The value to use */ setValue(value: string): this; /** - * Sets whether this text input is required + * Sets whether this text input is required. * * @param required - Whether this text input is required */ @@ -1067,27 +907,42 @@ declare class TextInputBuilder extends ComponentBuilder i equals(other: APITextInputComponent | JSONEncodable): boolean; } +/** + * The builders that may be used for messages. + */ type MessageComponentBuilder = ActionRowBuilder | MessageActionRowComponentBuilder; +/** + * The builders that may be used for modals. + */ type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder; +/** + * The builders that may be used within an action row for messages. + */ type MessageActionRowComponentBuilder = ButtonBuilder | ChannelSelectMenuBuilder | MentionableSelectMenuBuilder | RoleSelectMenuBuilder | StringSelectMenuBuilder | UserSelectMenuBuilder; +/** + * The builders that may be used within an action row for modals. + */ type ModalActionRowComponentBuilder = TextInputBuilder; +/** + * Any builder. + */ type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder; /** - * Represents an action row component + * A builder that creates API-compatible JSON data for action rows. * * @typeParam T - The types of components this action row holds */ declare class ActionRowBuilder extends ComponentBuilder> { /** - * The components within this action row + * The components within this action row. */ readonly components: T[]; /** - * Creates a new action row from API data + * Creates a new action row from API data. * * @param data - The API data to create this action row with * @example - * Creating an action row from an API data object + * Creating an action row from an API data object: * ```ts * const actionRow = new ActionRowBuilder({ * components: [ @@ -1101,7 +956,7 @@ declare class ActionRowBuilder extends ComponentB * }); * ``` * @example - * Creating an action row using setters and API data + * Creating an action row using setters and API data: * ```ts * const actionRow = new ActionRowBuilder({ * components: [ @@ -1120,13 +975,13 @@ declare class ActionRowBuilder extends ComponentB /** * Adds components to this action row. * - * @param components - The components to add to this action row. + * @param components - The components to add */ addComponents(...components: RestOrArray): this; /** - * Sets the components in this action row + * Sets components for this action row. * - * @param components - The components to set this row to + * @param components - The components to set */ setComponents(...components: RestOrArray): this; /** @@ -1135,24 +990,58 @@ declare class ActionRowBuilder extends ComponentB toJSON(): APIActionRowComponent>; } +/** + * Components here are mapped to their respective builder. + */ interface MappedComponentTypes { + /** + * The action row component type is associated with an {@link ActionRowBuilder}. + */ [ComponentType.ActionRow]: ActionRowBuilder; + /** + * The button component type is associated with an {@link ButtonBuilder}. + */ [ComponentType.Button]: ButtonBuilder; + /** + * The string select component type is associated with an {@link StringSelectMenuBuilder}. + */ [ComponentType.StringSelect]: StringSelectMenuBuilder; + /** + * The text inpiut component type is associated with an {@link TextInputBuilder}. + */ [ComponentType.TextInput]: TextInputBuilder; + /** + * The user select component type is associated with an {@link UserSelectMenuBuilder}. + */ [ComponentType.UserSelect]: UserSelectMenuBuilder; + /** + * The role select component type is associated with an {@link RoleSelectMenuBuilder}. + */ [ComponentType.RoleSelect]: RoleSelectMenuBuilder; + /** + * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}. + */ [ComponentType.MentionableSelect]: MentionableSelectMenuBuilder; + /** + * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}. + */ [ComponentType.ChannelSelect]: ChannelSelectMenuBuilder; } /** - * Factory for creating components from API data + * Factory for creating components from API data. * - * @param data - The api data to transform to a component class + * @typeParam T - The type of component to use + * @param data - The API data to transform to a component class */ declare function createComponentBuilder(data: (APIModalComponent | APIMessageComponent) & { type: T; }): MappedComponentTypes[T]; +/** + * Factory for creating components from API data. + * + * @typeParam C - The type of component to use + * @param data - The API data to transform to a component class + */ declare function createComponentBuilder(data: C): C; declare const textInputStyleValidator: _sapphire_shapeshift.NativeEnumValidator; @@ -1164,52 +1053,66 @@ declare const placeholderValidator: _sapphire_shapeshift.StringValidator declare const labelValidator: _sapphire_shapeshift.StringValidator; declare function validateRequiredParameters$3(customId?: string, style?: TextInputStyle, label?: string): void; -declare const Assertions$3_textInputStyleValidator: typeof textInputStyleValidator; -declare const Assertions$3_minLengthValidator: typeof minLengthValidator; -declare const Assertions$3_maxLengthValidator: typeof maxLengthValidator; -declare const Assertions$3_requiredValidator: typeof requiredValidator; -declare const Assertions$3_valueValidator: typeof valueValidator; -declare const Assertions$3_placeholderValidator: typeof placeholderValidator; declare const Assertions$3_labelValidator: typeof labelValidator; +declare const Assertions$3_maxLengthValidator: typeof maxLengthValidator; +declare const Assertions$3_minLengthValidator: typeof minLengthValidator; +declare const Assertions$3_placeholderValidator: typeof placeholderValidator; +declare const Assertions$3_requiredValidator: typeof requiredValidator; +declare const Assertions$3_textInputStyleValidator: typeof textInputStyleValidator; +declare const Assertions$3_valueValidator: typeof valueValidator; declare namespace Assertions$3 { export { - Assertions$3_textInputStyleValidator as textInputStyleValidator, - Assertions$3_minLengthValidator as minLengthValidator, - Assertions$3_maxLengthValidator as maxLengthValidator, - Assertions$3_requiredValidator as requiredValidator, - Assertions$3_valueValidator as valueValidator, - Assertions$3_placeholderValidator as placeholderValidator, Assertions$3_labelValidator as labelValidator, + Assertions$3_maxLengthValidator as maxLengthValidator, + Assertions$3_minLengthValidator as minLengthValidator, + Assertions$3_placeholderValidator as placeholderValidator, + Assertions$3_requiredValidator as requiredValidator, + Assertions$3_textInputStyleValidator as textInputStyleValidator, validateRequiredParameters$3 as validateRequiredParameters, + Assertions$3_valueValidator as valueValidator, }; } +/** + * A builder that creates API-compatible JSON data for modals. + */ declare class ModalBuilder implements JSONEncodable { + /** + * The API data associated with this modal. + */ readonly data: Partial; + /** + * The components within this modal. + */ readonly components: ActionRowBuilder[]; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ constructor({ components, ...data }?: Partial); /** - * Sets the title of the modal + * Sets the title of this modal. * - * @param title - The title of the modal + * @param title - The title to use */ setTitle(title: string): this; /** - * Sets the custom id of the modal + * Sets the custom id of this modal. * - * @param customId - The custom id of this modal + * @param customId - The custom id to use */ setCustomId(customId: string): this; /** - * Adds components to this modal + * Adds components to this modal. * - * @param components - The components to add to this modal + * @param components - The components to add */ addComponents(...components: RestOrArray | APIActionRowComponent>): this; /** - * Sets the components in this modal + * Sets components for this modal. * - * @param components - The components to set this modal to + * @param components - The components to set */ setComponents(...components: RestOrArray>): this; /** @@ -1222,140 +1125,252 @@ declare const titleValidator: _sapphire_shapeshift.StringValidator; declare const componentsValidator: _sapphire_shapeshift.ArrayValidator<[ActionRowBuilder, ...ActionRowBuilder[]], ActionRowBuilder>; declare function validateRequiredParameters$2(customId?: string, title?: string, components?: ActionRowBuilder[]): void; -declare const Assertions$2_titleValidator: typeof titleValidator; declare const Assertions$2_componentsValidator: typeof componentsValidator; +declare const Assertions$2_titleValidator: typeof titleValidator; declare namespace Assertions$2 { export { - Assertions$2_titleValidator as titleValidator, Assertions$2_componentsValidator as componentsValidator, + Assertions$2_titleValidator as titleValidator, validateRequiredParameters$2 as validateRequiredParameters, }; } +/** + * This mixin holds name and description symbols for slash commands. + */ declare class SharedNameAndDescription { + /** + * The name of this command. + */ readonly name: string; + /** + * The name localizations of this command. + */ readonly name_localizations?: LocalizationMap; + /** + * The description of this command. + */ readonly description: string; + /** + * The description localizations of this command. + */ readonly description_localizations?: LocalizationMap; /** - * Sets the name + * Sets the name of this command. * - * @param name - The name + * @param name - The name to use */ setName(name: string): this; /** - * Sets the description + * Sets the description of this command. * - * @param description - The description + * @param description - The description to use */ setDescription(description: string): this; /** - * Sets a name localization + * SSets a name localization for this command. * - * @param locale - The locale to set a description for - * @param localizedName - The localized description for the given locale + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` */ setNameLocalization(locale: LocaleString, localizedName: string | null): this; /** - * Sets the name localizations + * Sets the name localizations for this command. * - * @param localizedNames - The dictionary of localized descriptions to set + * @param localizedNames - The object of localized names to set */ setNameLocalizations(localizedNames: LocalizationMap | null): this; /** - * Sets a description localization + * Sets a description localization for this command. * - * @param locale - The locale to set a description for + * @param locale - The locale to set * @param localizedDescription - The localized description for the given locale */ setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null): this; /** - * Sets the description localizations + * Sets the description localizations for this command. * - * @param localizedDescriptions - The dictionary of localized descriptions to set + * @param localizedDescriptions - The object of localized descriptions to set */ setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null): this; } +/** + * The base application command option builder that contains common symbols for application command builders. + */ declare abstract class ApplicationCommandOptionBase extends SharedNameAndDescription { + /** + * The type of this option. + */ abstract readonly type: ApplicationCommandOptionType; + /** + * Whether this option is required. + * + * @defaultValue `false` + */ readonly required: boolean; /** - * Marks the option as required + * Sets whether this option is required. * - * @param required - If this option should be required + * @param required - Whether this option should be required */ setRequired(required: boolean): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ abstract toJSON(): APIApplicationCommandBasicOption; + /** + * This method runs required validators on this builder. + */ protected runRequiredValidations(): void; } +/** + * A slash command attachment option. + */ declare class SlashCommandAttachmentOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandAttachmentOption; } +/** + * A slash command boolean option. + */ declare class SlashCommandBooleanOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandBooleanOption; } +/** + * The allowed channel types used for a channel option in a slash command builder. + * + * @privateRemarks This can't be dynamic because const enums are erased at runtime. + * @internal + */ declare const allowedChannelTypes: readonly [ChannelType.GuildText, ChannelType.GuildVoice, ChannelType.GuildCategory, ChannelType.GuildAnnouncement, ChannelType.AnnouncementThread, ChannelType.PublicThread, ChannelType.PrivateThread, ChannelType.GuildStageVoice, ChannelType.GuildForum]; -type ApplicationCommandOptionAllowedChannelTypes = typeof allowedChannelTypes[number]; +/** + * The type of allowed channel types used for a channel option. + */ +type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number]; +/** + * This mixin holds channel type symbols used for options. + */ declare class ApplicationCommandOptionChannelTypesMixin { + /** + * The channel types of this option. + */ readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[]; /** - * Adds channel types to this option + * Adds channel types to this option. * - * @param channelTypes - The channel types to add + * @param channelTypes - The channel types */ addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]): this; } +/** + * A slash command channel option. + */ declare class SlashCommandChannelOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandChannelOption; } interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin { } +/** + * This mixin holds minimum and maximum symbols used for options. + */ declare abstract class ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The maximum value of this option. + */ readonly max_value?: number; + /** + * The minimum value of this option. + */ readonly min_value?: number; /** - * Sets the maximum number value of this option + * Sets the maximum number value of this option. * * @param max - The maximum value this option can be */ abstract setMaxValue(max: number): this; /** - * Sets the minimum number value of this option + * Sets the minimum number value of this option. * * @param min - The minimum value this option can be */ abstract setMinValue(min: number): this; } +/** + * This mixin holds choices and autocomplete symbols used for options. + */ declare class ApplicationCommandOptionWithChoicesAndAutocompleteMixin { + /** + * The choices of this option. + */ readonly choices?: APIApplicationCommandOptionChoice[]; + /** + * Whether this option utilizes autocomplete. + */ readonly autocomplete?: boolean; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ readonly type: ApplicationCommandOptionType; /** - * Adds multiple choices for this option + * Adds multiple choices to this option. * * @param choices - The choices to add */ addChoices(...choices: APIApplicationCommandOptionChoice[]): this; + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ setChoices[]>(...choices: Input): this; /** - * Marks the option as autocompletable + * Whether this option uses autocomplete. * - * @param autocomplete - If this option should be autocompletable + * @param autocomplete - Whether this option should use autocomplete */ setAutocomplete(autocomplete: boolean): this; } +/** + * A slash command integer option. + */ declare class SlashCommandIntegerOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Integer; /** * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} @@ -1365,17 +1380,35 @@ declare class SlashCommandIntegerOption extends ApplicationCommandOptionBase imp * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} */ setMinValue(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandIntegerOption; } interface SlashCommandIntegerOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { } +/** + * A slash command mentionable option. + */ declare class SlashCommandMentionableOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandMentionableOption; } +/** + * A slash command number option. + */ declare class SlashCommandNumberOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Number; /** * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} @@ -1385,19 +1418,43 @@ declare class SlashCommandNumberOption extends ApplicationCommandOptionBase impl * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} */ setMinValue(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandNumberOption; } interface SlashCommandNumberOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { } +/** + * A slash command role option. + */ declare class SlashCommandRoleOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandRoleOption; } +/** + * A slash command string option. + */ declare class SlashCommandStringOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.String; + /** + * The maximum length of this option. + */ readonly max_length?: number; + /** + * The minimum length of this option. + */ readonly min_length?: number; /** * Sets the maximum length of this string option. @@ -1411,179 +1468,217 @@ declare class SlashCommandStringOption extends ApplicationCommandOptionBase { * @param min - The minimum length this option can be */ setMinLength(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandStringOption; } interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin { } +/** + * A slash command user option. + */ declare class SlashCommandUserOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandUserOption; } +/** + * This mixin holds symbols that can be shared in slash command options. + * + * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions. + */ declare class SharedSlashCommandOptions { readonly options: ToAPIApplicationCommandOptions[]; /** - * Adds a boolean option + * Adds a boolean option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addBooleanOption(input: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a user option + * Adds a user option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a channel option + * Adds a channel option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addChannelOption(input: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a role option + * Adds a role option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds an attachment option + * Adds an attachment option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addAttachmentOption(input: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a mentionable option + * Adds a mentionable option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addMentionableOption(input: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a string option + * Adds a string option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addStringOption(input: Omit | Omit | SlashCommandStringOption | ((builder: SlashCommandStringOption) => Omit | Omit | SlashCommandStringOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds an integer option + * Adds an integer option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addIntegerOption(input: Omit | Omit | SlashCommandIntegerOption | ((builder: SlashCommandIntegerOption) => Omit | Omit | SlashCommandIntegerOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a number option + * Adds a number option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addNumberOption(input: Omit | Omit | SlashCommandNumberOption | ((builder: SlashCommandNumberOption) => Omit | Omit | SlashCommandNumberOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ private _sharedAddOptionMethod; } /** - * Represents a folder for subcommands + * Represents a folder for subcommands. * - * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups + * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups} */ declare class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions { /** - * The name of this subcommand group + * The name of this subcommand group. */ readonly name: string; /** - * The description of this subcommand group + * The description of this subcommand group. */ readonly description: string; /** - * The subcommands part of this subcommand group + * The subcommands within this subcommand group. */ readonly options: SlashCommandSubcommandBuilder[]; /** - * Adds a new subcommand to this group + * Adds a new subcommand to this group. * - * @param input - A function that returns a subcommand builder, or an already built builder + * @param input - A function that returns a subcommand builder or an already built builder */ addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): this; - toJSON(): APIApplicationCommandSubcommandGroupOption; -} -interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription { -} -/** - * Represents a subcommand - * - * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups - */ -declare class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions { /** - * The name of this subcommand - */ - readonly name: string; - /** - * The description of this subcommand - */ - readonly description: string; - /** - * The options of this subcommand - */ - readonly options: ApplicationCommandOptionBase[]; - toJSON(): APIApplicationCommandSubcommandOption; -} -interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { -} - -declare class SlashCommandBuilder { - /** - * The name of this slash command - */ - readonly name: string; - /** - * The localized names for this command - */ - readonly name_localizations?: LocalizationMap; - /** - * The description of this slash command - */ - readonly description: string; - /** - * The localized descriptions for this command - */ - readonly description_localizations?: LocalizationMap; - /** - * The options of this slash command - */ - readonly options: ToAPIApplicationCommandOptions[]; - /** - * Whether the command is enabled by default when the app is added to a guild - * - * @deprecated This property is deprecated and will be removed in the future. - * You should use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead. - */ - readonly default_permission: boolean | undefined; - /** - * Set of permissions represented as a bit set for the command - */ - readonly default_member_permissions: Permissions | null | undefined; - /** - * Indicates whether the command is available in DMs with the application, only for globally-scoped commands. - * By default, commands are visible. - */ - readonly dm_permission: boolean | undefined; - /** - * Returns the final data that should be sent to Discord. + * Serializes this builder to API-compatible JSON data. * * @remarks * This method runs validations on the data before serializing it. * As such, it may throw an error if the data is invalid. */ - toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody; + toJSON(): APIApplicationCommandSubcommandGroupOption; +} +interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription { +} +/** + * A builder that creates API-compatible JSON data for slash command subcommands. + * + * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups} + */ +declare class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions { + /** + * The name of this subcommand. + */ + readonly name: string; + /** + * The description of this subcommand. + */ + readonly description: string; + /** + * The options within this subcommand. + */ + readonly options: ApplicationCommandOptionBase[]; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): APIApplicationCommandSubcommandOption; +} +interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { +} + +/** + * A builder that creates API-compatible JSON data for slash commands. + */ +declare class SlashCommandBuilder { + /** + * The name of this command. + */ + readonly name: string; + /** + * The name localizations of this command. + */ + readonly name_localizations?: LocalizationMap; + /** + * The description of this command. + */ + readonly description: string; + /** + * The description localizations of this command. + */ + readonly description_localizations?: LocalizationMap; + /** + * The options of this command. + */ + readonly options: ToAPIApplicationCommandOptions[]; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + readonly default_permission: boolean | undefined; + /** + * The set of permissions represented as a bit set for the command. + */ + readonly default_member_permissions: Permissions | null | undefined; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ + readonly dm_permission: boolean | undefined; + /** + * Whether this command is NSFW. + */ + readonly nsfw: boolean | undefined; /** * Sets whether the command is enabled by default when the application is added to a guild. * * @remarks * If set to `false`, you will have to later `PUT` the permissions for this command. * @param value - Whether or not to enable this command by default - * @see https://discord.com/developers/docs/interactions/application-commands#permissions - * @deprecated Use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead. + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. */ setDefaultPermission(value: boolean): this; /** @@ -1592,36 +1687,61 @@ declare class SlashCommandBuilder { * @remarks * You can set this to `'0'` to disable the command by default. * @param permissions - The permissions bit field to set - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} */ setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined): this; /** - * Sets if the command is available in DMs with the application, only for globally-scoped commands. - * By default, commands are visible. + * Sets if the command is available in direct messages with the application. * - * @param enabled - If the command should be enabled in DMs - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} */ setDMPermission(enabled: boolean | null | undefined): this; /** - * Adds a new subcommand group to this command + * Sets whether this command is NSFW. * - * @param input - A function that returns a subcommand group builder, or an already built builder + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw?: boolean): this; + /** + * Adds a new subcommand group to this command. + * + * @param input - A function that returns a subcommand group builder or an already built builder */ addSubcommandGroup(input: SlashCommandSubcommandGroupBuilder | ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder)): SlashCommandSubcommandsOnlyBuilder; /** - * Adds a new subcommand to this command + * Adds a new subcommand to this command. * - * @param input - A function that returns a subcommand builder, or an already built builder + * @param input - A function that returns a subcommand builder or an already built builder */ addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): SlashCommandSubcommandsOnlyBuilder; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody; } interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { } +/** + * An interface specifically for slash command subcommands. + */ interface SlashCommandSubcommandsOnlyBuilder extends Omit> { } +/** + * An interface specifically for slash command options. + */ interface SlashCommandOptionsOnlyBuilder extends SharedNameAndDescription, SharedSlashCommandOptions, Pick { } +/** + * An interface that ensures the `toJSON()` call will return something + * that can be serialized into API-compatible data. + */ interface ToAPIApplicationCommandOptions { toJSON(): APIApplicationCommandOption; } @@ -1635,76 +1755,87 @@ declare function validateDefaultPermission$1(value: unknown): asserts value is b declare function validateRequired(required: unknown): asserts required is boolean; declare function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void; declare function assertReturnOfBuilder(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T; -declare const localizationMapPredicate: _sapphire_shapeshift.UnionValidator<_sapphire_shapeshift.UndefinedToOptional>> | null | undefined>; +declare const localizationMapPredicate: _sapphire_shapeshift.UnionValidator<_sapphire_shapeshift.UndefinedToOptional>> | null | undefined>; declare function validateLocalizationMap(value: unknown): asserts value is LocalizationMap; declare function validateDMPermission$1(value: unknown): asserts value is boolean | null | undefined; declare function validateDefaultMemberPermissions$1(permissions: unknown): string | null | undefined; +declare function validateNSFW(value: unknown): asserts value is boolean; -declare const Assertions$1_validateDescription: typeof validateDescription; -declare const Assertions$1_validateLocale: typeof validateLocale; -declare const Assertions$1_validateMaxOptionsLength: typeof validateMaxOptionsLength; -declare const Assertions$1_validateRequired: typeof validateRequired; -declare const Assertions$1_validateChoicesLength: typeof validateChoicesLength; declare const Assertions$1_assertReturnOfBuilder: typeof assertReturnOfBuilder; declare const Assertions$1_localizationMapPredicate: typeof localizationMapPredicate; +declare const Assertions$1_validateChoicesLength: typeof validateChoicesLength; +declare const Assertions$1_validateDescription: typeof validateDescription; +declare const Assertions$1_validateLocale: typeof validateLocale; declare const Assertions$1_validateLocalizationMap: typeof validateLocalizationMap; +declare const Assertions$1_validateMaxOptionsLength: typeof validateMaxOptionsLength; +declare const Assertions$1_validateNSFW: typeof validateNSFW; +declare const Assertions$1_validateRequired: typeof validateRequired; declare namespace Assertions$1 { export { - validateName$1 as validateName, - Assertions$1_validateDescription as validateDescription, - Assertions$1_validateLocale as validateLocale, - Assertions$1_validateMaxOptionsLength as validateMaxOptionsLength, - validateRequiredParameters$1 as validateRequiredParameters, - validateDefaultPermission$1 as validateDefaultPermission, - Assertions$1_validateRequired as validateRequired, - Assertions$1_validateChoicesLength as validateChoicesLength, Assertions$1_assertReturnOfBuilder as assertReturnOfBuilder, Assertions$1_localizationMapPredicate as localizationMapPredicate, - Assertions$1_validateLocalizationMap as validateLocalizationMap, + Assertions$1_validateChoicesLength as validateChoicesLength, validateDMPermission$1 as validateDMPermission, validateDefaultMemberPermissions$1 as validateDefaultMemberPermissions, + validateDefaultPermission$1 as validateDefaultPermission, + Assertions$1_validateDescription as validateDescription, + Assertions$1_validateLocale as validateLocale, + Assertions$1_validateLocalizationMap as validateLocalizationMap, + Assertions$1_validateMaxOptionsLength as validateMaxOptionsLength, + Assertions$1_validateNSFW as validateNSFW, + validateName$1 as validateName, + Assertions$1_validateRequired as validateRequired, + validateRequiredParameters$1 as validateRequiredParameters, }; } +/** + * The type a context menu command can be. + */ +type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User; +/** + * A builder that creates API-compatible JSON data for context menu commands. + */ declare class ContextMenuCommandBuilder { /** - * The name of this context menu command + * The name of this command. */ readonly name: string; /** - * The localized names for this command + * The name localizations of this command. */ readonly name_localizations?: LocalizationMap; /** - * The type of this context menu command + * The type of this command. */ readonly type: ContextMenuCommandType; /** - * Whether the command is enabled by default when the app is added to a guild + * Whether this command is enabled by default when the application is added to a guild. * - * @deprecated This property is deprecated and will be removed in the future. - * You should use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. */ readonly default_permission: boolean | undefined; /** - * Set of permissions represented as a bit set for the command + * The set of permissions represented as a bit set for the command. */ readonly default_member_permissions: Permissions | null | undefined; /** - * Indicates whether the command is available in DMs with the application, only for globally-scoped commands. - * By default, commands are visible. + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. */ readonly dm_permission: boolean | undefined; /** - * Sets the name + * Sets the name of this command. * - * @param name - The name + * @param name - The name to use */ setName(name: string): this; /** - * Sets the type + * Sets the type of this command. * - * @param type - The type + * @param type - The type to use */ setType(type: ContextMenuCommandType): this; /** @@ -1712,43 +1843,44 @@ declare class ContextMenuCommandBuilder { * * @remarks * If set to `false`, you will have to later `PUT` the permissions for this command. - * @param value - Whether or not to enable this command by default - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. */ setDefaultPermission(value: boolean): this; /** - * Sets the default permissions a member should have in order to run the command. + * Sets the default permissions a member should have in order to run this command. * * @remarks * You can set this to `'0'` to disable the command by default. * @param permissions - The permissions bit field to set - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} */ setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined): this; /** - * Sets if the command is available in DMs with the application, only for globally-scoped commands. - * By default, commands are visible. + * Sets if the command is available in direct messages with the application. * - * @param enabled - If the command should be enabled in DMs - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} */ setDMPermission(enabled: boolean | null | undefined): this; /** - * Sets a name localization + * Sets a name localization for this command. * - * @param locale - The locale to set a description for - * @param localizedName - The localized description for the given locale + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` */ setNameLocalization(locale: LocaleString, localizedName: string | null): this; /** - * Sets the name localizations + * Sets the name localizations for this command. * - * @param localizedNames - The dictionary of localized descriptions to set + * @param localizedNames - The object of localized names to set */ setNameLocalizations(localizedNames: LocalizationMap | null): this; /** - * Returns the final data that should be sent to Discord. + * Serializes this builder to API-compatible JSON data. * * @remarks * This method runs validations on the data before serializing it. @@ -1756,7 +1888,6 @@ declare class ContextMenuCommandBuilder { */ toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody; } -type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User; declare function validateDefaultPermission(value: unknown): asserts value is boolean; declare function validateName(name: unknown): asserts name is string; @@ -1765,33 +1896,53 @@ declare function validateRequiredParameters(name: string, type: number): void; declare function validateDMPermission(value: unknown): asserts value is boolean | null | undefined; declare function validateDefaultMemberPermissions(permissions: unknown): string | null | undefined; -declare const Assertions_validateDefaultPermission: typeof validateDefaultPermission; -declare const Assertions_validateName: typeof validateName; -declare const Assertions_validateType: typeof validateType; -declare const Assertions_validateRequiredParameters: typeof validateRequiredParameters; declare const Assertions_validateDMPermission: typeof validateDMPermission; declare const Assertions_validateDefaultMemberPermissions: typeof validateDefaultMemberPermissions; +declare const Assertions_validateDefaultPermission: typeof validateDefaultPermission; +declare const Assertions_validateName: typeof validateName; +declare const Assertions_validateRequiredParameters: typeof validateRequiredParameters; +declare const Assertions_validateType: typeof validateType; declare namespace Assertions { export { - Assertions_validateDefaultPermission as validateDefaultPermission, - Assertions_validateName as validateName, - Assertions_validateType as validateType, - Assertions_validateRequiredParameters as validateRequiredParameters, Assertions_validateDMPermission as validateDMPermission, Assertions_validateDefaultMemberPermissions as validateDefaultMemberPermissions, + Assertions_validateDefaultPermission as validateDefaultPermission, + Assertions_validateName as validateName, + Assertions_validateRequiredParameters as validateRequiredParameters, + Assertions_validateType as validateType, }; } +/** + * Calculates the length of the embed. + * + * @param data - The embed data to check + */ declare function embedLength(data: APIEmbed): number; -declare const enableValidators: () => boolean; -declare const disableValidators: () => boolean; -declare const isValidationEnabled: () => boolean; +/** + * Enables validators. + * + * @returns Whether validation is occurring. + */ +declare function enableValidators(): boolean; +/** + * Disables validators. + * + * @returns Whether validation is occurring. + */ +declare function disableValidators(): boolean; +/** + * Checks whether validation is occurring. + */ +declare function isValidationEnabled(): boolean; /** - * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders/#readme | @discordjs/builders} version + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version * that you are currently using. + * + * @privateRemarks This needs to explicitly be `string` so it is not typed as a "const string" that gets injected by esbuild. */ declare const version: string; -export { ActionRowBuilder, AnyAPIActionRowComponent, AnyComponentBuilder, ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionAllowedChannelTypes, ApplicationCommandOptionBase, ApplicationCommandOptionChannelTypesMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin, BaseSelectMenuBuilder, ButtonBuilder, ChannelSelectMenuBuilder, Assertions$4 as ComponentAssertions, ComponentBuilder, Assertions as ContextMenuCommandAssertions, ContextMenuCommandBuilder, ContextMenuCommandType, Assertions$5 as EmbedAssertions, EmbedAuthorData, EmbedAuthorOptions, EmbedBuilder, EmbedFooterData, EmbedFooterOptions, EmbedImageData, Faces, IconData, MappedComponentTypes, MentionableSelectMenuBuilder, MessageActionRowComponentBuilder, MessageComponentBuilder, ModalActionRowComponentBuilder, Assertions$2 as ModalAssertions, ModalBuilder, ModalComponentBuilder, RGBTuple, RestOrArray, RoleSelectMenuBuilder, StringSelectMenuBuilder as SelectMenuBuilder, StringSelectMenuOptionBuilder as SelectMenuOptionBuilder, SharedNameAndDescription, SharedSlashCommandOptions, Assertions$1 as SlashCommandAssertions, SlashCommandAttachmentOption, SlashCommandBooleanOption, SlashCommandBuilder, SlashCommandChannelOption, SlashCommandIntegerOption, SlashCommandMentionableOption, SlashCommandNumberOption, SlashCommandOptionsOnlyBuilder, SlashCommandRoleOption, SlashCommandStringOption, SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder, SlashCommandSubcommandsOnlyBuilder, SlashCommandUserOption, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, Assertions$3 as TextInputAssertions, TextInputBuilder, TimestampStyles, TimestampStylesString, ToAPIApplicationCommandOptions, UserSelectMenuBuilder, blockQuote, bold, channelLink, channelMention, chatInputApplicationCommandMention, codeBlock, createComponentBuilder, disableValidators, embedLength, enableValidators, formatEmoji, hideLinkEmbed, hyperlink, inlineCode, isValidationEnabled, italic, messageLink, normalizeArray, quote, roleMention, spoiler, strikethrough, time, underscore, userMention, version }; +export { ActionRowBuilder, AnyAPIActionRowComponent, AnyComponentBuilder, ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionAllowedChannelTypes, ApplicationCommandOptionBase, ApplicationCommandOptionChannelTypesMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin, BaseSelectMenuBuilder, ButtonBuilder, ChannelSelectMenuBuilder, Assertions$4 as ComponentAssertions, ComponentBuilder, Assertions as ContextMenuCommandAssertions, ContextMenuCommandBuilder, ContextMenuCommandType, Assertions$5 as EmbedAssertions, EmbedAuthorData, EmbedAuthorOptions, EmbedBuilder, EmbedFooterData, EmbedFooterOptions, EmbedImageData, IconData, MappedComponentTypes, MentionableSelectMenuBuilder, MessageActionRowComponentBuilder, MessageComponentBuilder, ModalActionRowComponentBuilder, Assertions$2 as ModalAssertions, ModalBuilder, ModalComponentBuilder, RGBTuple, RestOrArray, RoleSelectMenuBuilder, StringSelectMenuBuilder as SelectMenuBuilder, StringSelectMenuOptionBuilder as SelectMenuOptionBuilder, SharedNameAndDescription, SharedSlashCommandOptions, Assertions$1 as SlashCommandAssertions, SlashCommandAttachmentOption, SlashCommandBooleanOption, SlashCommandBuilder, SlashCommandChannelOption, SlashCommandIntegerOption, SlashCommandMentionableOption, SlashCommandNumberOption, SlashCommandOptionsOnlyBuilder, SlashCommandRoleOption, SlashCommandStringOption, SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder, SlashCommandSubcommandsOnlyBuilder, SlashCommandUserOption, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, Assertions$3 as TextInputAssertions, TextInputBuilder, ToAPIApplicationCommandOptions, UserSelectMenuBuilder, createComponentBuilder, disableValidators, embedLength, enableValidators, isValidationEnabled, normalizeArray, version }; diff --git a/node_modules/@discordjs/builders/dist/index.js b/node_modules/@discordjs/builders/dist/index.js index 8e6a442..456ed60 100644 --- a/node_modules/@discordjs/builders/dist/index.js +++ b/node_modules/@discordjs/builders/dist/index.js @@ -20,6 +20,10 @@ var __copyProps = (to, from, except, desc) => { }; var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); @@ -51,7 +55,6 @@ __export(src_exports, { ContextMenuCommandBuilder: () => ContextMenuCommandBuilder, EmbedAssertions: () => Assertions_exports, EmbedBuilder: () => EmbedBuilder, - Faces: () => Faces, MentionableSelectMenuBuilder: () => MentionableSelectMenuBuilder, ModalAssertions: () => Assertions_exports4, ModalBuilder: () => ModalBuilder, @@ -77,33 +80,13 @@ __export(src_exports, { StringSelectMenuOptionBuilder: () => StringSelectMenuOptionBuilder, TextInputAssertions: () => Assertions_exports3, TextInputBuilder: () => TextInputBuilder, - TimestampStyles: () => TimestampStyles, UserSelectMenuBuilder: () => UserSelectMenuBuilder, - blockQuote: () => blockQuote, - bold: () => bold, - channelLink: () => channelLink, - channelMention: () => channelMention, - chatInputApplicationCommandMention: () => chatInputApplicationCommandMention, - codeBlock: () => codeBlock, createComponentBuilder: () => createComponentBuilder, disableValidators: () => disableValidators, embedLength: () => embedLength, enableValidators: () => enableValidators, - formatEmoji: () => formatEmoji, - hideLinkEmbed: () => hideLinkEmbed, - hyperlink: () => hyperlink, - inlineCode: () => inlineCode, isValidationEnabled: () => isValidationEnabled, - italic: () => italic, - messageLink: () => messageLink, normalizeArray: () => normalizeArray, - quote: () => quote, - roleMention: () => roleMention, - spoiler: () => spoiler, - strikethrough: () => strikethrough, - time: () => time, - underscore: () => underscore, - userMention: () => userMention, version: () => version }); module.exports = __toCommonJS(src_exports); @@ -134,9 +117,18 @@ var import_shapeshift = require("@sapphire/shapeshift"); // src/util/validation.ts var validate = true; -var enableValidators = /* @__PURE__ */ __name(() => validate = true, "enableValidators"); -var disableValidators = /* @__PURE__ */ __name(() => validate = false, "disableValidators"); -var isValidationEnabled = /* @__PURE__ */ __name(() => validate, "isValidationEnabled"); +function enableValidators() { + return validate = true; +} +__name(enableValidators, "enableValidators"); +function disableValidators() { + return validate = false; +} +__name(disableValidators, "disableValidators"); +function isValidationEnabled() { + return validate; +} +__name(isValidationEnabled, "isValidationEnabled"); // src/messages/embed/Assertions.ts var fieldNamePredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(256).setValidationEnabled(isValidationEnabled); @@ -186,22 +178,83 @@ __name(normalizeArray, "normalizeArray"); // src/messages/embed/Embed.ts var EmbedBuilder = class { + /** + * The API data associated with this embed. + */ data; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ constructor(data = {}) { this.data = { ...data }; if (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString(); } + /** + * Appends fields to the embed. + * + * @remarks + * This method accepts either an array of fields or a variable number of field parameters. + * The maximum amount of fields that can be added is 25. + * @example + * Using an array: + * ```ts + * const fields: APIEmbedField[] = ...; + * const embed = new EmbedBuilder() + * .addFields(fields); + * ``` + * @example + * Using rest parameters (variadic): + * ```ts + * const embed = new EmbedBuilder() + * .addFields( + * { name: 'Field 1', value: 'Value 1' }, + * { name: 'Field 2', value: 'Value 2' }, + * ); + * ``` + * @param fields - The fields to add + */ addFields(...fields) { - fields = normalizeArray(fields); - validateFieldLength(fields.length, this.data.fields); - embedFieldsArrayPredicate.parse(fields); + const normalizedFields = normalizeArray(fields); + validateFieldLength(normalizedFields.length, this.data.fields); + embedFieldsArrayPredicate.parse(normalizedFields); if (this.data.fields) - this.data.fields.push(...fields); + this.data.fields.push(...normalizedFields); else - this.data.fields = fields; + this.data.fields = normalizedFields; return this; } + /** + * Removes, replaces, or inserts fields for this embed. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. + * The maximum amount of fields that can be added is 25. + * + * It's useful for modifying and adjusting order of the already-existing fields of an embed. + * @example + * Remove the first field: + * ```ts + * embed.spliceFields(0, 1); + * ``` + * @example + * Remove the first n fields: + * ```ts + * const n = 4; + * embed.spliceFields(0, n); + * ``` + * @example + * Remove the last field: + * ```ts + * embed.spliceFields(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of fields to remove + * @param fields - The replacing field objects + */ spliceFields(index, deleteCount, ...fields) { validateFieldLength(fields.length - deleteCount, this.data.fields); embedFieldsArrayPredicate.parse(fields); @@ -211,10 +264,25 @@ var EmbedBuilder = class { this.data.fields = fields; return this; } + /** + * Sets the fields for this embed. + * + * @remarks + * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, + * it splices the entire array of fields, replacing them with the provided fields. + * + * You can set a maximum of 25 fields. + * @param fields - The fields to set + */ setFields(...fields) { this.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields)); return this; } + /** + * Sets the author of this embed. + * + * @param options - The options to use + */ setAuthor(options) { if (options === null) { this.data.author = void 0; @@ -224,6 +292,11 @@ var EmbedBuilder = class { this.data.author = { name: options.name, url: options.url, icon_url: options.iconURL }; return this; } + /** + * Sets the color of this embed. + * + * @param color - The color to use + */ setColor(color) { colorPredicate.parse(color); if (Array.isArray(color)) { @@ -234,11 +307,21 @@ var EmbedBuilder = class { this.data.color = color ?? void 0; return this; } + /** + * Sets the description of this embed. + * + * @param description - The description to use + */ setDescription(description) { descriptionPredicate.parse(description); this.data.description = description ?? void 0; return this; } + /** + * Sets the footer of this embed. + * + * @param options - The footer to use + */ setFooter(options) { if (options === null) { this.data.footer = void 0; @@ -248,142 +331,71 @@ var EmbedBuilder = class { this.data.footer = { text: options.text, icon_url: options.iconURL }; return this; } + /** + * Sets the image of this embed. + * + * @param url - The image URL to use + */ setImage(url) { imageURLPredicate.parse(url); this.data.image = url ? { url } : void 0; return this; } + /** + * Sets the thumbnail of this embed. + * + * @param url - The thumbnail URL to use + */ setThumbnail(url) { imageURLPredicate.parse(url); this.data.thumbnail = url ? { url } : void 0; return this; } + /** + * Sets the timestamp of this embed. + * + * @param timestamp - The timestamp or date to use + */ setTimestamp(timestamp = Date.now()) { timestampPredicate.parse(timestamp); this.data.timestamp = timestamp ? new Date(timestamp).toISOString() : void 0; return this; } + /** + * Sets the title for this embed. + * + * @param title - The title to use + */ setTitle(title) { titlePredicate.parse(title); this.data.title = title ?? void 0; return this; } + /** + * Sets the URL of this embed. + * + * @param url - The URL to use + */ setURL(url) { urlPredicate.parse(url); this.data.url = url ?? void 0; return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { return { ...this.data }; } }; __name(EmbedBuilder, "EmbedBuilder"); -// src/messages/formatters.ts -function codeBlock(language, content) { - return typeof content === "undefined" ? `\`\`\` -${language} -\`\`\`` : `\`\`\`${language} -${content} -\`\`\``; -} -__name(codeBlock, "codeBlock"); -function inlineCode(content) { - return `\`${content}\``; -} -__name(inlineCode, "inlineCode"); -function italic(content) { - return `_${content}_`; -} -__name(italic, "italic"); -function bold(content) { - return `**${content}**`; -} -__name(bold, "bold"); -function underscore(content) { - return `__${content}__`; -} -__name(underscore, "underscore"); -function strikethrough(content) { - return `~~${content}~~`; -} -__name(strikethrough, "strikethrough"); -function quote(content) { - return `> ${content}`; -} -__name(quote, "quote"); -function blockQuote(content) { - return `>>> ${content}`; -} -__name(blockQuote, "blockQuote"); -function hideLinkEmbed(url) { - return `<${url}>`; -} -__name(hideLinkEmbed, "hideLinkEmbed"); -function hyperlink(content, url, title) { - return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`; -} -__name(hyperlink, "hyperlink"); -function spoiler(content) { - return `||${content}||`; -} -__name(spoiler, "spoiler"); -function userMention(userId) { - return `<@${userId}>`; -} -__name(userMention, "userMention"); -function channelMention(channelId) { - return `<#${channelId}>`; -} -__name(channelMention, "channelMention"); -function roleMention(roleId) { - return `<@&${roleId}>`; -} -__name(roleMention, "roleMention"); -function chatInputApplicationCommandMention(commandName, subcommandGroupName, subcommandName, commandId) { - if (typeof commandId !== "undefined") { - return ``; - } - if (typeof subcommandName !== "undefined") { - return ``; - } - return ``; -} -__name(chatInputApplicationCommandMention, "chatInputApplicationCommandMention"); -function formatEmoji(emojiId, animated = false) { - return `<${animated ? "a" : ""}:_:${emojiId}>`; -} -__name(formatEmoji, "formatEmoji"); -function channelLink(channelId, guildId) { - return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}`; -} -__name(channelLink, "channelLink"); -function messageLink(channelId, messageId, guildId) { - return `${typeof guildId === "undefined" ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`; -} -__name(messageLink, "messageLink"); -function time(timeOrSeconds, style) { - if (typeof timeOrSeconds !== "number") { - timeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1e3); - } - return typeof style === "string" ? `` : ``; -} -__name(time, "time"); -var TimestampStyles = { - ShortTime: "t", - LongTime: "T", - ShortDate: "d", - LongDate: "D", - ShortDateTime: "f", - LongDateTime: "F", - RelativeTime: "R" -}; -var Faces = /* @__PURE__ */ ((Faces2) => { - Faces2["Shrug"] = "\xAF\\_(\u30C4)\\_/\xAF"; - Faces2["Tableflip"] = "(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B"; - Faces2["Unflip"] = "\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)"; - return Faces2; -})(Faces || {}); +// src/index.ts +__reExport(src_exports, require("@discordjs/formatters"), module.exports); // src/components/Assertions.ts var Assertions_exports2 = {}; @@ -412,29 +424,79 @@ var import_v10 = require("discord-api-types/v10"); // src/components/selectMenu/StringSelectMenuOption.ts var StringSelectMenuOptionBuilder = class { + /** + * Creates a new string select menu option from API data. + * + * @param data - The API data to create this string select menu option with + * @example + * Creating a string select menu option from an API data object: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * label: 'catchy label', + * value: '1', + * }); + * ``` + * @example + * Creating a string select menu option using setters and API data: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * default: true, + * value: '1', + * }) + * .setLabel('woah'); + * ``` + */ constructor(data = {}) { this.data = data; } + /** + * Sets the label for this option. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = labelValueDescriptionValidator.parse(label); return this; } + /** + * Sets the value for this option. + * + * @param value - The value to use + */ setValue(value) { this.data.value = labelValueDescriptionValidator.parse(value); return this; } + /** + * Sets the description for this option. + * + * @param description - The description to use + */ setDescription(description) { this.data.description = labelValueDescriptionValidator.parse(description); return this; } + /** + * Sets whether this option is selected by default. + * + * @param isDefault - Whether this option is selected by default + */ setDefault(isDefault = true) { this.data.default = defaultValidator.parse(isDefault); return this; } + /** + * Sets the emoji to display for this option. + * + * @param emoji - The emoji to use + */ setEmoji(emoji) { this.data.emoji = emojiValidator.parse(emoji); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value); return { @@ -504,7 +566,15 @@ var import_v1011 = require("discord-api-types/v10"); // src/components/Component.ts var ComponentBuilder = class { + /** + * The API data associated with this component. + */ data; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ constructor(data) { this.data = data; } @@ -517,33 +587,99 @@ var import_v1010 = require("discord-api-types/v10"); // src/components/button/Button.ts var import_v102 = require("discord-api-types/v10"); var ButtonBuilder = class extends ComponentBuilder { + /** + * Creates a new button from API data. + * + * @param data - The API data to create this button with + * @example + * Creating a button from an API data object: + * ```ts + * const button = new ButtonBuilder({ + * custom_id: 'a cool button', + * style: ButtonStyle.Primary, + * label: 'Click Me', + * emoji: { + * name: 'smile', + * id: '123456789012345678', + * }, + * }); + * ``` + * @example + * Creating a button using setters and API data: + * ```ts + * const button = new ButtonBuilder({ + * style: ButtonStyle.Secondary, + * label: 'Click Me', + * }) + * .setEmoji({ name: '🙂' }) + * .setCustomId('another cool button'); + * ``` + */ constructor(data) { super({ type: import_v102.ComponentType.Button, ...data }); } + /** + * Sets the style of this button. + * + * @param style - The style to use + */ setStyle(style) { this.data.style = buttonStyleValidator.parse(style); return this; } + /** + * Sets the URL for this button. + * + * @remarks + * This method is only available to buttons using the `Link` button style. + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use + */ setURL(url) { this.data.url = urlValidator.parse(url); return this; } + /** + * Sets the custom id for this button. + * + * @remarks + * This method is only applicable to buttons that are not using the `Link` button style. + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets the emoji to display on this button. + * + * @param emoji - The emoji to use + */ setEmoji(emoji) { this.data.emoji = emojiValidator.parse(emoji); return this; } + /** + * Sets whether this button is disabled. + * + * @param disabled - Whether to disable this button + */ setDisabled(disabled = true) { this.data.disabled = disabledValidator.parse(disabled); return this; } + /** + * Sets the label for this button. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = buttonLabelValidator.parse(label); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredButtonParameters( this.data.style, @@ -564,26 +700,54 @@ var import_v103 = require("discord-api-types/v10"); // src/components/selectMenu/BaseSelectMenu.ts var BaseSelectMenuBuilder = class extends ComponentBuilder { + /** + * Sets the placeholder for this select menu. + * + * @param placeholder - The placeholder to use + */ setPlaceholder(placeholder) { this.data.placeholder = placeholderValidator.parse(placeholder); return this; } + /** + * Sets the minimum values that must be selected in the select menu. + * + * @param minValues - The minimum values that must be selected + */ setMinValues(minValues) { this.data.min_values = minMaxValidator.parse(minValues); return this; } + /** + * Sets the maximum values that must be selected in the select menu. + * + * @param maxValues - The maximum values that must be selected + */ setMaxValues(maxValues) { this.data.max_values = minMaxValidator.parse(maxValues); return this; } + /** + * Sets the custom id for this select menu. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets whether this select menu is disabled. + * + * @param disabled - Whether this select menu is disabled + */ setDisabled(disabled = true) { this.data.disabled = disabledValidator.parse(disabled); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { customIdValidator.parse(this.data.custom_id); return { @@ -595,21 +759,57 @@ __name(BaseSelectMenuBuilder, "BaseSelectMenuBuilder"); // src/components/selectMenu/ChannelSelectMenu.ts var ChannelSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement) + * .setMinValues(2); + * ``` + */ constructor(data) { super({ ...data, type: import_v103.ComponentType.ChannelSelect }); } + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ addChannelTypes(...types) { - types = normalizeArray(types); + const normalizedTypes = normalizeArray(types); this.data.channel_types ??= []; - this.data.channel_types.push(...channelTypesValidator.parse(types)); + this.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes)); return this; } + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ setChannelTypes(...types) { - types = normalizeArray(types); + const normalizedTypes = normalizeArray(types); this.data.channel_types ??= []; - this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types)); + this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes)); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { customIdValidator.parse(this.data.custom_id); return { @@ -622,6 +822,28 @@ __name(ChannelSelectMenuBuilder, "ChannelSelectMenuBuilder"); // src/components/selectMenu/MentionableSelectMenu.ts var import_v104 = require("discord-api-types/v10"); var MentionableSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: import_v104.ComponentType.MentionableSelect }); } @@ -631,6 +853,28 @@ __name(MentionableSelectMenuBuilder, "MentionableSelectMenuBuilder"); // src/components/selectMenu/RoleSelectMenu.ts var import_v105 = require("discord-api-types/v10"); var RoleSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: import_v105.ComponentType.RoleSelect }); } @@ -640,34 +884,113 @@ __name(RoleSelectMenuBuilder, "RoleSelectMenuBuilder"); // src/components/selectMenu/StringSelectMenu.ts var import_v106 = require("discord-api-types/v10"); var StringSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * The options within this select menu. + */ options; + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * options: [ + * { label: 'option 1', value: '1' }, + * { label: 'option 2', value: '2' }, + * { label: 'option 3', value: '3' }, + * ], + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1) + * .addOptions({ + * label: 'Catchy', + * value: 'catch', + * }); + * ``` + */ constructor(data) { const { options, ...initData } = data ?? {}; super({ ...initData, type: import_v106.ComponentType.StringSelect }); this.options = options?.map((option) => new StringSelectMenuOptionBuilder(option)) ?? []; } + /** + * Adds options to this select menu. + * + * @param options - The options to add + */ addOptions(...options) { - options = normalizeArray(options); - optionsLengthValidator.parse(this.options.length + options.length); + const normalizedOptions = normalizeArray(options); + optionsLengthValidator.parse(this.options.length + normalizedOptions.length); this.options.push( - ...options.map( - (option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)) + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) ) ); return this; } + /** + * Sets the options for this select menu. + * + * @param options - The options to set + */ setOptions(...options) { - options = normalizeArray(options); - optionsLengthValidator.parse(options.length); - this.options.splice( - 0, - this.options.length, - ...options.map( - (option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)) + return this.spliceOptions(0, this.options.length, ...options); + } + /** + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index, deleteCount, ...options) { + const normalizedOptions = normalizeArray(options); + const clone = [...this.options]; + clone.splice( + index, + deleteCount, + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) ) ); + optionsLengthValidator.parse(clone.length); + this.options.splice(0, this.options.length, ...clone); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { validateRequiredSelectMenuParameters(this.options, this.data.custom_id); return { @@ -681,6 +1004,28 @@ __name(StringSelectMenuBuilder, "StringSelectMenuBuilder"); // src/components/selectMenu/UserSelectMenu.ts var import_v107 = require("discord-api-types/v10"); var UserSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: import_v107.ComponentType.UserSelect }); } @@ -722,47 +1067,116 @@ __name(validateRequiredParameters, "validateRequiredParameters"); // src/components/textInput/TextInput.ts var TextInputBuilder = class extends ComponentBuilder { + /** + * Creates a new text input from API data. + * + * @param data - The API data to create this text input with + * @example + * Creating a select menu option from an API data object: + * ```ts + * const textInput = new TextInputBuilder({ + * custom_id: 'a cool select menu', + * label: 'Type something', + * style: TextInputStyle.Short, + * }); + * ``` + * @example + * Creating a select menu option using setters and API data: + * ```ts + * const textInput = new TextInputBuilder({ + * label: 'Type something else', + * }) + * .setCustomId('woah') + * .setStyle(TextInputStyle.Paragraph); + * ``` + */ constructor(data) { super({ type: import_v109.ComponentType.TextInput, ...data }); } + /** + * Sets the custom id for this text input. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets the label for this text input. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = labelValidator.parse(label); return this; } + /** + * Sets the style for this text input. + * + * @param style - The style to use + */ setStyle(style) { this.data.style = textInputStyleValidator.parse(style); return this; } + /** + * Sets the minimum length of text for this text input. + * + * @param minLength - The minimum length of text for this text input + */ setMinLength(minLength) { this.data.min_length = minLengthValidator.parse(minLength); return this; } + /** + * Sets the maximum length of text for this text input. + * + * @param maxLength - The maximum length of text for this text input + */ setMaxLength(maxLength) { this.data.max_length = maxLengthValidator.parse(maxLength); return this; } + /** + * Sets the placeholder for this text input. + * + * @param placeholder - The placeholder to use + */ setPlaceholder(placeholder) { this.data.placeholder = placeholderValidator2.parse(placeholder); return this; } + /** + * Sets the value for this text input. + * + * @param value - The value to use + */ setValue(value) { this.data.value = valueValidator.parse(value); return this; } + /** + * Sets whether this text input is required. + * + * @param required - Whether this text input is required + */ setRequired(required = true) { this.data.required = requiredValidator.parse(required); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label); return { ...this.data }; } + /** + * {@inheritDoc Equatable.equals} + */ equals(other) { if ((0, import_util.isJSONEncodable)(other)) { return (0, import_fast_deep_equal.default)(other.toJSON(), this.data); @@ -802,19 +1216,69 @@ __name(createComponentBuilder, "createComponentBuilder"); // src/components/ActionRow.ts var ActionRowBuilder = class extends ComponentBuilder { + /** + * The components within this action row. + */ components; + /** + * Creates a new action row from API data. + * + * @param data - The API data to create this action row with + * @example + * Creating an action row from an API data object: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Type something", + * style: TextInputStyle.Short, + * type: ComponentType.TextInput, + * }, + * ], + * }); + * ``` + * @example + * Creating an action row using setters and API data: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Click me", + * style: ButtonStyle.Primary, + * type: ComponentType.Button, + * }, + * ], + * }) + * .addComponents(button2, button3); + * ``` + */ constructor({ components, ...data } = {}) { super({ type: import_v1011.ComponentType.ActionRow, ...data }); this.components = components?.map((component) => createComponentBuilder(component)) ?? []; } + /** + * Adds components to this action row. + * + * @param components - The components to add + */ addComponents(...components) { this.components.push(...normalizeArray(components)); return this; } + /** + * Sets components for this action row. + * + * @param components - The components to set + */ setComponents(...components) { this.components.splice(0, this.components.length, ...normalizeArray(components)); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { return { ...this.data, @@ -843,20 +1307,46 @@ __name(validateRequiredParameters2, "validateRequiredParameters"); // src/interactions/modals/Modal.ts var ModalBuilder = class { + /** + * The API data associated with this modal. + */ data; + /** + * The components within this modal. + */ components = []; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ constructor({ components, ...data } = {}) { this.data = { ...data }; this.components = components?.map((component) => createComponentBuilder(component)) ?? []; } + /** + * Sets the title of this modal. + * + * @param title - The title to use + */ setTitle(title) { this.data.title = titleValidator.parse(title); return this; } + /** + * Sets the custom id of this modal. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Adds components to this modal. + * + * @param components - The components to add + */ addComponents(...components) { this.components.push( ...normalizeArray(components).map( @@ -865,10 +1355,18 @@ var ModalBuilder = class { ); return this; } + /** + * Sets components for this modal. + * + * @param components - The components to set + */ setComponents(...components) { this.components.splice(0, this.components.length, ...normalizeArray(components)); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredParameters2(this.data.custom_id, this.data.title, this.components); return { @@ -892,6 +1390,7 @@ __export(Assertions_exports5, { validateLocale: () => validateLocale, validateLocalizationMap: () => validateLocalizationMap, validateMaxOptionsLength: () => validateMaxOptionsLength, + validateNSFW: () => validateNSFW, validateName: () => validateName, validateRequired: () => validateRequired, validateRequiredParameters: () => validateRequiredParameters3 @@ -961,6 +1460,10 @@ function validateDefaultMemberPermissions(permissions) { return memberPermissionPredicate.parse(permissions); } __name(validateDefaultMemberPermissions, "validateDefaultMemberPermissions"); +function validateNSFW(value) { + booleanPredicate.parse(value); +} +__name(validateNSFW, "validateNSFW"); // src/interactions/slashCommands/SlashCommandBuilder.ts var import_ts_mixer6 = require("ts-mixer"); @@ -971,20 +1474,48 @@ var import_ts_mixer5 = require("ts-mixer"); // src/interactions/slashCommands/mixins/NameAndDescription.ts var SharedNameAndDescription = class { + /** + * The name of this command. + */ name; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The description of this command. + */ description; + /** + * The description localizations of this command. + */ description_localizations; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ setName(name) { validateName(name); Reflect.set(this, "name", name); return this; } + /** + * Sets the description of this command. + * + * @param description - The description to use + */ setDescription(description) { validateDescription(description); Reflect.set(this, "description", description); return this; } + /** + * SSets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ setNameLocalization(locale, localizedName) { if (!this.name_localizations) { Reflect.set(this, "name_localizations", {}); @@ -998,6 +1529,11 @@ var SharedNameAndDescription = class { this.name_localizations[parsedLocale] = localizedName; return this; } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ setNameLocalizations(localizedNames) { if (localizedNames === null) { Reflect.set(this, "name_localizations", null); @@ -1009,6 +1545,12 @@ var SharedNameAndDescription = class { } return this; } + /** + * Sets a description localization for this command. + * + * @param locale - The locale to set + * @param localizedDescription - The localized description for the given locale + */ setDescriptionLocalization(locale, localizedDescription) { if (!this.description_localizations) { Reflect.set(this, "description_localizations", {}); @@ -1022,6 +1564,11 @@ var SharedNameAndDescription = class { this.description_localizations[parsedLocale] = localizedDescription; return this; } + /** + * Sets the description localizations for this command. + * + * @param localizedDescriptions - The object of localized descriptions to set + */ setDescriptionLocalizations(localizedDescriptions) { if (localizedDescriptions === null) { Reflect.set(this, "description_localizations", null); @@ -1041,12 +1588,25 @@ var import_v1013 = require("discord-api-types/v10"); // src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts var ApplicationCommandOptionBase = class extends SharedNameAndDescription { + /** + * Whether this option is required. + * + * @defaultValue `false` + */ required = false; + /** + * Sets whether this option is required. + * + * @param required - Whether this option should be required + */ setRequired(required) { validateRequired(required); Reflect.set(this, "required", required); return this; } + /** + * This method runs required validators on this builder. + */ runRequiredValidations() { validateRequiredParameters3(this.name, this.description, []); validateLocalizationMap(this.name_localizations); @@ -1058,7 +1618,13 @@ __name(ApplicationCommandOptionBase, "ApplicationCommandOptionBase"); // src/interactions/slashCommands/options/attachment.ts var SlashCommandAttachmentOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1013.ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1069,7 +1635,13 @@ __name(SlashCommandAttachmentOption, "SlashCommandAttachmentOption"); // src/interactions/slashCommands/options/boolean.ts var import_v1014 = require("discord-api-types/v10"); var SlashCommandBooleanOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1014.ApplicationCommandOptionType.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1097,7 +1669,15 @@ var allowedChannelTypes = [ ]; var channelTypesPredicate = import_shapeshift6.s.array(import_shapeshift6.s.union(...allowedChannelTypes.map((type) => import_shapeshift6.s.literal(type)))); var ApplicationCommandOptionChannelTypesMixin = class { + /** + * The channel types of this option. + */ channel_types; + /** + * Adds channel types to this option. + * + * @param channelTypes - The channel types + */ addChannelTypes(...channelTypes) { if (this.channel_types === void 0) { Reflect.set(this, "channel_types", []); @@ -1110,7 +1690,13 @@ __name(ApplicationCommandOptionChannelTypesMixin, "ApplicationCommandOptionChann // src/interactions/slashCommands/options/channel.ts var SlashCommandChannelOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1016.ApplicationCommandOptionType.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1128,7 +1714,13 @@ var import_ts_mixer2 = require("ts-mixer"); // src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts var ApplicationCommandNumericOptionMinMaxValueMixin = class { + /** + * The maximum value of this option. + */ max_value; + /** + * The minimum value of this option. + */ min_value; }; __name(ApplicationCommandNumericOptionMinMaxValueMixin, "ApplicationCommandNumericOptionMinMaxValueMixin"); @@ -1145,9 +1737,25 @@ var choicesPredicate = import_shapeshift7.s.object({ }).array; var booleanPredicate2 = import_shapeshift7.s.boolean; var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { + /** + * The choices of this option. + */ choices; + /** + * Whether this option utilizes autocomplete. + */ autocomplete; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ type; + /** + * Adds multiple choices to this option. + * + * @param choices - The choices to add + */ addChoices(...choices) { if (choices.length > 0 && this.autocomplete) { throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); @@ -1167,6 +1775,11 @@ var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { } return this; } + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ setChoices(...choices) { if (choices.length > 0 && this.autocomplete) { throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); @@ -1176,6 +1789,11 @@ var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { this.addChoices(...choices); return this; } + /** + * Whether this option uses autocomplete. + * + * @param autocomplete - Whether this option should use autocomplete + */ setAutocomplete(autocomplete) { booleanPredicate2.parse(autocomplete); if (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1190,17 +1808,29 @@ __name(ApplicationCommandOptionWithChoicesAndAutocompleteMixin, "ApplicationComm // src/interactions/slashCommands/options/integer.ts var numberValidator = import_shapeshift8.s.number.int; var SlashCommandIntegerOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1018.ApplicationCommandOptionType.Integer; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ setMaxValue(max) { numberValidator.parse(max); Reflect.set(this, "max_value", max); return this; } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ setMinValue(min) { numberValidator.parse(min); Reflect.set(this, "min_value", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1217,7 +1847,13 @@ SlashCommandIntegerOption = __decorateClass([ // src/interactions/slashCommands/options/mentionable.ts var import_v1019 = require("discord-api-types/v10"); var SlashCommandMentionableOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1019.ApplicationCommandOptionType.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1231,17 +1867,29 @@ var import_v1020 = require("discord-api-types/v10"); var import_ts_mixer3 = require("ts-mixer"); var numberValidator2 = import_shapeshift9.s.number; var SlashCommandNumberOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1020.ApplicationCommandOptionType.Number; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ setMaxValue(max) { numberValidator2.parse(max); Reflect.set(this, "max_value", max); return this; } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ setMinValue(min) { numberValidator2.parse(min); Reflect.set(this, "min_value", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1258,7 +1906,13 @@ SlashCommandNumberOption = __decorateClass([ // src/interactions/slashCommands/options/role.ts var import_v1021 = require("discord-api-types/v10"); var SlashCommandRoleOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1021.ApplicationCommandOptionType.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1273,19 +1927,41 @@ var import_ts_mixer4 = require("ts-mixer"); var minLengthValidator2 = import_shapeshift10.s.number.greaterThanOrEqual(0).lessThanOrEqual(6e3); var maxLengthValidator2 = import_shapeshift10.s.number.greaterThanOrEqual(1).lessThanOrEqual(6e3); var SlashCommandStringOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1022.ApplicationCommandOptionType.String; + /** + * The maximum length of this option. + */ max_length; + /** + * The minimum length of this option. + */ min_length; + /** + * Sets the maximum length of this string option. + * + * @param max - The maximum length this option can be + */ setMaxLength(max) { maxLengthValidator2.parse(max); Reflect.set(this, "max_length", max); return this; } + /** + * Sets the minimum length of this string option. + * + * @param min - The minimum length this option can be + */ setMinLength(min) { minLengthValidator2.parse(min); Reflect.set(this, "min_length", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1302,7 +1978,13 @@ SlashCommandStringOption = __decorateClass([ // src/interactions/slashCommands/options/user.ts var import_v1023 = require("discord-api-types/v10"); var SlashCommandUserOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1023.ApplicationCommandOptionType.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1313,33 +1995,85 @@ __name(SlashCommandUserOption, "SlashCommandUserOption"); // src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts var SharedSlashCommandOptions = class { options; + /** + * Adds a boolean option. + * + * @param input - A function that returns an option builder or an already built builder + */ addBooleanOption(input) { return this._sharedAddOptionMethod(input, SlashCommandBooleanOption); } + /** + * Adds a user option. + * + * @param input - A function that returns an option builder or an already built builder + */ addUserOption(input) { return this._sharedAddOptionMethod(input, SlashCommandUserOption); } + /** + * Adds a channel option. + * + * @param input - A function that returns an option builder or an already built builder + */ addChannelOption(input) { return this._sharedAddOptionMethod(input, SlashCommandChannelOption); } + /** + * Adds a role option. + * + * @param input - A function that returns an option builder or an already built builder + */ addRoleOption(input) { return this._sharedAddOptionMethod(input, SlashCommandRoleOption); } + /** + * Adds an attachment option. + * + * @param input - A function that returns an option builder or an already built builder + */ addAttachmentOption(input) { return this._sharedAddOptionMethod(input, SlashCommandAttachmentOption); } + /** + * Adds a mentionable option. + * + * @param input - A function that returns an option builder or an already built builder + */ addMentionableOption(input) { return this._sharedAddOptionMethod(input, SlashCommandMentionableOption); } + /** + * Adds a string option. + * + * @param input - A function that returns an option builder or an already built builder + */ addStringOption(input) { return this._sharedAddOptionMethod(input, SlashCommandStringOption); } + /** + * Adds an integer option. + * + * @param input - A function that returns an option builder or an already built builder + */ addIntegerOption(input) { return this._sharedAddOptionMethod(input, SlashCommandIntegerOption); } + /** + * Adds a number option. + * + * @param input - A function that returns an option builder or an already built builder + */ addNumberOption(input) { return this._sharedAddOptionMethod(input, SlashCommandNumberOption); } + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ _sharedAddOptionMethod(input, Instance) { const { options } = this; validateMaxOptionsLength(options); @@ -1353,9 +2087,23 @@ __name(SharedSlashCommandOptions, "SharedSlashCommandOptions"); // src/interactions/slashCommands/SlashCommandSubcommands.ts var SlashCommandSubcommandGroupBuilder = class { + /** + * The name of this subcommand group. + */ name = void 0; + /** + * The description of this subcommand group. + */ description = void 0; + /** + * The subcommands within this subcommand group. + */ options = []; + /** + * Adds a new subcommand to this group. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ addSubcommand(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1364,6 +2112,13 @@ var SlashCommandSubcommandGroupBuilder = class { options.push(result); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters3(this.name, this.description, this.options); return { @@ -1381,9 +2136,25 @@ SlashCommandSubcommandGroupBuilder = __decorateClass([ (0, import_ts_mixer5.mix)(SharedNameAndDescription) ], SlashCommandSubcommandGroupBuilder); var SlashCommandSubcommandBuilder = class { + /** + * The name of this subcommand. + */ name = void 0; + /** + * The description of this subcommand. + */ description = void 0; + /** + * The options within this subcommand. + */ options = []; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters3(this.name, this.description, this.options); return { @@ -1403,38 +2174,102 @@ SlashCommandSubcommandBuilder = __decorateClass([ // src/interactions/slashCommands/SlashCommandBuilder.ts var SlashCommandBuilder = class { + /** + * The name of this command. + */ name = void 0; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The description of this command. + */ description = void 0; + /** + * The description localizations of this command. + */ description_localizations; + /** + * The options of this command. + */ options = []; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ dm_permission = void 0; - toJSON() { - validateRequiredParameters3(this.name, this.description, this.options); - validateLocalizationMap(this.name_localizations); - validateLocalizationMap(this.description_localizations); - return { - ...this, - options: this.options.map((option) => option.toJSON()) - }; - } + /** + * Whether this command is NSFW. + */ + nsfw = void 0; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether or not to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. + */ setDefaultPermission(value) { validateDefaultPermission(value); Reflect.set(this, "default_permission", value); return this; } + /** + * Sets the default permissions a member should have in order to run the command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDefaultMemberPermissions(permissions) { const permissionValue = validateDefaultMemberPermissions(permissions); Reflect.set(this, "default_member_permissions", permissionValue); return this; } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDMPermission(enabled) { validateDMPermission(enabled); Reflect.set(this, "dm_permission", enabled); return this; } + /** + * Sets whether this command is NSFW. + * + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw = true) { + validateNSFW(nsfw); + Reflect.set(this, "nsfw", nsfw); + return this; + } + /** + * Adds a new subcommand group to this command. + * + * @param input - A function that returns a subcommand group builder or an already built builder + */ addSubcommandGroup(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1443,6 +2278,11 @@ var SlashCommandBuilder = class { options.push(result); return this; } + /** + * Adds a new subcommand to this command. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ addSubcommand(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1451,6 +2291,22 @@ var SlashCommandBuilder = class { options.push(result); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + return { + ...this, + options: this.options.map((option) => option.toJSON()) + }; + } }; __name(SlashCommandBuilder, "SlashCommandBuilder"); SlashCommandBuilder = __decorateClass([ @@ -1506,37 +2362,101 @@ __name(validateDefaultMemberPermissions2, "validateDefaultMemberPermissions"); // src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts var ContextMenuCommandBuilder = class { + /** + * The name of this command. + */ name = void 0; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The type of this command. + */ type = void 0; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ dm_permission = void 0; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ setName(name) { validateName2(name); Reflect.set(this, "name", name); return this; } + /** + * Sets the type of this command. + * + * @param type - The type to use + */ setType(type) { validateType(type); Reflect.set(this, "type", type); return this; } + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ setDefaultPermission(value) { validateDefaultPermission2(value); Reflect.set(this, "default_permission", value); return this; } + /** + * Sets the default permissions a member should have in order to run this command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDefaultMemberPermissions(permissions) { const permissionValue = validateDefaultMemberPermissions2(permissions); Reflect.set(this, "default_member_permissions", permissionValue); return this; } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDMPermission(enabled) { validateDMPermission2(enabled); Reflect.set(this, "dm_permission", enabled); return this; } + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ setNameLocalization(locale, localizedName) { if (!this.name_localizations) { Reflect.set(this, "name_localizations", {}); @@ -1550,6 +2470,11 @@ var ContextMenuCommandBuilder = class { this.name_localizations[parsedLocale] = localizedName; return this; } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ setNameLocalizations(localizedNames) { if (localizedNames === null) { Reflect.set(this, "name_localizations", null); @@ -1560,6 +2485,13 @@ var ContextMenuCommandBuilder = class { this.setNameLocalization(...args); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters4(this.name, this.type); validateLocalizationMap(this.name_localizations); @@ -1575,8 +2507,7 @@ function embedLength(data) { __name(embedLength, "embedLength"); // src/index.ts -__reExport(src_exports, require("@discordjs/util"), module.exports); -var version = "1.4.0"; +var version = "1.6.3"; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { ActionRowBuilder, @@ -1593,7 +2524,6 @@ var version = "1.4.0"; ContextMenuCommandBuilder, EmbedAssertions, EmbedBuilder, - Faces, MentionableSelectMenuBuilder, ModalAssertions, ModalBuilder, @@ -1619,33 +2549,14 @@ var version = "1.4.0"; StringSelectMenuOptionBuilder, TextInputAssertions, TextInputBuilder, - TimestampStyles, UserSelectMenuBuilder, - blockQuote, - bold, - channelLink, - channelMention, - chatInputApplicationCommandMention, - codeBlock, createComponentBuilder, disableValidators, embedLength, enableValidators, - formatEmoji, - hideLinkEmbed, - hyperlink, - inlineCode, isValidationEnabled, - italic, - messageLink, normalizeArray, - quote, - roleMention, - spoiler, - strikethrough, - time, - underscore, - userMention, - version + version, + ...require("@discordjs/formatters") }); //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.js.map b/node_modules/@discordjs/builders/dist/index.js.map index 0e76328..11b933a 100644 --- a/node_modules/@discordjs/builders/dist/index.js.map +++ b/node_modules/@discordjs/builders/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/messages/formatters.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts"],"sourcesContent":["export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\nexport * from './messages/formatters.js';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\nexport * from '@discordjs/util';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders/#readme | @discordjs/builders} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.4.0';\n","import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\nexport const enableValidators = () => (validate = true);\nexport const disableValidators = () => (validate = false);\nexport const isValidationEnabled = () => validate;\n","export function normalizeArray(arr: RestOrArray): T[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as T[];\n}\n\nexport type RestOrArray = T[] | [T[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\nexport type RGBTuple = [red: number, green: number, blue: number];\n\nexport interface IconData {\n\t/**\n\t * The URL of the icon\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon\n\t */\n\tproxyIconURL?: string;\n}\n\nexport type EmbedAuthorData = IconData & Omit;\n\nexport type EmbedAuthorOptions = Omit;\n\nexport type EmbedFooterData = IconData & Omit;\n\nexport type EmbedFooterOptions = Omit;\n\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image\n\t */\n\tproxyURL?: string;\n}\n/**\n * Represents a embed in a message (image/video preview, rich embed, etc.)\n */\nexport class EmbedBuilder {\n\tpublic readonly data: APIEmbed;\n\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic)\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\tfields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\n\t\tif (this.data.fields) this.data.fields.push(...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields in the embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields\n\t * ```ts\n\t * const n = 4\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the embed's fields\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed\n\t *\n\t * @param options - The options for the author\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed\n\t *\n\t * @param color - The color of the embed\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed\n\t *\n\t * @param description - The description\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed\n\t *\n\t * @param options - The options for the footer\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed\n\t *\n\t * @param url - The URL of the image\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed\n\t *\n\t * @param url - The URL of the thumbnail\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed\n\t *\n\t * @param timestamp - The timestamp or date\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title of this embed\n\t *\n\t * @param title - The title\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed\n\t *\n\t * @param url - The URL\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Transforms the embed to a plain object\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","import type { URL } from 'node:url';\nimport type { Snowflake } from 'discord-api-types/globals';\n\n/**\n * Wraps the content inside a codeblock with no language\n *\n * @param content - The content to wrap\n */\nexport function codeBlock(content: C): `\\`\\`\\`\\n${C}\\n\\`\\`\\``;\n\n/**\n * Wraps the content inside a codeblock with the specified language\n *\n * @param language - The language for the codeblock\n * @param content - The content to wrap\n */\nexport function codeBlock(language: L, content: C): `\\`\\`\\`${L}\\n${C}\\n\\`\\`\\``;\nexport function codeBlock(language: string, content?: string): string {\n\treturn typeof content === 'undefined' ? `\\`\\`\\`\\n${language}\\n\\`\\`\\`` : `\\`\\`\\`${language}\\n${content}\\n\\`\\`\\``;\n}\n\n/**\n * Wraps the content inside \\`backticks\\`, which formats it as inline code\n *\n * @param content - The content to wrap\n */\nexport function inlineCode(content: C): `\\`${C}\\`` {\n\treturn `\\`${content}\\``;\n}\n\n/**\n * Formats the content into italic text\n *\n * @param content - The content to wrap\n */\nexport function italic(content: C): `_${C}_` {\n\treturn `_${content}_`;\n}\n\n/**\n * Formats the content into bold text\n *\n * @param content - The content to wrap\n */\nexport function bold(content: C): `**${C}**` {\n\treturn `**${content}**`;\n}\n\n/**\n * Formats the content into underscored text\n *\n * @param content - The content to wrap\n */\nexport function underscore(content: C): `__${C}__` {\n\treturn `__${content}__`;\n}\n\n/**\n * Formats the content into strike-through text\n *\n * @param content - The content to wrap\n */\nexport function strikethrough(content: C): `~~${C}~~` {\n\treturn `~~${content}~~`;\n}\n\n/**\n * Formats the content into a quote. This needs to be at the start of the line for Discord to format it\n *\n * @param content - The content to wrap\n */\nexport function quote(content: C): `> ${C}` {\n\treturn `> ${content}`;\n}\n\n/**\n * Formats the content into a block quote. This needs to be at the start of the line for Discord to format it\n *\n * @param content - The content to wrap\n */\nexport function blockQuote(content: C): `>>> ${C}` {\n\treturn `>>> ${content}`;\n}\n\n/**\n * Wraps the URL into `<>`, which stops it from embedding\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: C): `<${C}>`;\n\n/**\n * Wraps the URL into `<>`, which stops it from embedding\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: URL): `<${string}>`;\nexport function hideLinkEmbed(url: URL | string) {\n\treturn `<${url}>`;\n}\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: URL): `[${C}](${string})`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: U): `[${C}](${U})`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: URL,\n\ttitle: T,\n): `[${C}](${string} \"${T}\")`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: U,\n\ttitle: T,\n): `[${C}](${U} \"${T}\")`;\nexport function hyperlink(content: string, url: URL | string, title?: string) {\n\treturn title ? `[${content}](${url} \"${title}\")` : `[${content}](${url})`;\n}\n\n/**\n * Wraps the content inside spoiler (hidden text)\n *\n * @param content - The content to wrap\n */\nexport function spoiler(content: C): `||${C}||` {\n\treturn `||${content}||`;\n}\n\n/**\n * Formats a user ID into a user mention\n *\n * @param userId - The user ID to format\n */\nexport function userMention(userId: C): `<@${C}>` {\n\treturn `<@${userId}>`;\n}\n\n/**\n * Formats a channel ID into a channel mention\n *\n * @param channelId - The channel ID to format\n */\nexport function channelMention(channelId: C): `<#${C}>` {\n\treturn `<#${channelId}>`;\n}\n\n/**\n * Formats a role ID into a role mention\n *\n * @param roleId - The role ID to format\n */\nexport function roleMention(roleId: C): `<@&${C}>` {\n\treturn `<@&${roleId}>`;\n}\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends string,\n\tS extends string,\n\tI extends Snowflake,\n>(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): ``;\n\n/**\n * Formats an application command name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tsubcommandName: S,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends Snowflake | string,\n\tS extends Snowflake | string,\n\tI extends Snowflake,\n>(\n\tcommandName: N,\n\tsubcommandGroupName: G,\n\tsubcommandName?: S,\n\tcommandId?: I,\n): `` | `` | `` {\n\tif (typeof commandId !== 'undefined') {\n\t\treturn ``;\n\t}\n\n\tif (typeof subcommandName !== 'undefined') {\n\t\treturn ``;\n\t}\n\n\treturn ``;\n}\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n */\nexport function formatEmoji(emojiId: C, animated?: false): `<:_:${C}>`;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated?: true): ``;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated?: boolean): `<:_:${C}>` | ``;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated = false): `<:_:${C}>` | `` {\n\treturn `<${animated ? 'a' : ''}:_:${emojiId}>`;\n}\n\n/**\n * Formats a channel link for a direct message channel.\n *\n * @param channelId - The channel's id\n */\nexport function channelLink(channelId: C): `https://discord.com/channels/@me/${C}`;\n\n/**\n * Formats a channel link for a guild channel.\n *\n * @param channelId - The channel's id\n * @param guildId - The guild's id\n */\nexport function channelLink(\n\tchannelId: C,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}`;\n\nexport function channelLink(\n\tchannelId: C,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}` | `https://discord.com/channels/${G}/${C}` {\n\treturn `https://discord.com/channels/${guildId ?? '@me'}/${channelId}`;\n}\n\n/**\n * Formats a message link for a direct message channel.\n *\n * @param channelId - The channel's id\n * @param messageId - The message's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n): `https://discord.com/channels/@me/${C}/${M}`;\n\n/**\n * Formats a message link for a guild channel.\n *\n * @param channelId - The channel's id\n * @param messageId - The message's id\n * @param guildId - The guild's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}/${M}`;\n\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}/${M}` | `https://discord.com/channels/${G}/${C}/${M}` {\n\treturn `${typeof guildId === 'undefined' ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`;\n}\n\n/**\n * Formats a date into a short date-time string\n *\n * @param date - The date to format, defaults to the current time\n */\nexport function time(date?: Date): ``;\n\n/**\n * Formats a date given a format style\n *\n * @param date - The date to format\n * @param style - The style to use\n */\nexport function time(date: Date, style: S): ``;\n\n/**\n * Formats the given timestamp into a short date-time string\n *\n * @param seconds - The time to format, represents an UNIX timestamp in seconds\n */\nexport function time(seconds: C): ``;\n\n/**\n * Formats the given timestamp into a short date-time string\n *\n * @param seconds - The time to format, represents an UNIX timestamp in seconds\n * @param style - The style to use\n */\nexport function time(seconds: C, style: S): ``;\nexport function time(timeOrSeconds?: Date | number, style?: TimestampStylesString): string {\n\tif (typeof timeOrSeconds !== 'number') {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttimeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1_000);\n\t}\n\n\treturn typeof style === 'string' ? `` : ``;\n}\n\n/**\n * The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles} supported by Discord\n */\nexport const TimestampStyles = {\n\t/**\n\t * Short time format, consisting of hours and minutes, e.g. 16:20\n\t */\n\tShortTime: 't',\n\n\t/**\n\t * Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30\n\t */\n\tLongTime: 'T',\n\n\t/**\n\t * Short date format, consisting of day, month, and year, e.g. 20/04/2021\n\t */\n\tShortDate: 'd',\n\n\t/**\n\t * Long date format, consisting of day, month, and year, e.g. 20 April 2021\n\t */\n\tLongDate: 'D',\n\n\t/**\n\t * Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20\n\t */\n\tShortDateTime: 'f',\n\n\t/**\n\t * Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20\n\t */\n\tLongDateTime: 'F',\n\n\t/**\n\t * Relative time format, consisting of a relative duration format, e.g. 2 months ago\n\t */\n\tRelativeTime: 'R',\n} as const;\n\n/**\n * The possible values, see {@link TimestampStyles} for more information\n */\nexport type TimestampStylesString = typeof TimestampStyles[keyof typeof TimestampStyles];\n\n/**\n * An enum with all the available faces from Discord's native slash commands\n */\nexport enum Faces {\n\t/**\n\t * ¯\\\\_(ツ)\\\\_/¯\n\t */\n\tShrug = '¯\\\\_(ツ)\\\\_/¯',\n\n\t/**\n\t * (╯°□°)╯︵ ┻━┻\n\t */\n\tTableflip = '(╯°□°)╯︵ ┻━┻',\n\n\t/**\n\t * ┬─┬ ノ( ゜-゜ノ)\n\t */\n\tUnflip = '┬─┬ ノ( ゜-゜ノ)',\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * Represents an option within a string select menu component\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah')\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label of this option\n\t *\n\t * @param label - The label to show on this option\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value of this option\n\t *\n\t * @param value - The value of this option\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this option\n\t *\n\t * @param description - The description of this option\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this option\n\t *\n\t * @param emoji - The emoji to display on this option\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * Represents an action row component\n *\n * @typeParam T - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row\n\t */\n\tpublic readonly components: T[];\n\n\t/**\n\t * Creates a new action row from API data\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as T[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add to this action row.\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the components in this action row\n\t *\n\t * @param components - The components to set this row to\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * Represents a discord component\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this component to an API-compatible JSON object\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\nexport interface MappedComponentTypes {\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t[ComponentType.Button]: ButtonBuilder;\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data\n *\n * @param data - The api data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members\n\tdata: (APIModalComponent | APIMessageComponent) & { type: T },\n): MappedComponentTypes[T];\nexport function createComponentBuilder(data: C): C;\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error: This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * Represents a button component\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: '🙂' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button\n\t *\n\t * @param style - The style of the button\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://` and `discord://`\n\t * @param url - The URL to open when this button is clicked\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use for this button\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button\n\t *\n\t * @param emoji - The emoji to display on this button\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button\n\t *\n\t * @param label - The label to display on this button\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import type { APIChannelSelectComponent, ChannelType } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttypes = normalizeArray(types);\n\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(types));\n\t\treturn this;\n\t}\n\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttypes = normalizeArray(types);\n\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\nexport class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu\n\t *\n\t * @param placeholder - The placeholder to use for this select menu\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu\n\t *\n\t * @param customId - The custom id to use for this select menu\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import type { APIMentionableSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n}\n","import type { APIRoleSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n}\n","import type { APIStringSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType, type APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * Represents a string select menu component\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu\n\t *\n\t * @param options - The options to add to this select menu\n\t * @returns\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\toptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + options.length);\n\t\tthis.options.push(\n\t\t\t...options.map((option) =>\n\t\t\t\toption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? option\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options on this select menu\n\t *\n\t * @param options - The options to set on this select menu\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\toptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(options.length);\n\t\tthis.options.splice(\n\t\t\t0,\n\t\t\tthis.options.length,\n\t\t\t...options.map((option) =>\n\t\t\t\toption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? option\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import type { APIUserSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input\n\t *\n\t * @param customId - The custom id of this text input\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input\n\t *\n\t * @param label - The label for this text input\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input\n\t *\n\t * @param style - The style for this text input\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder of this text input\n\t *\n\t * @param placeholder - The placeholder of this text input\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value of this text input\n\t *\n\t * @param value - The value for this text input\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\nexport class ModalBuilder implements JSONEncodable {\n\tpublic readonly data: Partial;\n\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of the modal\n\t *\n\t * @param title - The title of the modal\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of the modal\n\t *\n\t * @param customId - The custom id of this modal\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal\n\t *\n\t * @param components - The components to add to this modal\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the components in this modal\n\t *\n\t * @param components - The components to set this modal to\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tT extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this slash command\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The localized names for this command\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this slash command\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The localized descriptions for this command\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this slash command\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether the command is enabled by default when the app is added to a guild\n\t *\n\t * @deprecated This property is deprecated and will be removed in the future.\n\t * You should use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Set of permissions represented as a bit set for the command\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Returns the final data that should be sent to Discord.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t * @deprecated Use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t *\n\t * @param enabled - If the command should be enabled in DMs\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command\n\t *\n\t * @param input - A function that returns a subcommand group builder, or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command\n\t *\n\t * @param input - A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands\n *\n * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands part of this subcommand group\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group\n\t *\n\t * @param input - A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * Represents a subcommand\n *\n * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options of this subcommand\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\nexport class SharedNameAndDescription {\n\tpublic readonly name!: string;\n\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\tpublic readonly description!: string;\n\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name\n\t *\n\t * @param name - The name\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description\n\t *\n\t * @param description - The description\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedName - The localized description for the given locale\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations\n\t *\n\t * @param localizedNames - The dictionary of localized descriptions to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations\n\t *\n\t * @param localizedDescriptions - The dictionary of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Marks the option as required\n\t *\n\t * @param required - If this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n// Only allow valid channel types to be used. (This can't be dynamic because const enums are erased at runtime)\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n] as const;\n\nexport type ApplicationCommandOptionAllowedChannelTypes = typeof allowedChannelTypes[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\nexport class ApplicationCommandOptionChannelTypesMixin {\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option\n\t *\n\t * @param channelTypes - The channel types to add\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","export abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\tpublic readonly max_value?: number;\n\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\tpublic readonly autocomplete?: boolean;\n\n\t// Since this is present and this is a mixin, this is needed\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices for this option\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Marks the option as autocompletable\n\t *\n\t * @param autocomplete - If this option should be autocompletable\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\tpublic readonly max_length?: number;\n\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| T\n\t\t\t| ((builder: T) => Omit | Omit | T),\n\t\tInstance: new () => T,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group, unicorn/no-unsafe-regex\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this context menu command\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The localized names for this command\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this context menu command\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether the command is enabled by default when the app is added to a guild\n\t *\n\t * @deprecated This property is deprecated and will be removed in the future.\n\t * You should use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Set of permissions represented as a bit set for the command\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name\n\t *\n\t * @param name - The name\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type\n\t *\n\t * @param type - The type\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t *\n\t * @param enabled - If the command should be enabled in DMs\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedName - The localized description for the given locale\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations\n\t *\n\t * @param localizedNames - The dictionary of localized descriptions to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the final data that should be sent to Discord.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n","import type { APIEmbed } from 'discord-api-types/v10';\n\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAAAA;AAAA,EAAA;AAAA,sCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAkB;;;ACAlB,IAAI,WAAW;AAER,IAAM,mBAAmB,6BAAO,WAAW,MAAlB;AACzB,IAAM,oBAAoB,6BAAO,WAAW,OAAlB;AAC1B,IAAM,sBAAsB,6BAAM,UAAN;;;ADA5B,IAAM,qB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AU,MAC5B,KAAK,QAAQ,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,KAAK,MACvF,KAAK,QAAQ,KAAK,UAAU,MAC5B,KAAK,QAAQ,KAAK,UAAU;AAE/B;AARgB;;;A1C0DhB,wBAAc,4BA5Dd;AAoEO,IAAM,UAAkB;","names":["Assertions_exports","Faces","Assertions_exports","import_shapeshift","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","Assertions_exports","placeholderValidator","import_shapeshift","import_v10","placeholderValidator","placeholderValidator","isEqual","Assertions_exports","validateRequiredParameters","import_shapeshift","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","import_shapeshift","import_v10","descriptionPredicate","validateRequiredParameters","import_ts_mixer","import_v10","import_ts_mixer","import_v10","validateRequiredParameters","import_v10","import_v10","import_shapeshift","import_v10","import_shapeshift","import_v10","import_ts_mixer","import_shapeshift","import_v10","booleanPredicate","import_v10","import_shapeshift","import_v10","import_ts_mixer","numberValidator","import_v10","import_shapeshift","import_v10","import_ts_mixer","minLengthValidator","maxLengthValidator","import_v10","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","import_shapeshift","import_v10","namePredicate","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts"],"sourcesContent":["export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\n// TODO: Consider removing this dep in the next major version\nexport * from '@discordjs/formatters';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version\n * that you are currently using.\n *\n * @privateRemarks This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild.\n */\nexport const version = '1.6.3' as string;\n","import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\n/**\n * Enables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function enableValidators() {\n\treturn (validate = true);\n}\n\n/**\n * Disables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function disableValidators() {\n\treturn (validate = false);\n}\n\n/**\n * Checks whether validation is occurring.\n */\nexport function isValidationEnabled() {\n\treturn validate;\n}\n","/**\n * Normalizes data that is a rest parameter or an array into an array with a depth of 1.\n *\n * @typeParam T - The data that must satisfy {@link RestOrArray}.\n * @param arr - The (possibly variadic) data to normalize\n */\nexport function normalizeArray(arr: RestOrArray): T[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as T[];\n}\n\n/**\n * Represents data that may be an array or came from a rest parameter.\n *\n * @remarks\n * This type is used throughout builders to ensure both an array and variadic arguments\n * may be used. It is normalized with {@link normalizeArray}.\n */\nexport type RestOrArray = T[] | [T[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\n/**\n * A tuple satisfying the RGB color model.\n *\n * @see {@link https://developer.mozilla.org/docs/Glossary/RGB}\n */\nexport type RGBTuple = [red: number, green: number, blue: number];\n\n/**\n * The base icon data typically used in payloads.\n */\nexport interface IconData {\n\t/**\n\t * The URL of the icon.\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon.\n\t */\n\tproxyIconURL?: string;\n}\n\n/**\n * Represents the author data of an embed.\n */\nexport type EmbedAuthorData = IconData & Omit;\n\n/**\n * Represents the author options of an embed.\n */\nexport type EmbedAuthorOptions = Omit;\n\n/**\n * Represents the footer data of an embed.\n */\nexport type EmbedFooterData = IconData & Omit;\n\n/**\n * Represents the footer options of an embed.\n */\nexport type EmbedFooterOptions = Omit;\n\n/**\n * Represents the image data of an embed.\n */\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image.\n\t */\n\tproxyURL?: string;\n}\n\n/**\n * A builder that creates API-compatible JSON data for embeds.\n */\nexport class EmbedBuilder {\n\t/**\n\t * The API data associated with this embed.\n\t */\n\tpublic readonly data: APIEmbed;\n\n\t/**\n\t * Creates a new embed from API data.\n\t *\n\t * @param data - The API data to create this embed with\n\t */\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed.\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array:\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic):\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\tconst normalizedFields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(normalizedFields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(normalizedFields);\n\n\t\tif (this.data.fields) this.data.fields.push(...normalizedFields);\n\t\telse this.data.fields = normalizedFields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields for this embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field:\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields:\n\t * ```ts\n\t * const n = 4;\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field:\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the fields for this embed.\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed.\n\t *\n\t * @param options - The options to use\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed.\n\t *\n\t * @param color - The color to use\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed.\n\t *\n\t * @param options - The footer to use\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed.\n\t *\n\t * @param url - The image URL to use\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed.\n\t *\n\t * @param url - The thumbnail URL to use\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed.\n\t *\n\t * @param timestamp - The timestamp or date to use\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title for this embed.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed.\n\t *\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menu options.\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data.\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah');\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label for this option.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this option.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description for this option.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default.\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display for this option.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * The builders that may be used for messages.\n */\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\n\n/**\n * The builders that may be used for modals.\n */\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\n\n/**\n * The builders that may be used within an action row for messages.\n */\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\n\n/**\n * The builders that may be used within an action row for modals.\n */\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\n\n/**\n * Any builder.\n */\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * A builder that creates API-compatible JSON data for action rows.\n *\n * @typeParam T - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row.\n\t */\n\tpublic readonly components: T[];\n\n\t/**\n\t * Creates a new action row from API data.\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as T[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this action row.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\n/**\n * Any action row component data represented as an object.\n */\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * The base component builder that contains common symbols for all sorts of components.\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\t/**\n\t * Constructs a new kind of component.\n\t *\n\t * @param data - The data to construct a component out of\n\t */\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * Components here are mapped to their respective builder.\n */\nexport interface MappedComponentTypes {\n\t/**\n\t * The action row component type is associated with an {@link ActionRowBuilder}.\n\t */\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t/**\n\t * The button component type is associated with an {@link ButtonBuilder}.\n\t */\n\t[ComponentType.Button]: ButtonBuilder;\n\t/**\n\t * The string select component type is associated with an {@link StringSelectMenuBuilder}.\n\t */\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t/**\n\t * The text inpiut component type is associated with an {@link TextInputBuilder}.\n\t */\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t/**\n\t * The user select component type is associated with an {@link UserSelectMenuBuilder}.\n\t */\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t/**\n\t * The role select component type is associated with an {@link RoleSelectMenuBuilder}.\n\t */\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t/**\n\t * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}.\n\t */\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t/**\n\t * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}.\n\t */\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam T - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members\n\tdata: (APIModalComponent | APIMessageComponent) & { type: T },\n): MappedComponentTypes[T];\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam C - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(data: C): C;\n\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * A builder that creates API-compatible JSON data for buttons.\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data.\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: '🙂' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button.\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`.\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button.\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled.\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import type { APIChannelSelectComponent, ChannelType } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for channel select menus.\n */\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\t/**\n\t * Adds channel types to this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets channel types for this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * The base select menu builder that contains common symbols for select menu builders.\n *\n * @typeParam SelectMenuType - The type of select menu this would be instantiated for.\n */\nexport abstract class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu.\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu.\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled.\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import type { APIMentionableSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for mentionable select menus.\n */\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n}\n","import type { APIRoleSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for role select menus.\n */\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n}\n","import { ComponentType } from 'discord-api-types/v10';\nimport type { APIStringSelectComponent, APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menus.\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu.\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu.\n\t *\n\t * @param options - The options to add\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + normalizedOptions.length);\n\t\tthis.options.push(\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options for this select menu.\n\t *\n\t * @param options - The options to set\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\treturn this.spliceOptions(0, this.options.length, ...options);\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts options for this select menu.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}.\n\t * It's useful for modifying and adjusting the order of existing options.\n\t * @example\n\t * Remove the first option:\n\t * ```ts\n\t * selectMenu.spliceOptions(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n option:\n\t * ```ts\n\t * const n = 4;\n\t * selectMenu.spliceOptions(0, n);\n\t * ```\n\t * @example\n\t * Remove the last option:\n\t * ```ts\n\t * selectMenu.spliceOptions(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of options to remove\n\t * @param options - The replacing option objects or builders\n\t */\n\tpublic spliceOptions(\n\t\tindex: number,\n\t\tdeleteCount: number,\n\t\t...options: RestOrArray\n\t) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\n\t\tconst clone = [...this.options];\n\n\t\tclone.splice(\n\t\t\tindex,\n\t\t\tdeleteCount,\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\n\t\toptionsLengthValidator.parse(clone.length);\n\t\tthis.options.splice(0, this.options.length, ...clone);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import type { APIUserSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for user select menus.\n */\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for text inputs.\n */\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data.\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input.\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input.\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder for this text input.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this text input.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required.\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for modals.\n */\nexport class ModalBuilder implements JSONEncodable {\n\t/**\n\t * The API data associated with this modal.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * The components within this modal.\n\t */\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\t/**\n\t * Creates a new modal from API data.\n\t *\n\t * @param data - The API data to create this modal with\n\t */\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of this modal.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of this modal.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this modal.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tT extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n\nexport function validateNSFW(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n\tvalidateNSFW,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * A builder that creates API-compatible JSON data for slash commands.\n */\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this command.\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Whether this command is NSFW.\n\t */\n\tpublic readonly nsfw: boolean | undefined = undefined;\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this command is NSFW.\n\t *\n\t * @param nsfw - Whether this command is NSFW\n\t */\n\tpublic setNSFW(nsfw = true) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateNSFW(nsfw);\n\t\tReflect.set(this, 'nsfw', nsfw);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command.\n\t *\n\t * @param input - A function that returns a subcommand group builder or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\n/**\n * An interface specifically for slash command subcommands.\n */\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\n/**\n * An interface specifically for slash command options.\n */\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\n/**\n * An interface that ensures the `toJSON()` call will return something\n * that can be serialized into API-compatible data.\n */\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands within this subcommand group.\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * A builder that creates API-compatible JSON data for slash command subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options within this subcommand.\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\n/**\n * This mixin holds name and description symbols for slash commands.\n */\nexport class SharedNameAndDescription {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name!: string;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description!: string;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this command.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * SSets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations for this command.\n\t *\n\t * @param localizedDescriptions - The object of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command attachment option.\n */\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\n/**\n * The base application command option builder that contains common symbols for application command builders.\n */\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\t/**\n\t * Whether this option is required.\n\t *\n\t * @defaultValue `false`\n\t */\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Sets whether this option is required.\n\t *\n\t * @param required - Whether this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\t/**\n\t * This method runs required validators on this builder.\n\t */\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command boolean option.\n */\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n/**\n * A slash command channel option.\n */\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n/**\n * The allowed channel types used for a channel option in a slash command builder.\n *\n * @privateRemarks This can't be dynamic because const enums are erased at runtime.\n * @internal\n */\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n] as const;\n\n/**\n * The type of allowed channel types used for a channel option.\n */\nexport type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\n/**\n * This mixin holds channel type symbols used for options.\n */\nexport class ApplicationCommandOptionChannelTypesMixin {\n\t/**\n\t * The channel types of this option.\n\t */\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option.\n\t *\n\t * @param channelTypes - The channel types\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n/**\n * A slash command integer option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","/**\n * This mixin holds minimum and maximum symbols used for options.\n */\nexport abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\t/**\n\t * The maximum value of this option.\n\t */\n\tpublic readonly max_value?: number;\n\n\t/**\n\t * The minimum value of this option.\n\t */\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option.\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option.\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\n/**\n * This mixin holds choices and autocomplete symbols used for options.\n */\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\t/**\n\t * The choices of this option.\n\t */\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\t/**\n\t * Whether this option utilizes autocomplete.\n\t */\n\tpublic readonly autocomplete?: boolean;\n\n\t/**\n\t * The type of this option.\n\t *\n\t * @privateRemarks Since this is present and this is a mixin, this is needed.\n\t */\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices to this option.\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets multiple choices for this option.\n\t *\n\t * @param choices - The choices to set\n\t */\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Whether this option uses autocomplete.\n\t *\n\t * @param autocomplete - Whether this option should use autocomplete\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command mentionable option.\n */\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n/**\n * A slash command number option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command role option.\n */\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n/**\n * A slash command string option.\n */\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\t/**\n\t * The maximum length of this option.\n\t */\n\tpublic readonly max_length?: number;\n\n\t/**\n\t * The minimum length of this option.\n\t */\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command user option.\n */\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\n/**\n * This mixin holds symbols that can be shared in slash command options.\n *\n * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions.\n */\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\t/**\n\t * Where the actual adding magic happens. ✨\n\t *\n\t * @param input - The input. What else?\n\t * @param Instance - The instance of whatever is being added\n\t * @internal\n\t */\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| T\n\t\t\t| ((builder: T) => Omit | Omit | T),\n\t\tInstance: new () => T,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group, unicorn/no-unsafe-regex\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\n/**\n * The type a context menu command can be.\n */\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n\n/**\n * A builder that creates API-compatible JSON data for context menu commands.\n */\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this command.\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type of this command.\n\t *\n\t * @param type - The type to use\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run this command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIEmbed } from 'discord-api-types/v10';\n\n/**\n * Calculates the length of the embed.\n *\n * @param data - The embed data to check\n */\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAAAA;AAAA,EAAA;AAAA,sCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,yBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAkB;;;ACAlB,IAAI,WAAW;AAOR,SAAS,mBAAmB;AAClC,SAAQ,WAAW;AACpB;AAFgB;AAST,SAAS,oBAAoB;AACnC,SAAQ,WAAW;AACpB;AAFgB;AAOT,SAAS,sBAAsB;AACrC,SAAO;AACR;AAFgB;;;ADnBT,IAAM,qBAAqB,oBAAE,OAClC,yBAAyB,CAAC,EAC1B,sBAAsB,GAAG,EACzB,qBAAqB,mBAAmB;AAEnC,IAAM,sBAAsB,oBAAE,OACnC,yBAAyB,CAAC,EAC1B,sBAAsB,IAAK,EAC3B,qBAAqB,mBAAmB;AAEnC,IAAM,uBAAuB,oBAAE,QAAQ;AAEvC,IAAM,sBAAsB,oBACjC,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,QAAQ;AACT,CAAC,EACA,qBAAqB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C;AAEA,UAAM,eAAe,eAAe,MAAM;AAE1C,QAAI,kBAAkB,MAAM;AAC3B,WAAK,mBAAoB,YAAY,IAAI;AACzC,aAAO;AAAA,IACR;AAEA,IAAAH,cAAa,aAAa;AAE1B,SAAK,mBAAoB,YAAY,IAAI;AACzC,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,qBAAqB,gBAAwC;AACnE,QAAI,mBAAmB,MAAM;AAC5B,cAAQ,IAAI,MAAM,sBAAsB,IAAI;AAC5C,aAAO;AAAA,IACR;AAEA,YAAQ,IAAI,MAAM,sBAAsB,CAAC,CAAC;AAE1C,eAAW,QAAQ,OAAO,QAAQ,cAAc;AAC/C,WAAK,oBAAoB,GAAI,IAAsC;AACpE,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,SAA4D;AAClE,IAAAI,4BAA2B,KAAK,MAAM,KAAK,IAAI;AAE/C,4BAAwB,KAAK,kBAAkB;AAE/C,WAAO,EAAE,GAAG,KAAK;AAAA,EAClB;AACD;AA5Ka;;;AClBN,SAAS,YAAY,MAAgB;AAC3C,UACE,KAAK,OAAO,UAAU,MACtB,KAAK,aAAa,UAAU,MAC5B,KAAK,QAAQ,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,KAAK,MACvF,KAAK,QAAQ,KAAK,UAAU,MAC5B,KAAK,QAAQ,KAAK,UAAU;AAE/B;AARgB;;;AzC6DT,IAAM,UAAU;","names":["Assertions_exports","Assertions_exports","import_shapeshift","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","Assertions_exports","placeholderValidator","import_shapeshift","import_v10","placeholderValidator","placeholderValidator","isEqual","Assertions_exports","validateRequiredParameters","import_shapeshift","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","import_shapeshift","import_v10","descriptionPredicate","validateRequiredParameters","import_ts_mixer","import_v10","import_ts_mixer","import_v10","validateRequiredParameters","import_v10","import_v10","import_shapeshift","import_v10","import_shapeshift","import_v10","import_ts_mixer","import_shapeshift","import_v10","booleanPredicate","import_v10","import_shapeshift","import_v10","import_ts_mixer","numberValidator","import_v10","import_shapeshift","import_v10","import_ts_mixer","minLengthValidator","maxLengthValidator","import_v10","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","import_shapeshift","import_v10","namePredicate","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.mjs b/node_modules/@discordjs/builders/dist/index.mjs index 6741e4e..2f32e8d 100644 --- a/node_modules/@discordjs/builders/dist/index.mjs +++ b/node_modules/@discordjs/builders/dist/index.mjs @@ -41,9 +41,18 @@ import { s } from "@sapphire/shapeshift"; // src/util/validation.ts var validate = true; -var enableValidators = /* @__PURE__ */ __name(() => validate = true, "enableValidators"); -var disableValidators = /* @__PURE__ */ __name(() => validate = false, "disableValidators"); -var isValidationEnabled = /* @__PURE__ */ __name(() => validate, "isValidationEnabled"); +function enableValidators() { + return validate = true; +} +__name(enableValidators, "enableValidators"); +function disableValidators() { + return validate = false; +} +__name(disableValidators, "disableValidators"); +function isValidationEnabled() { + return validate; +} +__name(isValidationEnabled, "isValidationEnabled"); // src/messages/embed/Assertions.ts var fieldNamePredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(256).setValidationEnabled(isValidationEnabled); @@ -93,22 +102,83 @@ __name(normalizeArray, "normalizeArray"); // src/messages/embed/Embed.ts var EmbedBuilder = class { + /** + * The API data associated with this embed. + */ data; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ constructor(data = {}) { this.data = { ...data }; if (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString(); } + /** + * Appends fields to the embed. + * + * @remarks + * This method accepts either an array of fields or a variable number of field parameters. + * The maximum amount of fields that can be added is 25. + * @example + * Using an array: + * ```ts + * const fields: APIEmbedField[] = ...; + * const embed = new EmbedBuilder() + * .addFields(fields); + * ``` + * @example + * Using rest parameters (variadic): + * ```ts + * const embed = new EmbedBuilder() + * .addFields( + * { name: 'Field 1', value: 'Value 1' }, + * { name: 'Field 2', value: 'Value 2' }, + * ); + * ``` + * @param fields - The fields to add + */ addFields(...fields) { - fields = normalizeArray(fields); - validateFieldLength(fields.length, this.data.fields); - embedFieldsArrayPredicate.parse(fields); + const normalizedFields = normalizeArray(fields); + validateFieldLength(normalizedFields.length, this.data.fields); + embedFieldsArrayPredicate.parse(normalizedFields); if (this.data.fields) - this.data.fields.push(...fields); + this.data.fields.push(...normalizedFields); else - this.data.fields = fields; + this.data.fields = normalizedFields; return this; } + /** + * Removes, replaces, or inserts fields for this embed. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. + * The maximum amount of fields that can be added is 25. + * + * It's useful for modifying and adjusting order of the already-existing fields of an embed. + * @example + * Remove the first field: + * ```ts + * embed.spliceFields(0, 1); + * ``` + * @example + * Remove the first n fields: + * ```ts + * const n = 4; + * embed.spliceFields(0, n); + * ``` + * @example + * Remove the last field: + * ```ts + * embed.spliceFields(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of fields to remove + * @param fields - The replacing field objects + */ spliceFields(index, deleteCount, ...fields) { validateFieldLength(fields.length - deleteCount, this.data.fields); embedFieldsArrayPredicate.parse(fields); @@ -118,10 +188,25 @@ var EmbedBuilder = class { this.data.fields = fields; return this; } + /** + * Sets the fields for this embed. + * + * @remarks + * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, + * it splices the entire array of fields, replacing them with the provided fields. + * + * You can set a maximum of 25 fields. + * @param fields - The fields to set + */ setFields(...fields) { this.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields)); return this; } + /** + * Sets the author of this embed. + * + * @param options - The options to use + */ setAuthor(options) { if (options === null) { this.data.author = void 0; @@ -131,6 +216,11 @@ var EmbedBuilder = class { this.data.author = { name: options.name, url: options.url, icon_url: options.iconURL }; return this; } + /** + * Sets the color of this embed. + * + * @param color - The color to use + */ setColor(color) { colorPredicate.parse(color); if (Array.isArray(color)) { @@ -141,11 +231,21 @@ var EmbedBuilder = class { this.data.color = color ?? void 0; return this; } + /** + * Sets the description of this embed. + * + * @param description - The description to use + */ setDescription(description) { descriptionPredicate.parse(description); this.data.description = description ?? void 0; return this; } + /** + * Sets the footer of this embed. + * + * @param options - The footer to use + */ setFooter(options) { if (options === null) { this.data.footer = void 0; @@ -155,142 +255,71 @@ var EmbedBuilder = class { this.data.footer = { text: options.text, icon_url: options.iconURL }; return this; } + /** + * Sets the image of this embed. + * + * @param url - The image URL to use + */ setImage(url) { imageURLPredicate.parse(url); this.data.image = url ? { url } : void 0; return this; } + /** + * Sets the thumbnail of this embed. + * + * @param url - The thumbnail URL to use + */ setThumbnail(url) { imageURLPredicate.parse(url); this.data.thumbnail = url ? { url } : void 0; return this; } + /** + * Sets the timestamp of this embed. + * + * @param timestamp - The timestamp or date to use + */ setTimestamp(timestamp = Date.now()) { timestampPredicate.parse(timestamp); this.data.timestamp = timestamp ? new Date(timestamp).toISOString() : void 0; return this; } + /** + * Sets the title for this embed. + * + * @param title - The title to use + */ setTitle(title) { titlePredicate.parse(title); this.data.title = title ?? void 0; return this; } + /** + * Sets the URL of this embed. + * + * @param url - The URL to use + */ setURL(url) { urlPredicate.parse(url); this.data.url = url ?? void 0; return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { return { ...this.data }; } }; __name(EmbedBuilder, "EmbedBuilder"); -// src/messages/formatters.ts -function codeBlock(language, content) { - return typeof content === "undefined" ? `\`\`\` -${language} -\`\`\`` : `\`\`\`${language} -${content} -\`\`\``; -} -__name(codeBlock, "codeBlock"); -function inlineCode(content) { - return `\`${content}\``; -} -__name(inlineCode, "inlineCode"); -function italic(content) { - return `_${content}_`; -} -__name(italic, "italic"); -function bold(content) { - return `**${content}**`; -} -__name(bold, "bold"); -function underscore(content) { - return `__${content}__`; -} -__name(underscore, "underscore"); -function strikethrough(content) { - return `~~${content}~~`; -} -__name(strikethrough, "strikethrough"); -function quote(content) { - return `> ${content}`; -} -__name(quote, "quote"); -function blockQuote(content) { - return `>>> ${content}`; -} -__name(blockQuote, "blockQuote"); -function hideLinkEmbed(url) { - return `<${url}>`; -} -__name(hideLinkEmbed, "hideLinkEmbed"); -function hyperlink(content, url, title) { - return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`; -} -__name(hyperlink, "hyperlink"); -function spoiler(content) { - return `||${content}||`; -} -__name(spoiler, "spoiler"); -function userMention(userId) { - return `<@${userId}>`; -} -__name(userMention, "userMention"); -function channelMention(channelId) { - return `<#${channelId}>`; -} -__name(channelMention, "channelMention"); -function roleMention(roleId) { - return `<@&${roleId}>`; -} -__name(roleMention, "roleMention"); -function chatInputApplicationCommandMention(commandName, subcommandGroupName, subcommandName, commandId) { - if (typeof commandId !== "undefined") { - return ``; - } - if (typeof subcommandName !== "undefined") { - return ``; - } - return ``; -} -__name(chatInputApplicationCommandMention, "chatInputApplicationCommandMention"); -function formatEmoji(emojiId, animated = false) { - return `<${animated ? "a" : ""}:_:${emojiId}>`; -} -__name(formatEmoji, "formatEmoji"); -function channelLink(channelId, guildId) { - return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}`; -} -__name(channelLink, "channelLink"); -function messageLink(channelId, messageId, guildId) { - return `${typeof guildId === "undefined" ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`; -} -__name(messageLink, "messageLink"); -function time(timeOrSeconds, style) { - if (typeof timeOrSeconds !== "number") { - timeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1e3); - } - return typeof style === "string" ? `` : ``; -} -__name(time, "time"); -var TimestampStyles = { - ShortTime: "t", - LongTime: "T", - ShortDate: "d", - LongDate: "D", - ShortDateTime: "f", - LongDateTime: "F", - RelativeTime: "R" -}; -var Faces = /* @__PURE__ */ ((Faces2) => { - Faces2["Shrug"] = "\xAF\\_(\u30C4)\\_/\xAF"; - Faces2["Tableflip"] = "(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B"; - Faces2["Unflip"] = "\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)"; - return Faces2; -})(Faces || {}); +// src/index.ts +export * from "@discordjs/formatters"; // src/components/Assertions.ts var Assertions_exports2 = {}; @@ -319,29 +348,79 @@ import { ButtonStyle, ChannelType } from "discord-api-types/v10"; // src/components/selectMenu/StringSelectMenuOption.ts var StringSelectMenuOptionBuilder = class { + /** + * Creates a new string select menu option from API data. + * + * @param data - The API data to create this string select menu option with + * @example + * Creating a string select menu option from an API data object: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * label: 'catchy label', + * value: '1', + * }); + * ``` + * @example + * Creating a string select menu option using setters and API data: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * default: true, + * value: '1', + * }) + * .setLabel('woah'); + * ``` + */ constructor(data = {}) { this.data = data; } + /** + * Sets the label for this option. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = labelValueDescriptionValidator.parse(label); return this; } + /** + * Sets the value for this option. + * + * @param value - The value to use + */ setValue(value) { this.data.value = labelValueDescriptionValidator.parse(value); return this; } + /** + * Sets the description for this option. + * + * @param description - The description to use + */ setDescription(description) { this.data.description = labelValueDescriptionValidator.parse(description); return this; } + /** + * Sets whether this option is selected by default. + * + * @param isDefault - Whether this option is selected by default + */ setDefault(isDefault = true) { this.data.default = defaultValidator.parse(isDefault); return this; } + /** + * Sets the emoji to display for this option. + * + * @param emoji - The emoji to use + */ setEmoji(emoji) { this.data.emoji = emojiValidator.parse(emoji); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value); return { @@ -413,7 +492,15 @@ import { // src/components/Component.ts var ComponentBuilder = class { + /** + * The API data associated with this component. + */ data; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ constructor(data) { this.data = data; } @@ -428,33 +515,99 @@ import { ComponentType } from "discord-api-types/v10"; var ButtonBuilder = class extends ComponentBuilder { + /** + * Creates a new button from API data. + * + * @param data - The API data to create this button with + * @example + * Creating a button from an API data object: + * ```ts + * const button = new ButtonBuilder({ + * custom_id: 'a cool button', + * style: ButtonStyle.Primary, + * label: 'Click Me', + * emoji: { + * name: 'smile', + * id: '123456789012345678', + * }, + * }); + * ``` + * @example + * Creating a button using setters and API data: + * ```ts + * const button = new ButtonBuilder({ + * style: ButtonStyle.Secondary, + * label: 'Click Me', + * }) + * .setEmoji({ name: '🙂' }) + * .setCustomId('another cool button'); + * ``` + */ constructor(data) { super({ type: ComponentType.Button, ...data }); } + /** + * Sets the style of this button. + * + * @param style - The style to use + */ setStyle(style) { this.data.style = buttonStyleValidator.parse(style); return this; } + /** + * Sets the URL for this button. + * + * @remarks + * This method is only available to buttons using the `Link` button style. + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use + */ setURL(url) { this.data.url = urlValidator.parse(url); return this; } + /** + * Sets the custom id for this button. + * + * @remarks + * This method is only applicable to buttons that are not using the `Link` button style. + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets the emoji to display on this button. + * + * @param emoji - The emoji to use + */ setEmoji(emoji) { this.data.emoji = emojiValidator.parse(emoji); return this; } + /** + * Sets whether this button is disabled. + * + * @param disabled - Whether to disable this button + */ setDisabled(disabled = true) { this.data.disabled = disabledValidator.parse(disabled); return this; } + /** + * Sets the label for this button. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = buttonLabelValidator.parse(label); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredButtonParameters( this.data.style, @@ -475,26 +628,54 @@ import { ComponentType as ComponentType2 } from "discord-api-types/v10"; // src/components/selectMenu/BaseSelectMenu.ts var BaseSelectMenuBuilder = class extends ComponentBuilder { + /** + * Sets the placeholder for this select menu. + * + * @param placeholder - The placeholder to use + */ setPlaceholder(placeholder) { this.data.placeholder = placeholderValidator.parse(placeholder); return this; } + /** + * Sets the minimum values that must be selected in the select menu. + * + * @param minValues - The minimum values that must be selected + */ setMinValues(minValues) { this.data.min_values = minMaxValidator.parse(minValues); return this; } + /** + * Sets the maximum values that must be selected in the select menu. + * + * @param maxValues - The maximum values that must be selected + */ setMaxValues(maxValues) { this.data.max_values = minMaxValidator.parse(maxValues); return this; } + /** + * Sets the custom id for this select menu. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets whether this select menu is disabled. + * + * @param disabled - Whether this select menu is disabled + */ setDisabled(disabled = true) { this.data.disabled = disabledValidator.parse(disabled); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { customIdValidator.parse(this.data.custom_id); return { @@ -506,21 +687,57 @@ __name(BaseSelectMenuBuilder, "BaseSelectMenuBuilder"); // src/components/selectMenu/ChannelSelectMenu.ts var ChannelSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement) + * .setMinValues(2); + * ``` + */ constructor(data) { super({ ...data, type: ComponentType2.ChannelSelect }); } + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ addChannelTypes(...types) { - types = normalizeArray(types); + const normalizedTypes = normalizeArray(types); this.data.channel_types ??= []; - this.data.channel_types.push(...channelTypesValidator.parse(types)); + this.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes)); return this; } + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ setChannelTypes(...types) { - types = normalizeArray(types); + const normalizedTypes = normalizeArray(types); this.data.channel_types ??= []; - this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types)); + this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes)); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { customIdValidator.parse(this.data.custom_id); return { @@ -533,6 +750,28 @@ __name(ChannelSelectMenuBuilder, "ChannelSelectMenuBuilder"); // src/components/selectMenu/MentionableSelectMenu.ts import { ComponentType as ComponentType3 } from "discord-api-types/v10"; var MentionableSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: ComponentType3.MentionableSelect }); } @@ -542,6 +781,28 @@ __name(MentionableSelectMenuBuilder, "MentionableSelectMenuBuilder"); // src/components/selectMenu/RoleSelectMenu.ts import { ComponentType as ComponentType4 } from "discord-api-types/v10"; var RoleSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: ComponentType4.RoleSelect }); } @@ -551,34 +812,113 @@ __name(RoleSelectMenuBuilder, "RoleSelectMenuBuilder"); // src/components/selectMenu/StringSelectMenu.ts import { ComponentType as ComponentType5 } from "discord-api-types/v10"; var StringSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * The options within this select menu. + */ options; + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * options: [ + * { label: 'option 1', value: '1' }, + * { label: 'option 2', value: '2' }, + * { label: 'option 3', value: '3' }, + * ], + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1) + * .addOptions({ + * label: 'Catchy', + * value: 'catch', + * }); + * ``` + */ constructor(data) { const { options, ...initData } = data ?? {}; super({ ...initData, type: ComponentType5.StringSelect }); this.options = options?.map((option) => new StringSelectMenuOptionBuilder(option)) ?? []; } + /** + * Adds options to this select menu. + * + * @param options - The options to add + */ addOptions(...options) { - options = normalizeArray(options); - optionsLengthValidator.parse(this.options.length + options.length); + const normalizedOptions = normalizeArray(options); + optionsLengthValidator.parse(this.options.length + normalizedOptions.length); this.options.push( - ...options.map( - (option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)) + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) ) ); return this; } + /** + * Sets the options for this select menu. + * + * @param options - The options to set + */ setOptions(...options) { - options = normalizeArray(options); - optionsLengthValidator.parse(options.length); - this.options.splice( - 0, - this.options.length, - ...options.map( - (option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)) + return this.spliceOptions(0, this.options.length, ...options); + } + /** + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index, deleteCount, ...options) { + const normalizedOptions = normalizeArray(options); + const clone = [...this.options]; + clone.splice( + index, + deleteCount, + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) ) ); + optionsLengthValidator.parse(clone.length); + this.options.splice(0, this.options.length, ...clone); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { validateRequiredSelectMenuParameters(this.options, this.data.custom_id); return { @@ -592,6 +932,28 @@ __name(StringSelectMenuBuilder, "StringSelectMenuBuilder"); // src/components/selectMenu/UserSelectMenu.ts import { ComponentType as ComponentType6 } from "discord-api-types/v10"; var UserSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: ComponentType6.UserSelect }); } @@ -633,47 +995,116 @@ __name(validateRequiredParameters, "validateRequiredParameters"); // src/components/textInput/TextInput.ts var TextInputBuilder = class extends ComponentBuilder { + /** + * Creates a new text input from API data. + * + * @param data - The API data to create this text input with + * @example + * Creating a select menu option from an API data object: + * ```ts + * const textInput = new TextInputBuilder({ + * custom_id: 'a cool select menu', + * label: 'Type something', + * style: TextInputStyle.Short, + * }); + * ``` + * @example + * Creating a select menu option using setters and API data: + * ```ts + * const textInput = new TextInputBuilder({ + * label: 'Type something else', + * }) + * .setCustomId('woah') + * .setStyle(TextInputStyle.Paragraph); + * ``` + */ constructor(data) { super({ type: ComponentType7.TextInput, ...data }); } + /** + * Sets the custom id for this text input. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets the label for this text input. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = labelValidator.parse(label); return this; } + /** + * Sets the style for this text input. + * + * @param style - The style to use + */ setStyle(style) { this.data.style = textInputStyleValidator.parse(style); return this; } + /** + * Sets the minimum length of text for this text input. + * + * @param minLength - The minimum length of text for this text input + */ setMinLength(minLength) { this.data.min_length = minLengthValidator.parse(minLength); return this; } + /** + * Sets the maximum length of text for this text input. + * + * @param maxLength - The maximum length of text for this text input + */ setMaxLength(maxLength) { this.data.max_length = maxLengthValidator.parse(maxLength); return this; } + /** + * Sets the placeholder for this text input. + * + * @param placeholder - The placeholder to use + */ setPlaceholder(placeholder) { this.data.placeholder = placeholderValidator2.parse(placeholder); return this; } + /** + * Sets the value for this text input. + * + * @param value - The value to use + */ setValue(value) { this.data.value = valueValidator.parse(value); return this; } + /** + * Sets whether this text input is required. + * + * @param required - Whether this text input is required + */ setRequired(required = true) { this.data.required = requiredValidator.parse(required); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label); return { ...this.data }; } + /** + * {@inheritDoc Equatable.equals} + */ equals(other) { if (isJSONEncodable(other)) { return isEqual(other.toJSON(), this.data); @@ -713,19 +1144,69 @@ __name(createComponentBuilder, "createComponentBuilder"); // src/components/ActionRow.ts var ActionRowBuilder = class extends ComponentBuilder { + /** + * The components within this action row. + */ components; + /** + * Creates a new action row from API data. + * + * @param data - The API data to create this action row with + * @example + * Creating an action row from an API data object: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Type something", + * style: TextInputStyle.Short, + * type: ComponentType.TextInput, + * }, + * ], + * }); + * ``` + * @example + * Creating an action row using setters and API data: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Click me", + * style: ButtonStyle.Primary, + * type: ComponentType.Button, + * }, + * ], + * }) + * .addComponents(button2, button3); + * ``` + */ constructor({ components, ...data } = {}) { super({ type: ComponentType9.ActionRow, ...data }); this.components = components?.map((component) => createComponentBuilder(component)) ?? []; } + /** + * Adds components to this action row. + * + * @param components - The components to add + */ addComponents(...components) { this.components.push(...normalizeArray(components)); return this; } + /** + * Sets components for this action row. + * + * @param components - The components to set + */ setComponents(...components) { this.components.splice(0, this.components.length, ...normalizeArray(components)); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { return { ...this.data, @@ -754,20 +1235,46 @@ __name(validateRequiredParameters2, "validateRequiredParameters"); // src/interactions/modals/Modal.ts var ModalBuilder = class { + /** + * The API data associated with this modal. + */ data; + /** + * The components within this modal. + */ components = []; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ constructor({ components, ...data } = {}) { this.data = { ...data }; this.components = components?.map((component) => createComponentBuilder(component)) ?? []; } + /** + * Sets the title of this modal. + * + * @param title - The title to use + */ setTitle(title) { this.data.title = titleValidator.parse(title); return this; } + /** + * Sets the custom id of this modal. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Adds components to this modal. + * + * @param components - The components to add + */ addComponents(...components) { this.components.push( ...normalizeArray(components).map( @@ -776,10 +1283,18 @@ var ModalBuilder = class { ); return this; } + /** + * Sets components for this modal. + * + * @param components - The components to set + */ setComponents(...components) { this.components.splice(0, this.components.length, ...normalizeArray(components)); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredParameters2(this.data.custom_id, this.data.title, this.components); return { @@ -803,6 +1318,7 @@ __export(Assertions_exports5, { validateLocale: () => validateLocale, validateLocalizationMap: () => validateLocalizationMap, validateMaxOptionsLength: () => validateMaxOptionsLength, + validateNSFW: () => validateNSFW, validateName: () => validateName, validateRequired: () => validateRequired, validateRequiredParameters: () => validateRequiredParameters3 @@ -872,6 +1388,10 @@ function validateDefaultMemberPermissions(permissions) { return memberPermissionPredicate.parse(permissions); } __name(validateDefaultMemberPermissions, "validateDefaultMemberPermissions"); +function validateNSFW(value) { + booleanPredicate.parse(value); +} +__name(validateNSFW, "validateNSFW"); // src/interactions/slashCommands/SlashCommandBuilder.ts import { mix as mix6 } from "ts-mixer"; @@ -884,20 +1404,48 @@ import { mix as mix5 } from "ts-mixer"; // src/interactions/slashCommands/mixins/NameAndDescription.ts var SharedNameAndDescription = class { + /** + * The name of this command. + */ name; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The description of this command. + */ description; + /** + * The description localizations of this command. + */ description_localizations; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ setName(name) { validateName(name); Reflect.set(this, "name", name); return this; } + /** + * Sets the description of this command. + * + * @param description - The description to use + */ setDescription(description) { validateDescription(description); Reflect.set(this, "description", description); return this; } + /** + * SSets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ setNameLocalization(locale, localizedName) { if (!this.name_localizations) { Reflect.set(this, "name_localizations", {}); @@ -911,6 +1459,11 @@ var SharedNameAndDescription = class { this.name_localizations[parsedLocale] = localizedName; return this; } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ setNameLocalizations(localizedNames) { if (localizedNames === null) { Reflect.set(this, "name_localizations", null); @@ -922,6 +1475,12 @@ var SharedNameAndDescription = class { } return this; } + /** + * Sets a description localization for this command. + * + * @param locale - The locale to set + * @param localizedDescription - The localized description for the given locale + */ setDescriptionLocalization(locale, localizedDescription) { if (!this.description_localizations) { Reflect.set(this, "description_localizations", {}); @@ -935,6 +1494,11 @@ var SharedNameAndDescription = class { this.description_localizations[parsedLocale] = localizedDescription; return this; } + /** + * Sets the description localizations for this command. + * + * @param localizedDescriptions - The object of localized descriptions to set + */ setDescriptionLocalizations(localizedDescriptions) { if (localizedDescriptions === null) { Reflect.set(this, "description_localizations", null); @@ -954,12 +1518,25 @@ import { ApplicationCommandOptionType } from "discord-api-types/v10"; // src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts var ApplicationCommandOptionBase = class extends SharedNameAndDescription { + /** + * Whether this option is required. + * + * @defaultValue `false` + */ required = false; + /** + * Sets whether this option is required. + * + * @param required - Whether this option should be required + */ setRequired(required) { validateRequired(required); Reflect.set(this, "required", required); return this; } + /** + * This method runs required validators on this builder. + */ runRequiredValidations() { validateRequiredParameters3(this.name, this.description, []); validateLocalizationMap(this.name_localizations); @@ -971,7 +1548,13 @@ __name(ApplicationCommandOptionBase, "ApplicationCommandOptionBase"); // src/interactions/slashCommands/options/attachment.ts var SlashCommandAttachmentOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -982,7 +1565,13 @@ __name(SlashCommandAttachmentOption, "SlashCommandAttachmentOption"); // src/interactions/slashCommands/options/boolean.ts import { ApplicationCommandOptionType as ApplicationCommandOptionType2 } from "discord-api-types/v10"; var SlashCommandBooleanOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType2.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1010,7 +1599,15 @@ var allowedChannelTypes = [ ]; var channelTypesPredicate = s6.array(s6.union(...allowedChannelTypes.map((type) => s6.literal(type)))); var ApplicationCommandOptionChannelTypesMixin = class { + /** + * The channel types of this option. + */ channel_types; + /** + * Adds channel types to this option. + * + * @param channelTypes - The channel types + */ addChannelTypes(...channelTypes) { if (this.channel_types === void 0) { Reflect.set(this, "channel_types", []); @@ -1023,7 +1620,13 @@ __name(ApplicationCommandOptionChannelTypesMixin, "ApplicationCommandOptionChann // src/interactions/slashCommands/options/channel.ts var SlashCommandChannelOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType3.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1041,7 +1644,13 @@ import { mix as mix2 } from "ts-mixer"; // src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts var ApplicationCommandNumericOptionMinMaxValueMixin = class { + /** + * The maximum value of this option. + */ max_value; + /** + * The minimum value of this option. + */ min_value; }; __name(ApplicationCommandNumericOptionMinMaxValueMixin, "ApplicationCommandNumericOptionMinMaxValueMixin"); @@ -1058,9 +1667,25 @@ var choicesPredicate = s7.object({ }).array; var booleanPredicate2 = s7.boolean; var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { + /** + * The choices of this option. + */ choices; + /** + * Whether this option utilizes autocomplete. + */ autocomplete; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ type; + /** + * Adds multiple choices to this option. + * + * @param choices - The choices to add + */ addChoices(...choices) { if (choices.length > 0 && this.autocomplete) { throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); @@ -1080,6 +1705,11 @@ var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { } return this; } + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ setChoices(...choices) { if (choices.length > 0 && this.autocomplete) { throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); @@ -1089,6 +1719,11 @@ var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { this.addChoices(...choices); return this; } + /** + * Whether this option uses autocomplete. + * + * @param autocomplete - Whether this option should use autocomplete + */ setAutocomplete(autocomplete) { booleanPredicate2.parse(autocomplete); if (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1103,17 +1738,29 @@ __name(ApplicationCommandOptionWithChoicesAndAutocompleteMixin, "ApplicationComm // src/interactions/slashCommands/options/integer.ts var numberValidator = s8.number.int; var SlashCommandIntegerOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType5.Integer; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ setMaxValue(max) { numberValidator.parse(max); Reflect.set(this, "max_value", max); return this; } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ setMinValue(min) { numberValidator.parse(min); Reflect.set(this, "min_value", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1130,7 +1777,13 @@ SlashCommandIntegerOption = __decorateClass([ // src/interactions/slashCommands/options/mentionable.ts import { ApplicationCommandOptionType as ApplicationCommandOptionType6 } from "discord-api-types/v10"; var SlashCommandMentionableOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType6.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1144,17 +1797,29 @@ import { ApplicationCommandOptionType as ApplicationCommandOptionType7 } from "d import { mix as mix3 } from "ts-mixer"; var numberValidator2 = s9.number; var SlashCommandNumberOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType7.Number; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ setMaxValue(max) { numberValidator2.parse(max); Reflect.set(this, "max_value", max); return this; } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ setMinValue(min) { numberValidator2.parse(min); Reflect.set(this, "min_value", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1171,7 +1836,13 @@ SlashCommandNumberOption = __decorateClass([ // src/interactions/slashCommands/options/role.ts import { ApplicationCommandOptionType as ApplicationCommandOptionType8 } from "discord-api-types/v10"; var SlashCommandRoleOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType8.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1186,19 +1857,41 @@ import { mix as mix4 } from "ts-mixer"; var minLengthValidator2 = s10.number.greaterThanOrEqual(0).lessThanOrEqual(6e3); var maxLengthValidator2 = s10.number.greaterThanOrEqual(1).lessThanOrEqual(6e3); var SlashCommandStringOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType9.String; + /** + * The maximum length of this option. + */ max_length; + /** + * The minimum length of this option. + */ min_length; + /** + * Sets the maximum length of this string option. + * + * @param max - The maximum length this option can be + */ setMaxLength(max) { maxLengthValidator2.parse(max); Reflect.set(this, "max_length", max); return this; } + /** + * Sets the minimum length of this string option. + * + * @param min - The minimum length this option can be + */ setMinLength(min) { minLengthValidator2.parse(min); Reflect.set(this, "min_length", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1215,7 +1908,13 @@ SlashCommandStringOption = __decorateClass([ // src/interactions/slashCommands/options/user.ts import { ApplicationCommandOptionType as ApplicationCommandOptionType10 } from "discord-api-types/v10"; var SlashCommandUserOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType10.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1226,33 +1925,85 @@ __name(SlashCommandUserOption, "SlashCommandUserOption"); // src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts var SharedSlashCommandOptions = class { options; + /** + * Adds a boolean option. + * + * @param input - A function that returns an option builder or an already built builder + */ addBooleanOption(input) { return this._sharedAddOptionMethod(input, SlashCommandBooleanOption); } + /** + * Adds a user option. + * + * @param input - A function that returns an option builder or an already built builder + */ addUserOption(input) { return this._sharedAddOptionMethod(input, SlashCommandUserOption); } + /** + * Adds a channel option. + * + * @param input - A function that returns an option builder or an already built builder + */ addChannelOption(input) { return this._sharedAddOptionMethod(input, SlashCommandChannelOption); } + /** + * Adds a role option. + * + * @param input - A function that returns an option builder or an already built builder + */ addRoleOption(input) { return this._sharedAddOptionMethod(input, SlashCommandRoleOption); } + /** + * Adds an attachment option. + * + * @param input - A function that returns an option builder or an already built builder + */ addAttachmentOption(input) { return this._sharedAddOptionMethod(input, SlashCommandAttachmentOption); } + /** + * Adds a mentionable option. + * + * @param input - A function that returns an option builder or an already built builder + */ addMentionableOption(input) { return this._sharedAddOptionMethod(input, SlashCommandMentionableOption); } + /** + * Adds a string option. + * + * @param input - A function that returns an option builder or an already built builder + */ addStringOption(input) { return this._sharedAddOptionMethod(input, SlashCommandStringOption); } + /** + * Adds an integer option. + * + * @param input - A function that returns an option builder or an already built builder + */ addIntegerOption(input) { return this._sharedAddOptionMethod(input, SlashCommandIntegerOption); } + /** + * Adds a number option. + * + * @param input - A function that returns an option builder or an already built builder + */ addNumberOption(input) { return this._sharedAddOptionMethod(input, SlashCommandNumberOption); } + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ _sharedAddOptionMethod(input, Instance) { const { options } = this; validateMaxOptionsLength(options); @@ -1266,9 +2017,23 @@ __name(SharedSlashCommandOptions, "SharedSlashCommandOptions"); // src/interactions/slashCommands/SlashCommandSubcommands.ts var SlashCommandSubcommandGroupBuilder = class { + /** + * The name of this subcommand group. + */ name = void 0; + /** + * The description of this subcommand group. + */ description = void 0; + /** + * The subcommands within this subcommand group. + */ options = []; + /** + * Adds a new subcommand to this group. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ addSubcommand(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1277,6 +2042,13 @@ var SlashCommandSubcommandGroupBuilder = class { options.push(result); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters3(this.name, this.description, this.options); return { @@ -1294,9 +2066,25 @@ SlashCommandSubcommandGroupBuilder = __decorateClass([ mix5(SharedNameAndDescription) ], SlashCommandSubcommandGroupBuilder); var SlashCommandSubcommandBuilder = class { + /** + * The name of this subcommand. + */ name = void 0; + /** + * The description of this subcommand. + */ description = void 0; + /** + * The options within this subcommand. + */ options = []; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters3(this.name, this.description, this.options); return { @@ -1316,38 +2104,102 @@ SlashCommandSubcommandBuilder = __decorateClass([ // src/interactions/slashCommands/SlashCommandBuilder.ts var SlashCommandBuilder = class { + /** + * The name of this command. + */ name = void 0; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The description of this command. + */ description = void 0; + /** + * The description localizations of this command. + */ description_localizations; + /** + * The options of this command. + */ options = []; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ dm_permission = void 0; - toJSON() { - validateRequiredParameters3(this.name, this.description, this.options); - validateLocalizationMap(this.name_localizations); - validateLocalizationMap(this.description_localizations); - return { - ...this, - options: this.options.map((option) => option.toJSON()) - }; - } + /** + * Whether this command is NSFW. + */ + nsfw = void 0; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether or not to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. + */ setDefaultPermission(value) { validateDefaultPermission(value); Reflect.set(this, "default_permission", value); return this; } + /** + * Sets the default permissions a member should have in order to run the command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDefaultMemberPermissions(permissions) { const permissionValue = validateDefaultMemberPermissions(permissions); Reflect.set(this, "default_member_permissions", permissionValue); return this; } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDMPermission(enabled) { validateDMPermission(enabled); Reflect.set(this, "dm_permission", enabled); return this; } + /** + * Sets whether this command is NSFW. + * + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw = true) { + validateNSFW(nsfw); + Reflect.set(this, "nsfw", nsfw); + return this; + } + /** + * Adds a new subcommand group to this command. + * + * @param input - A function that returns a subcommand group builder or an already built builder + */ addSubcommandGroup(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1356,6 +2208,11 @@ var SlashCommandBuilder = class { options.push(result); return this; } + /** + * Adds a new subcommand to this command. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ addSubcommand(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1364,6 +2221,22 @@ var SlashCommandBuilder = class { options.push(result); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + return { + ...this, + options: this.options.map((option) => option.toJSON()) + }; + } }; __name(SlashCommandBuilder, "SlashCommandBuilder"); SlashCommandBuilder = __decorateClass([ @@ -1419,37 +2292,101 @@ __name(validateDefaultMemberPermissions2, "validateDefaultMemberPermissions"); // src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts var ContextMenuCommandBuilder = class { + /** + * The name of this command. + */ name = void 0; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The type of this command. + */ type = void 0; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ dm_permission = void 0; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ setName(name) { validateName2(name); Reflect.set(this, "name", name); return this; } + /** + * Sets the type of this command. + * + * @param type - The type to use + */ setType(type) { validateType(type); Reflect.set(this, "type", type); return this; } + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ setDefaultPermission(value) { validateDefaultPermission2(value); Reflect.set(this, "default_permission", value); return this; } + /** + * Sets the default permissions a member should have in order to run this command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDefaultMemberPermissions(permissions) { const permissionValue = validateDefaultMemberPermissions2(permissions); Reflect.set(this, "default_member_permissions", permissionValue); return this; } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDMPermission(enabled) { validateDMPermission2(enabled); Reflect.set(this, "dm_permission", enabled); return this; } + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ setNameLocalization(locale, localizedName) { if (!this.name_localizations) { Reflect.set(this, "name_localizations", {}); @@ -1463,6 +2400,11 @@ var ContextMenuCommandBuilder = class { this.name_localizations[parsedLocale] = localizedName; return this; } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ setNameLocalizations(localizedNames) { if (localizedNames === null) { Reflect.set(this, "name_localizations", null); @@ -1473,6 +2415,13 @@ var ContextMenuCommandBuilder = class { this.setNameLocalization(...args); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters4(this.name, this.type); validateLocalizationMap(this.name_localizations); @@ -1488,8 +2437,7 @@ function embedLength(data) { __name(embedLength, "embedLength"); // src/index.ts -export * from "@discordjs/util"; -var version = "1.4.0"; +var version = "1.6.3"; export { ActionRowBuilder, ApplicationCommandNumericOptionMinMaxValueMixin, @@ -1505,7 +2453,6 @@ export { ContextMenuCommandBuilder, Assertions_exports as EmbedAssertions, EmbedBuilder, - Faces, MentionableSelectMenuBuilder, Assertions_exports4 as ModalAssertions, ModalBuilder, @@ -1531,33 +2478,13 @@ export { StringSelectMenuOptionBuilder, Assertions_exports3 as TextInputAssertions, TextInputBuilder, - TimestampStyles, UserSelectMenuBuilder, - blockQuote, - bold, - channelLink, - channelMention, - chatInputApplicationCommandMention, - codeBlock, createComponentBuilder, disableValidators, embedLength, enableValidators, - formatEmoji, - hideLinkEmbed, - hyperlink, - inlineCode, isValidationEnabled, - italic, - messageLink, normalizeArray, - quote, - roleMention, - spoiler, - strikethrough, - time, - underscore, - userMention, version }; //# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.mjs.map b/node_modules/@discordjs/builders/dist/index.mjs.map index 49ec254..38013f8 100644 --- a/node_modules/@discordjs/builders/dist/index.mjs.map +++ b/node_modules/@discordjs/builders/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/messages/formatters.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts","../src/index.ts"],"sourcesContent":["import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\nexport const enableValidators = () => (validate = true);\nexport const disableValidators = () => (validate = false);\nexport const isValidationEnabled = () => validate;\n","export function normalizeArray(arr: RestOrArray): T[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as T[];\n}\n\nexport type RestOrArray = T[] | [T[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\nexport type RGBTuple = [red: number, green: number, blue: number];\n\nexport interface IconData {\n\t/**\n\t * The URL of the icon\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon\n\t */\n\tproxyIconURL?: string;\n}\n\nexport type EmbedAuthorData = IconData & Omit;\n\nexport type EmbedAuthorOptions = Omit;\n\nexport type EmbedFooterData = IconData & Omit;\n\nexport type EmbedFooterOptions = Omit;\n\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image\n\t */\n\tproxyURL?: string;\n}\n/**\n * Represents a embed in a message (image/video preview, rich embed, etc.)\n */\nexport class EmbedBuilder {\n\tpublic readonly data: APIEmbed;\n\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic)\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\tfields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\n\t\tif (this.data.fields) this.data.fields.push(...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields in the embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields\n\t * ```ts\n\t * const n = 4\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the embed's fields\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed\n\t *\n\t * @param options - The options for the author\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed\n\t *\n\t * @param color - The color of the embed\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed\n\t *\n\t * @param description - The description\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed\n\t *\n\t * @param options - The options for the footer\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed\n\t *\n\t * @param url - The URL of the image\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed\n\t *\n\t * @param url - The URL of the thumbnail\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed\n\t *\n\t * @param timestamp - The timestamp or date\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title of this embed\n\t *\n\t * @param title - The title\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed\n\t *\n\t * @param url - The URL\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Transforms the embed to a plain object\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","import type { URL } from 'node:url';\nimport type { Snowflake } from 'discord-api-types/globals';\n\n/**\n * Wraps the content inside a codeblock with no language\n *\n * @param content - The content to wrap\n */\nexport function codeBlock(content: C): `\\`\\`\\`\\n${C}\\n\\`\\`\\``;\n\n/**\n * Wraps the content inside a codeblock with the specified language\n *\n * @param language - The language for the codeblock\n * @param content - The content to wrap\n */\nexport function codeBlock(language: L, content: C): `\\`\\`\\`${L}\\n${C}\\n\\`\\`\\``;\nexport function codeBlock(language: string, content?: string): string {\n\treturn typeof content === 'undefined' ? `\\`\\`\\`\\n${language}\\n\\`\\`\\`` : `\\`\\`\\`${language}\\n${content}\\n\\`\\`\\``;\n}\n\n/**\n * Wraps the content inside \\`backticks\\`, which formats it as inline code\n *\n * @param content - The content to wrap\n */\nexport function inlineCode(content: C): `\\`${C}\\`` {\n\treturn `\\`${content}\\``;\n}\n\n/**\n * Formats the content into italic text\n *\n * @param content - The content to wrap\n */\nexport function italic(content: C): `_${C}_` {\n\treturn `_${content}_`;\n}\n\n/**\n * Formats the content into bold text\n *\n * @param content - The content to wrap\n */\nexport function bold(content: C): `**${C}**` {\n\treturn `**${content}**`;\n}\n\n/**\n * Formats the content into underscored text\n *\n * @param content - The content to wrap\n */\nexport function underscore(content: C): `__${C}__` {\n\treturn `__${content}__`;\n}\n\n/**\n * Formats the content into strike-through text\n *\n * @param content - The content to wrap\n */\nexport function strikethrough(content: C): `~~${C}~~` {\n\treturn `~~${content}~~`;\n}\n\n/**\n * Formats the content into a quote. This needs to be at the start of the line for Discord to format it\n *\n * @param content - The content to wrap\n */\nexport function quote(content: C): `> ${C}` {\n\treturn `> ${content}`;\n}\n\n/**\n * Formats the content into a block quote. This needs to be at the start of the line for Discord to format it\n *\n * @param content - The content to wrap\n */\nexport function blockQuote(content: C): `>>> ${C}` {\n\treturn `>>> ${content}`;\n}\n\n/**\n * Wraps the URL into `<>`, which stops it from embedding\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: C): `<${C}>`;\n\n/**\n * Wraps the URL into `<>`, which stops it from embedding\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: URL): `<${string}>`;\nexport function hideLinkEmbed(url: URL | string) {\n\treturn `<${url}>`;\n}\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: URL): `[${C}](${string})`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: U): `[${C}](${U})`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: URL,\n\ttitle: T,\n): `[${C}](${string} \"${T}\")`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: U,\n\ttitle: T,\n): `[${C}](${U} \"${T}\")`;\nexport function hyperlink(content: string, url: URL | string, title?: string) {\n\treturn title ? `[${content}](${url} \"${title}\")` : `[${content}](${url})`;\n}\n\n/**\n * Wraps the content inside spoiler (hidden text)\n *\n * @param content - The content to wrap\n */\nexport function spoiler(content: C): `||${C}||` {\n\treturn `||${content}||`;\n}\n\n/**\n * Formats a user ID into a user mention\n *\n * @param userId - The user ID to format\n */\nexport function userMention(userId: C): `<@${C}>` {\n\treturn `<@${userId}>`;\n}\n\n/**\n * Formats a channel ID into a channel mention\n *\n * @param channelId - The channel ID to format\n */\nexport function channelMention(channelId: C): `<#${C}>` {\n\treturn `<#${channelId}>`;\n}\n\n/**\n * Formats a role ID into a role mention\n *\n * @param roleId - The role ID to format\n */\nexport function roleMention(roleId: C): `<@&${C}>` {\n\treturn `<@&${roleId}>`;\n}\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends string,\n\tS extends string,\n\tI extends Snowflake,\n>(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): ``;\n\n/**\n * Formats an application command name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tsubcommandName: S,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends Snowflake | string,\n\tS extends Snowflake | string,\n\tI extends Snowflake,\n>(\n\tcommandName: N,\n\tsubcommandGroupName: G,\n\tsubcommandName?: S,\n\tcommandId?: I,\n): `` | `` | `` {\n\tif (typeof commandId !== 'undefined') {\n\t\treturn ``;\n\t}\n\n\tif (typeof subcommandName !== 'undefined') {\n\t\treturn ``;\n\t}\n\n\treturn ``;\n}\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n */\nexport function formatEmoji(emojiId: C, animated?: false): `<:_:${C}>`;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated?: true): ``;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated?: boolean): `<:_:${C}>` | ``;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated = false): `<:_:${C}>` | `` {\n\treturn `<${animated ? 'a' : ''}:_:${emojiId}>`;\n}\n\n/**\n * Formats a channel link for a direct message channel.\n *\n * @param channelId - The channel's id\n */\nexport function channelLink(channelId: C): `https://discord.com/channels/@me/${C}`;\n\n/**\n * Formats a channel link for a guild channel.\n *\n * @param channelId - The channel's id\n * @param guildId - The guild's id\n */\nexport function channelLink(\n\tchannelId: C,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}`;\n\nexport function channelLink(\n\tchannelId: C,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}` | `https://discord.com/channels/${G}/${C}` {\n\treturn `https://discord.com/channels/${guildId ?? '@me'}/${channelId}`;\n}\n\n/**\n * Formats a message link for a direct message channel.\n *\n * @param channelId - The channel's id\n * @param messageId - The message's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n): `https://discord.com/channels/@me/${C}/${M}`;\n\n/**\n * Formats a message link for a guild channel.\n *\n * @param channelId - The channel's id\n * @param messageId - The message's id\n * @param guildId - The guild's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}/${M}`;\n\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}/${M}` | `https://discord.com/channels/${G}/${C}/${M}` {\n\treturn `${typeof guildId === 'undefined' ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`;\n}\n\n/**\n * Formats a date into a short date-time string\n *\n * @param date - The date to format, defaults to the current time\n */\nexport function time(date?: Date): ``;\n\n/**\n * Formats a date given a format style\n *\n * @param date - The date to format\n * @param style - The style to use\n */\nexport function time(date: Date, style: S): ``;\n\n/**\n * Formats the given timestamp into a short date-time string\n *\n * @param seconds - The time to format, represents an UNIX timestamp in seconds\n */\nexport function time(seconds: C): ``;\n\n/**\n * Formats the given timestamp into a short date-time string\n *\n * @param seconds - The time to format, represents an UNIX timestamp in seconds\n * @param style - The style to use\n */\nexport function time(seconds: C, style: S): ``;\nexport function time(timeOrSeconds?: Date | number, style?: TimestampStylesString): string {\n\tif (typeof timeOrSeconds !== 'number') {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttimeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1_000);\n\t}\n\n\treturn typeof style === 'string' ? `` : ``;\n}\n\n/**\n * The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles} supported by Discord\n */\nexport const TimestampStyles = {\n\t/**\n\t * Short time format, consisting of hours and minutes, e.g. 16:20\n\t */\n\tShortTime: 't',\n\n\t/**\n\t * Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30\n\t */\n\tLongTime: 'T',\n\n\t/**\n\t * Short date format, consisting of day, month, and year, e.g. 20/04/2021\n\t */\n\tShortDate: 'd',\n\n\t/**\n\t * Long date format, consisting of day, month, and year, e.g. 20 April 2021\n\t */\n\tLongDate: 'D',\n\n\t/**\n\t * Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20\n\t */\n\tShortDateTime: 'f',\n\n\t/**\n\t * Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20\n\t */\n\tLongDateTime: 'F',\n\n\t/**\n\t * Relative time format, consisting of a relative duration format, e.g. 2 months ago\n\t */\n\tRelativeTime: 'R',\n} as const;\n\n/**\n * The possible values, see {@link TimestampStyles} for more information\n */\nexport type TimestampStylesString = typeof TimestampStyles[keyof typeof TimestampStyles];\n\n/**\n * An enum with all the available faces from Discord's native slash commands\n */\nexport enum Faces {\n\t/**\n\t * ¯\\\\_(ツ)\\\\_/¯\n\t */\n\tShrug = '¯\\\\_(ツ)\\\\_/¯',\n\n\t/**\n\t * (╯°□°)╯︵ ┻━┻\n\t */\n\tTableflip = '(╯°□°)╯︵ ┻━┻',\n\n\t/**\n\t * ┬─┬ ノ( ゜-゜ノ)\n\t */\n\tUnflip = '┬─┬ ノ( ゜-゜ノ)',\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * Represents an option within a string select menu component\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah')\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label of this option\n\t *\n\t * @param label - The label to show on this option\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value of this option\n\t *\n\t * @param value - The value of this option\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this option\n\t *\n\t * @param description - The description of this option\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this option\n\t *\n\t * @param emoji - The emoji to display on this option\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * Represents an action row component\n *\n * @typeParam T - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row\n\t */\n\tpublic readonly components: T[];\n\n\t/**\n\t * Creates a new action row from API data\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as T[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add to this action row.\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the components in this action row\n\t *\n\t * @param components - The components to set this row to\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * Represents a discord component\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this component to an API-compatible JSON object\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\nexport interface MappedComponentTypes {\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t[ComponentType.Button]: ButtonBuilder;\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data\n *\n * @param data - The api data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members\n\tdata: (APIModalComponent | APIMessageComponent) & { type: T },\n): MappedComponentTypes[T];\nexport function createComponentBuilder(data: C): C;\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error: This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * Represents a button component\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: '🙂' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button\n\t *\n\t * @param style - The style of the button\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://` and `discord://`\n\t * @param url - The URL to open when this button is clicked\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use for this button\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button\n\t *\n\t * @param emoji - The emoji to display on this button\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button\n\t *\n\t * @param label - The label to display on this button\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import type { APIChannelSelectComponent, ChannelType } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttypes = normalizeArray(types);\n\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(types));\n\t\treturn this;\n\t}\n\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttypes = normalizeArray(types);\n\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\nexport class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu\n\t *\n\t * @param placeholder - The placeholder to use for this select menu\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu\n\t *\n\t * @param customId - The custom id to use for this select menu\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import type { APIMentionableSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n}\n","import type { APIRoleSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n}\n","import type { APIStringSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType, type APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * Represents a string select menu component\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu\n\t *\n\t * @param options - The options to add to this select menu\n\t * @returns\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\toptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + options.length);\n\t\tthis.options.push(\n\t\t\t...options.map((option) =>\n\t\t\t\toption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? option\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options on this select menu\n\t *\n\t * @param options - The options to set on this select menu\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\toptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(options.length);\n\t\tthis.options.splice(\n\t\t\t0,\n\t\t\tthis.options.length,\n\t\t\t...options.map((option) =>\n\t\t\t\toption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? option\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import type { APIUserSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input\n\t *\n\t * @param customId - The custom id of this text input\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input\n\t *\n\t * @param label - The label for this text input\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input\n\t *\n\t * @param style - The style for this text input\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder of this text input\n\t *\n\t * @param placeholder - The placeholder of this text input\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value of this text input\n\t *\n\t * @param value - The value for this text input\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\nexport class ModalBuilder implements JSONEncodable {\n\tpublic readonly data: Partial;\n\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of the modal\n\t *\n\t * @param title - The title of the modal\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of the modal\n\t *\n\t * @param customId - The custom id of this modal\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal\n\t *\n\t * @param components - The components to add to this modal\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the components in this modal\n\t *\n\t * @param components - The components to set this modal to\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tT extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this slash command\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The localized names for this command\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this slash command\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The localized descriptions for this command\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this slash command\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether the command is enabled by default when the app is added to a guild\n\t *\n\t * @deprecated This property is deprecated and will be removed in the future.\n\t * You should use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Set of permissions represented as a bit set for the command\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Returns the final data that should be sent to Discord.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t * @deprecated Use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t *\n\t * @param enabled - If the command should be enabled in DMs\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command\n\t *\n\t * @param input - A function that returns a subcommand group builder, or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command\n\t *\n\t * @param input - A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands\n *\n * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands part of this subcommand group\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group\n\t *\n\t * @param input - A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * Represents a subcommand\n *\n * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options of this subcommand\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\nexport class SharedNameAndDescription {\n\tpublic readonly name!: string;\n\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\tpublic readonly description!: string;\n\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name\n\t *\n\t * @param name - The name\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description\n\t *\n\t * @param description - The description\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedName - The localized description for the given locale\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations\n\t *\n\t * @param localizedNames - The dictionary of localized descriptions to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations\n\t *\n\t * @param localizedDescriptions - The dictionary of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Marks the option as required\n\t *\n\t * @param required - If this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n// Only allow valid channel types to be used. (This can't be dynamic because const enums are erased at runtime)\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n] as const;\n\nexport type ApplicationCommandOptionAllowedChannelTypes = typeof allowedChannelTypes[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\nexport class ApplicationCommandOptionChannelTypesMixin {\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option\n\t *\n\t * @param channelTypes - The channel types to add\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","export abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\tpublic readonly max_value?: number;\n\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\tpublic readonly autocomplete?: boolean;\n\n\t// Since this is present and this is a mixin, this is needed\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices for this option\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Marks the option as autocompletable\n\t *\n\t * @param autocomplete - If this option should be autocompletable\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\tpublic readonly max_length?: number;\n\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| T\n\t\t\t| ((builder: T) => Omit | Omit | T),\n\t\tInstance: new () => T,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group, unicorn/no-unsafe-regex\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this context menu command\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The localized names for this command\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this context menu command\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether the command is enabled by default when the app is added to a guild\n\t *\n\t * @deprecated This property is deprecated and will be removed in the future.\n\t * You should use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Set of permissions represented as a bit set for the command\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name\n\t *\n\t * @param name - The name\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type\n\t *\n\t * @param type - The type\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t *\n\t * @param enabled - If the command should be enabled in DMs\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedName - The localized description for the given locale\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations\n\t *\n\t * @param localizedNames - The dictionary of localized descriptions to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the final data that should be sent to Discord.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n","import type { APIEmbed } from 'discord-api-types/v10';\n\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n","export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\nexport * from './messages/formatters.js';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\nexport * from '@discordjs/util';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders/#readme | @discordjs/builders} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.4.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAS,SAAS;;;ACAlB,IAAI,WAAW;AAER,IAAM,mBAAmB,6BAAO,WAAW,MAAlB;AACzB,IAAM,oBAAoB,6BAAO,WAAW,OAAlB;AAC1B,IAAM,sBAAsB,6BAAM,UAAN;;;ADA5B,IAAM,qBAAqB,EAAE,OAClC,yBAAyB,CAAC,EAC1B,sBAAsB,GAAG,EACzB,qBAAqB,mBAAmB;AAEnC,IAAM,sBAAsB,EAAE,OACnC,yBAAyB,CAAC,EAC1B,sBAAsB,IAAK,EAC3B,qBAAqB,mBAAmB;AAEnC,IAAM,uBAAuB,EAAE,QAAQ;AAEvC,IAAM,sBAAsB,EACjC,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,QAAQ;AACT,CAAC,EACA,qBAAqB,mBAAmB;AAEnC,IAAM,4BAA4B,oBAAoB,MAAM,qBAAqB,mBAAmB;AAEpG,IAAM,uBAAuB,EAAE,OAAO,gBAAgB,EAAE,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QP,IAAM,UAAkB;","names":["Faces","Assertions_exports","s","s","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","Assertions_exports","placeholderValidator","s","s","placeholderValidator","ComponentType","placeholderValidator","ComponentType","ComponentType","Assertions_exports","validateRequiredParameters","s","s","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","s","s","descriptionPredicate","validateRequiredParameters","mix","ApplicationCommandOptionType","mix","validateRequiredParameters","ApplicationCommandOptionType","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ChannelType","ChannelType","s","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","s","ApplicationCommandOptionType","s","booleanPredicate","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","numberValidator","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","minLengthValidator","s","maxLengthValidator","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","validateRequiredParameters","ApplicationCommandOptionType","mix","validateRequiredParameters","mix","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","s","namePredicate","s","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file +{"version":3,"sources":["../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/index.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts"],"sourcesContent":["import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\n/**\n * Enables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function enableValidators() {\n\treturn (validate = true);\n}\n\n/**\n * Disables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function disableValidators() {\n\treturn (validate = false);\n}\n\n/**\n * Checks whether validation is occurring.\n */\nexport function isValidationEnabled() {\n\treturn validate;\n}\n","/**\n * Normalizes data that is a rest parameter or an array into an array with a depth of 1.\n *\n * @typeParam T - The data that must satisfy {@link RestOrArray}.\n * @param arr - The (possibly variadic) data to normalize\n */\nexport function normalizeArray(arr: RestOrArray): T[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as T[];\n}\n\n/**\n * Represents data that may be an array or came from a rest parameter.\n *\n * @remarks\n * This type is used throughout builders to ensure both an array and variadic arguments\n * may be used. It is normalized with {@link normalizeArray}.\n */\nexport type RestOrArray = T[] | [T[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\n/**\n * A tuple satisfying the RGB color model.\n *\n * @see {@link https://developer.mozilla.org/docs/Glossary/RGB}\n */\nexport type RGBTuple = [red: number, green: number, blue: number];\n\n/**\n * The base icon data typically used in payloads.\n */\nexport interface IconData {\n\t/**\n\t * The URL of the icon.\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon.\n\t */\n\tproxyIconURL?: string;\n}\n\n/**\n * Represents the author data of an embed.\n */\nexport type EmbedAuthorData = IconData & Omit;\n\n/**\n * Represents the author options of an embed.\n */\nexport type EmbedAuthorOptions = Omit;\n\n/**\n * Represents the footer data of an embed.\n */\nexport type EmbedFooterData = IconData & Omit;\n\n/**\n * Represents the footer options of an embed.\n */\nexport type EmbedFooterOptions = Omit;\n\n/**\n * Represents the image data of an embed.\n */\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image.\n\t */\n\tproxyURL?: string;\n}\n\n/**\n * A builder that creates API-compatible JSON data for embeds.\n */\nexport class EmbedBuilder {\n\t/**\n\t * The API data associated with this embed.\n\t */\n\tpublic readonly data: APIEmbed;\n\n\t/**\n\t * Creates a new embed from API data.\n\t *\n\t * @param data - The API data to create this embed with\n\t */\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed.\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array:\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic):\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\tconst normalizedFields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(normalizedFields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(normalizedFields);\n\n\t\tif (this.data.fields) this.data.fields.push(...normalizedFields);\n\t\telse this.data.fields = normalizedFields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields for this embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field:\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields:\n\t * ```ts\n\t * const n = 4;\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field:\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the fields for this embed.\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed.\n\t *\n\t * @param options - The options to use\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed.\n\t *\n\t * @param color - The color to use\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed.\n\t *\n\t * @param options - The footer to use\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed.\n\t *\n\t * @param url - The image URL to use\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed.\n\t *\n\t * @param url - The thumbnail URL to use\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed.\n\t *\n\t * @param timestamp - The timestamp or date to use\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title for this embed.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed.\n\t *\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\n// TODO: Consider removing this dep in the next major version\nexport * from '@discordjs/formatters';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version\n * that you are currently using.\n *\n * @privateRemarks This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild.\n */\nexport const version = '1.6.3' as string;\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menu options.\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data.\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah');\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label for this option.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this option.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description for this option.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default.\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display for this option.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * The builders that may be used for messages.\n */\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\n\n/**\n * The builders that may be used for modals.\n */\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\n\n/**\n * The builders that may be used within an action row for messages.\n */\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\n\n/**\n * The builders that may be used within an action row for modals.\n */\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\n\n/**\n * Any builder.\n */\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * A builder that creates API-compatible JSON data for action rows.\n *\n * @typeParam T - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row.\n\t */\n\tpublic readonly components: T[];\n\n\t/**\n\t * Creates a new action row from API data.\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as T[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this action row.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\n/**\n * Any action row component data represented as an object.\n */\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * The base component builder that contains common symbols for all sorts of components.\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\t/**\n\t * Constructs a new kind of component.\n\t *\n\t * @param data - The data to construct a component out of\n\t */\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * Components here are mapped to their respective builder.\n */\nexport interface MappedComponentTypes {\n\t/**\n\t * The action row component type is associated with an {@link ActionRowBuilder}.\n\t */\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t/**\n\t * The button component type is associated with an {@link ButtonBuilder}.\n\t */\n\t[ComponentType.Button]: ButtonBuilder;\n\t/**\n\t * The string select component type is associated with an {@link StringSelectMenuBuilder}.\n\t */\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t/**\n\t * The text inpiut component type is associated with an {@link TextInputBuilder}.\n\t */\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t/**\n\t * The user select component type is associated with an {@link UserSelectMenuBuilder}.\n\t */\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t/**\n\t * The role select component type is associated with an {@link RoleSelectMenuBuilder}.\n\t */\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t/**\n\t * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}.\n\t */\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t/**\n\t * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}.\n\t */\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam T - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members\n\tdata: (APIModalComponent | APIMessageComponent) & { type: T },\n): MappedComponentTypes[T];\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam C - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(data: C): C;\n\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * A builder that creates API-compatible JSON data for buttons.\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data.\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: '🙂' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button.\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`.\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button.\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled.\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import type { APIChannelSelectComponent, ChannelType } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for channel select menus.\n */\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\t/**\n\t * Adds channel types to this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets channel types for this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * The base select menu builder that contains common symbols for select menu builders.\n *\n * @typeParam SelectMenuType - The type of select menu this would be instantiated for.\n */\nexport abstract class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu.\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu.\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled.\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import type { APIMentionableSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for mentionable select menus.\n */\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n}\n","import type { APIRoleSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for role select menus.\n */\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n}\n","import { ComponentType } from 'discord-api-types/v10';\nimport type { APIStringSelectComponent, APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menus.\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu.\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu.\n\t *\n\t * @param options - The options to add\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + normalizedOptions.length);\n\t\tthis.options.push(\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options for this select menu.\n\t *\n\t * @param options - The options to set\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\treturn this.spliceOptions(0, this.options.length, ...options);\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts options for this select menu.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}.\n\t * It's useful for modifying and adjusting the order of existing options.\n\t * @example\n\t * Remove the first option:\n\t * ```ts\n\t * selectMenu.spliceOptions(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n option:\n\t * ```ts\n\t * const n = 4;\n\t * selectMenu.spliceOptions(0, n);\n\t * ```\n\t * @example\n\t * Remove the last option:\n\t * ```ts\n\t * selectMenu.spliceOptions(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of options to remove\n\t * @param options - The replacing option objects or builders\n\t */\n\tpublic spliceOptions(\n\t\tindex: number,\n\t\tdeleteCount: number,\n\t\t...options: RestOrArray\n\t) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\n\t\tconst clone = [...this.options];\n\n\t\tclone.splice(\n\t\t\tindex,\n\t\t\tdeleteCount,\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\n\t\toptionsLengthValidator.parse(clone.length);\n\t\tthis.options.splice(0, this.options.length, ...clone);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import type { APIUserSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for user select menus.\n */\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for text inputs.\n */\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data.\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input.\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input.\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder for this text input.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this text input.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required.\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for modals.\n */\nexport class ModalBuilder implements JSONEncodable {\n\t/**\n\t * The API data associated with this modal.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * The components within this modal.\n\t */\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\t/**\n\t * Creates a new modal from API data.\n\t *\n\t * @param data - The API data to create this modal with\n\t */\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of this modal.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of this modal.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this modal.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tT extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n\nexport function validateNSFW(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n\tvalidateNSFW,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * A builder that creates API-compatible JSON data for slash commands.\n */\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this command.\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Whether this command is NSFW.\n\t */\n\tpublic readonly nsfw: boolean | undefined = undefined;\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this command is NSFW.\n\t *\n\t * @param nsfw - Whether this command is NSFW\n\t */\n\tpublic setNSFW(nsfw = true) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateNSFW(nsfw);\n\t\tReflect.set(this, 'nsfw', nsfw);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command.\n\t *\n\t * @param input - A function that returns a subcommand group builder or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\n/**\n * An interface specifically for slash command subcommands.\n */\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\n/**\n * An interface specifically for slash command options.\n */\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\n/**\n * An interface that ensures the `toJSON()` call will return something\n * that can be serialized into API-compatible data.\n */\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands within this subcommand group.\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * A builder that creates API-compatible JSON data for slash command subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options within this subcommand.\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\n/**\n * This mixin holds name and description symbols for slash commands.\n */\nexport class SharedNameAndDescription {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name!: string;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description!: string;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this command.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * SSets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations for this command.\n\t *\n\t * @param localizedDescriptions - The object of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command attachment option.\n */\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\n/**\n * The base application command option builder that contains common symbols for application command builders.\n */\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\t/**\n\t * Whether this option is required.\n\t *\n\t * @defaultValue `false`\n\t */\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Sets whether this option is required.\n\t *\n\t * @param required - Whether this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\t/**\n\t * This method runs required validators on this builder.\n\t */\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command boolean option.\n */\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n/**\n * A slash command channel option.\n */\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n/**\n * The allowed channel types used for a channel option in a slash command builder.\n *\n * @privateRemarks This can't be dynamic because const enums are erased at runtime.\n * @internal\n */\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n] as const;\n\n/**\n * The type of allowed channel types used for a channel option.\n */\nexport type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\n/**\n * This mixin holds channel type symbols used for options.\n */\nexport class ApplicationCommandOptionChannelTypesMixin {\n\t/**\n\t * The channel types of this option.\n\t */\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option.\n\t *\n\t * @param channelTypes - The channel types\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n/**\n * A slash command integer option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","/**\n * This mixin holds minimum and maximum symbols used for options.\n */\nexport abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\t/**\n\t * The maximum value of this option.\n\t */\n\tpublic readonly max_value?: number;\n\n\t/**\n\t * The minimum value of this option.\n\t */\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option.\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option.\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\n/**\n * This mixin holds choices and autocomplete symbols used for options.\n */\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\t/**\n\t * The choices of this option.\n\t */\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\t/**\n\t * Whether this option utilizes autocomplete.\n\t */\n\tpublic readonly autocomplete?: boolean;\n\n\t/**\n\t * The type of this option.\n\t *\n\t * @privateRemarks Since this is present and this is a mixin, this is needed.\n\t */\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices to this option.\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets multiple choices for this option.\n\t *\n\t * @param choices - The choices to set\n\t */\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Whether this option uses autocomplete.\n\t *\n\t * @param autocomplete - Whether this option should use autocomplete\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command mentionable option.\n */\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n/**\n * A slash command number option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command role option.\n */\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n/**\n * A slash command string option.\n */\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\t/**\n\t * The maximum length of this option.\n\t */\n\tpublic readonly max_length?: number;\n\n\t/**\n\t * The minimum length of this option.\n\t */\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command user option.\n */\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\n/**\n * This mixin holds symbols that can be shared in slash command options.\n *\n * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions.\n */\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\t/**\n\t * Where the actual adding magic happens. ✨\n\t *\n\t * @param input - The input. What else?\n\t * @param Instance - The instance of whatever is being added\n\t * @internal\n\t */\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| T\n\t\t\t| ((builder: T) => Omit | Omit | T),\n\t\tInstance: new () => T,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group, unicorn/no-unsafe-regex\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\n/**\n * The type a context menu command can be.\n */\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n\n/**\n * A builder that creates API-compatible JSON data for context menu commands.\n */\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this command.\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type of this command.\n\t *\n\t * @param type - The type to use\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run this command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIEmbed } from 'discord-api-types/v10';\n\n/**\n * Calculates the length of the embed.\n *\n * @param data - The embed data to check\n */\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAS,SAAS;;;ACAlB,IAAI,WAAW;AAOR,SAAS,mBAAmB;AAClC,SAAQ,WAAW;AACpB;AAFgB;AAST,SAAS,oBAAoB;AACnC,SAAQ,WAAW;AACpB;AAFgB;AAOT,SAAS,sBAAsB;AACrC,SAAO;AACR;AAFgB;;;ADnBT,IAAM,qBAAqB,EAAE,OAClC,yBAAyB,CAAC,EAC1B,sBAAsB,GAAG,EACzB,qBAAqB,mBAAmB;AAEnC,IAAM,sBAAsB,EAAE,OACnC,yBAAyB,CAAC,EAC1B,sBAAsB,IAAK,EAC3B,qBAAqB,mBAAmB;AAEnC,IAAM,uBAAuB,EAAE,QAAQ;AAEvC,IAAM,sBAAsB,EACjC,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,QAAQ;AACT,CAAC,EACA,qBAAqB,mBAAmB;AAEnC,IAAM,4BAA4B,oBAAoB,MAAM,qBAAqB,mBAAmB;AAEpG,IAAM,uBAAuB,EAAE,OAAO,gBAAgB,EAAE,EAAE,qBAAqB,mBAAmB;AAElG,SAAS,oBAAoB,cAAsB,QAAgC;AACzF,uBAAqB,OAAO,QAAQ,UAAU,KAAK,YAAY;AAChE;AAFgB;AAIT,IAAM,sBAAsB,mBAAmB,SAAS,qBAAqB,mBAAmB;AAEhG,IAAM,oBAAoB,EAAE,OACjC,IAAI;AAAA,EACJ,kBAAkB,CAAC,SAAS,UAAU,aAAa;AACpD,CAAC,EACA,QAAQ,qBAAqB,mBAAmB;AA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;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,qBAAqB,gBAAwC;AACnE,QAAI,mBAAmB,MAAM;AAC5B,cAAQ,IAAI,MAAM,sBAAsB,IAAI;AAC5C,aAAO;AAAA,IACR;AAEA,YAAQ,IAAI,MAAM,sBAAsB,CAAC,CAAC;AAE1C,eAAW,QAAQ,OAAO,QAAQ,cAAc;AAC/C,WAAK,oBAAoB,GAAI,IAAsC;AACpE,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,SAA4D;AAClE,IAAAI,4BAA2B,KAAK,MAAM,KAAK,IAAI;AAE/C,4BAAwB,KAAK,kBAAkB;AAE/C,WAAO,EAAE,GAAG,KAAK;AAAA,EAClB;AACD;AA5Ka;;;AClBN,SAAS,YAAY,MAAgB;AAC3C,UACE,KAAK,OAAO,UAAU,MACtB,KAAK,aAAa,UAAU,MAC5B,KAAK,QAAQ,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,KAAK,MACvF,KAAK,QAAQ,KAAK,UAAU,MAC5B,KAAK,QAAQ,KAAK,UAAU;AAE/B;AARgB;;;ArC6DT,IAAM,UAAU;","names":["Assertions_exports","s","s","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","Assertions_exports","placeholderValidator","s","s","placeholderValidator","ComponentType","placeholderValidator","ComponentType","ComponentType","Assertions_exports","validateRequiredParameters","s","s","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","s","s","descriptionPredicate","validateRequiredParameters","mix","ApplicationCommandOptionType","mix","validateRequiredParameters","ApplicationCommandOptionType","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ChannelType","ChannelType","s","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","s","ApplicationCommandOptionType","s","booleanPredicate","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","numberValidator","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","minLengthValidator","s","maxLengthValidator","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","validateRequiredParameters","ApplicationCommandOptionType","mix","validateRequiredParameters","mix","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","s","namePredicate","s","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file diff --git a/node_modules/@discordjs/builders/package.json b/node_modules/@discordjs/builders/package.json index a606a14..da4ec0b 100644 --- a/node_modules/@discordjs/builders/package.json +++ b/node_modules/@discordjs/builders/package.json @@ -1,14 +1,15 @@ { "name": "@discordjs/builders", - "version": "1.4.0", + "version": "1.6.3", "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": "api-extractor run --local", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", "prepack": "yarn lint && yarn test && yarn build", "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/builders/*'", "release": "cliff-jumper" @@ -17,9 +18,9 @@ "module": "./dist/index.mjs", "types": "./dist/index.d.ts", "exports": { + "types": "./dist/index.d.ts", "import": "./dist/index.mjs", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" + "require": "./dist/index.js" }, "directories": { "lib": "src", @@ -47,34 +48,37 @@ ], "repository": { "type": "git", - "url": "https://github.com/discordjs/discord.js.git" + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/builders" }, "bugs": { "url": "https://github.com/discordjs/discord.js/issues" }, "homepage": "https://discord.js.org", "dependencies": { - "@discordjs/util": "^0.1.0", - "@sapphire/shapeshift": "^3.7.1", - "discord-api-types": "^0.37.20", + "@discordjs/formatters": "^0.3.1", + "@discordjs/util": "^0.3.1", + "@sapphire/shapeshift": "^3.8.2", + "discord-api-types": "^0.37.41", "fast-deep-equal": "^3.1.3", - "ts-mixer": "^6.0.2", - "tslib": "^2.4.1" + "ts-mixer": "^6.0.3", + "tslib": "^2.5.0" }, "devDependencies": { - "@favware/cliff-jumper": "^1.9.0", - "@microsoft/api-extractor": "^7.33.6", - "@types/node": "16.18.3", - "@vitest/coverage-c8": "^0.25.3", + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.6", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.30.1", "cross-env": "^7.0.3", - "esbuild-plugin-version-injector": "^1.0.2", - "eslint": "^8.28.0", - "eslint-config-neon": "^0.1.40", - "eslint-formatter-pretty": "^4.1.0", - "prettier": "^2.8.0", - "tsup": "^6.5.0", - "typescript": "^4.9.3", - "vitest": "^0.25.3" + "downlevel-dts": "^0.11.0", + "esbuild-plugin-version-injector": "^1.1.0", + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.42", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsup": "^6.7.0", + "typescript": "^5.0.4", + "vitest": "^0.29.8" }, "engines": { "node": ">=16.9.0" diff --git a/node_modules/@discordjs/collection/CHANGELOG.md b/node_modules/@discordjs/collection/CHANGELOG.md index 6337754..726af82 100644 --- a/node_modules/@discordjs/collection/CHANGELOG.md +++ b/node_modules/@discordjs/collection/CHANGELOG.md @@ -2,6 +2,44 @@ All notable changes to this project will be documented in this file. +# [@discordjs/collection@1.5.1](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.0...@discordjs/collection@1.5.1) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +# [@discordjs/collection@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.4.0...@discordjs/collection@1.5.0) - (2023-04-01) + +## Bug Fixes + +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +## Refactor + +- **collection:** Fix/silence linter warnings (#9266) ([d6f4e60](https://github.com/discordjs/discord.js/commit/d6f4e60efd1a1796fc84dbbfbac4f9790e480a1c)) + +# [@discordjs/collection@1.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.3.0...@discordjs/collection@1.4.0) - (2023-03-12) + +## Documentation + +- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28)) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) + +## Refactor + +- Compare with `undefined` directly (#9191) ([869153c](https://github.com/discordjs/discord.js/commit/869153c3fdf155783e7c0ecebd3627b087c3a026)) + # [@discordjs/collection@1.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.2.0...@discordjs/collection@1.3.0) - (2022-11-28) ## Bug Fixes diff --git a/node_modules/@discordjs/collection/README.md b/node_modules/@discordjs/collection/README.md index 93c12e4..3e7b369 100644 --- a/node_modules/@discordjs/collection/README.md +++ b/node_modules/@discordjs/collection/README.md @@ -24,7 +24,7 @@ **Node.js 16.9.0 or newer is required.** -```sh-session +```sh npm install @discordjs/collection yarn add @discordjs/collection pnpm add @discordjs/collection @@ -35,7 +35,7 @@ pnpm add @discordjs/collection - [Website][website] ([source][website-source]) - [Documentation][documentation] - [Guide][guide] ([source][guide-source]) - See also the [Update Guide][guide-update], including updated and removed items in the library. + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. - [discord.js Discord server][discord] - [Discord API Discord server][discord-api] - [GitHub][source] @@ -50,12 +50,11 @@ See [the contribution guide][contributing] if you'd like to submit a PR. ## Help -If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle -nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. -[website]: https://discord.js.org/ +[website]: https://discord.js.org [website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website -[documentation]: https://discord.js.org/#/docs/collection +[documentation]: https://discord.js.org/docs/packages/collection/stable [guide]: https://discordjs.guide/ [guide-source]: https://github.com/discordjs/guide [guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html diff --git a/node_modules/@discordjs/collection/dist/index.js b/node_modules/@discordjs/collection/dist/index.js index af69471..6d459fa 100644 --- a/node_modules/@discordjs/collection/dist/index.js +++ b/node_modules/@discordjs/collection/dist/index.js @@ -28,6 +28,16 @@ module.exports = __toCommonJS(src_exports); // src/collection.ts var Collection = class extends Map { + /** + * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator. + * + * @param key - The key to get if it exists, or set otherwise + * @param defaultValueGenerator - A function that generates the default value + * @example + * ```ts + * collection.ensure(guildId, () => defaultGuildConfig); + * ``` + */ ensure(key, defaultValueGenerator) { if (this.has(key)) return this.get(key); @@ -37,14 +47,26 @@ var Collection = class extends Map { this.set(key, defaultValue); return defaultValue; } + /** + * Checks if all of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if all of the elements exist, `false` if at least one does not exist. + */ hasAll(...keys) { - return keys.every((k) => super.has(k)); + return keys.every((key) => super.has(key)); } + /** + * Checks if any of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if any of the elements exist, `false` if none exist. + */ hasAny(...keys) { - return keys.some((k) => super.has(k)); + return keys.some((key) => super.has(key)); } first(amount) { - if (typeof amount === "undefined") + if (amount === void 0) return this.values().next().value; if (amount < 0) return this.last(amount * -1); @@ -53,7 +75,7 @@ var Collection = class extends Map { return Array.from({ length: amount }, () => iter.next().value); } firstKey(amount) { - if (typeof amount === "undefined") + if (amount === void 0) return this.keys().next().value; if (amount < 0) return this.lastKey(amount * -1); @@ -63,7 +85,7 @@ var Collection = class extends Map { } last(amount) { const arr = [...this.values()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[arr.length - 1]; if (amount < 0) return this.first(amount * -1); @@ -73,7 +95,7 @@ var Collection = class extends Map { } lastKey(amount) { const arr = [...this.keys()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[arr.length - 1]; if (amount < 0) return this.firstKey(amount * -1); @@ -81,11 +103,25 @@ var Collection = class extends Map { return []; return arr.slice(-amount); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the item at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the element to obtain + */ at(index) { index = Math.floor(index); const arr = [...this.values()]; return arr.at(index); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the key at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the key to obtain + */ keyAt(index) { index = Math.floor(index); const arr = [...this.keys()]; @@ -93,7 +129,7 @@ var Collection = class extends Map { } random(amount) { const arr = [...this.values()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[Math.floor(Math.random() * arr.length)]; if (!arr.length || !amount) return []; @@ -104,7 +140,7 @@ var Collection = class extends Map { } randomKey(amount) { const arr = [...this.keys()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[Math.floor(Math.random() * arr.length)]; if (!arr.length || !amount) return []; @@ -113,6 +149,10 @@ var Collection = class extends Map { () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0] ); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()} + * but returns a Collection instead of an Array. + */ reverse() { const entries = [...this.entries()].reverse(); this.clear(); @@ -123,7 +163,7 @@ var Collection = class extends Map { find(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -134,7 +174,7 @@ var Collection = class extends Map { findKey(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -145,7 +185,7 @@ var Collection = class extends Map { sweep(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const previousSize = this.size; for (const [key, val] of this) { @@ -157,7 +197,7 @@ var Collection = class extends Map { filter(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const results = new this.constructor[Symbol.species](); for (const [key, val] of this) { @@ -169,7 +209,7 @@ var Collection = class extends Map { partition(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const results = [ new this.constructor[Symbol.species](), @@ -191,7 +231,7 @@ var Collection = class extends Map { map(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const iter = this.entries(); return Array.from({ length: this.size }, () => { @@ -202,7 +242,7 @@ var Collection = class extends Map { mapValues(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const coll = new this.constructor[Symbol.species](); for (const [key, val] of this) @@ -212,7 +252,7 @@ var Collection = class extends Map { some(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -223,7 +263,7 @@ var Collection = class extends Map { every(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (!fn(val, key, this)) @@ -231,11 +271,23 @@ var Collection = class extends Map { } return true; } + /** + * Applies a function to produce a single value. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}. + * + * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, + * and `collection` + * @param initialValue - Starting value for the accumulator + * @example + * ```ts + * collection.reduce((acc, guild) => acc + guild.memberCount, 0); + * ``` + */ reduce(fn, initialValue) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); let accumulator; - if (typeof initialValue !== "undefined") { + if (initialValue !== void 0) { accumulator = initialValue; for (const [key, val] of this) accumulator = fn(accumulator, val, key, this); @@ -258,20 +310,41 @@ var Collection = class extends Map { each(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - this.forEach(fn, thisArg); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, value] of this) { + fn(value, key, this); + } return this; } tap(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); fn(this); return this; } + /** + * Creates an identical shallow copy of this collection. + * + * @example + * ```ts + * const newColl = someColl.clone(); + * ``` + */ clone() { return new this.constructor[Symbol.species](this); } + /** + * Combines this collection with others into a new collection. None of the source collections are modified. + * + * @param collections - Collections to merge + * @example + * ```ts + * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); + * ``` + */ concat(...collections) { const newColl = this.clone(); for (const coll of collections) { @@ -280,6 +353,14 @@ var Collection = class extends Map { } return newColl; } + /** + * Checks if this collection shares identical items with another. + * This is different to checking for equality using equal-signs, because + * the collections may be different objects, but contain the same data. + * + * @param collection - Collection to compare with + * @returns Whether the collections have identical contents + */ equals(collection) { if (!collection) return false; @@ -294,67 +375,135 @@ var Collection = class extends Map { } return true; } + /** + * The sort method sorts the items of a collection in place and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element. + * @example + * ```ts + * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ sort(compareFunction = Collection.defaultSort) { const entries = [...this.entries()]; entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0])); super.clear(); - for (const [k, v] of entries) { - super.set(k, v); + for (const [key, value] of entries) { + super.set(key, value); } return this; } + /** + * The intersect method returns a new structure containing items where the keys and values are present in both original structures. + * + * @param other - The other Collection to filter against + */ intersect(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of other) { - if (this.has(k) && Object.is(v, this.get(k))) { - coll.set(k, v); + for (const [key, value] of other) { + if (this.has(key) && Object.is(value, this.get(key))) { + coll.set(key, value); } } return coll; } + /** + * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other. + * + * @param other - The other Collection to filter against + */ subtract(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of this) { - if (!other.has(k) || !Object.is(v, other.get(k))) { - coll.set(k, v); + for (const [key, value] of this) { + if (!other.has(key) || !Object.is(value, other.get(key))) { + coll.set(key, value); } } return coll; } + /** + * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other. + * + * @param other - The other Collection to filter against + */ difference(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of other) { - if (!this.has(k)) - coll.set(k, v); + for (const [key, value] of other) { + if (!this.has(key)) + coll.set(key, value); } - for (const [k, v] of this) { - if (!other.has(k)) - coll.set(k, v); + for (const [key, value] of this) { + if (!other.has(key)) + coll.set(key, value); } return coll; } + /** + * Merges two Collections together into a new Collection. + * + * @param other - The other Collection to merge with + * @param whenInSelf - Function getting the result if the entry only exists in this Collection + * @param whenInOther - Function getting the result if the entry only exists in the other Collection + * @param whenInBoth - Function getting the result if the entry exists in both Collections + * @example + * ```ts + * // Sums up the entries in two collections. + * coll.merge( + * other, + * x => ({ keep: true, value: x }), + * y => ({ keep: true, value: y }), + * (x, y) => ({ keep: true, value: x + y }), + * ); + * ``` + * @example + * ```ts + * // Intersects two collections in a left-biased manner. + * coll.merge( + * other, + * x => ({ keep: false }), + * y => ({ keep: false }), + * (x, _) => ({ keep: true, value: x }), + * ); + * ``` + */ merge(other, whenInSelf, whenInOther, whenInBoth) { const coll = new this.constructor[Symbol.species](); const keys = /* @__PURE__ */ new Set([...this.keys(), ...other.keys()]); - for (const k of keys) { - const hasInSelf = this.has(k); - const hasInOther = other.has(k); + for (const key of keys) { + const hasInSelf = this.has(key); + const hasInOther = other.has(key); if (hasInSelf && hasInOther) { - const r = whenInBoth(this.get(k), other.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInBoth(this.get(key), other.get(key), key); + if (result.keep) + coll.set(key, result.value); } else if (hasInSelf) { - const r = whenInSelf(this.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInSelf(this.get(key), key); + if (result.keep) + coll.set(key, result.value); } else if (hasInOther) { - const r = whenInOther(other.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInOther(other.get(key), key); + if (result.keep) + coll.set(key, result.value); } } return coll; } + /** + * The sorted method sorts the items of a collection and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, + * according to the string conversion of each element. + * @example + * ```ts + * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ sorted(compareFunction = Collection.defaultSort) { return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk)); } @@ -364,13 +513,24 @@ var Collection = class extends Map { static defaultSort(firstValue, secondValue) { return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1; } + /** + * Creates a Collection from a list of entries. + * + * @param entries - The list of entries + * @param combine - Function to combine an existing entry with a new one + * @example + * ```ts + * Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y); + * // returns Collection { "a" => 3, "b" => 2 } + * ``` + */ static combineEntries(entries, combine) { const coll = new Collection(); - for (const [k, v] of entries) { - if (coll.has(k)) { - coll.set(k, combine(coll.get(k), v, k)); + for (const [key, value] of entries) { + if (coll.has(key)) { + coll.set(key, combine(coll.get(key), value, key)); } else { - coll.set(k, v); + coll.set(key, value); } } return coll; @@ -379,7 +539,7 @@ var Collection = class extends Map { __name(Collection, "Collection"); // src/index.ts -var version = "1.3.0"; +var version = "1.5.1"; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Collection, diff --git a/node_modules/@discordjs/collection/dist/index.js.map b/node_modules/@discordjs/collection/dist/index.js.map index 2f95d14..dee559b 100644 --- a/node_modules/@discordjs/collection/dist/index.js.map +++ b/node_modules/@discordjs/collection/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/collection.ts"],"sourcesContent":["export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.3.0';\n","/* eslint-disable id-length */\n/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((k) => super.has(k));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((k) => super.has(k));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (typeof amount === 'undefined') return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (typeof amount === 'undefined') return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (typeof amount === 'undefined') return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (typeof amount === 'undefined') return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tif (typeof initialValue !== 'undefined') {\n\t\t\taccumulator = initialValue;\n\t\t\tfor (const [key, val] of this) accumulator = fn(accumulator, val, key, this);\n\t\t\treturn accumulator;\n\t\t}\n\n\t\tlet first = true;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (first) {\n\t\t\t\taccumulator = val as unknown as T;\n\t\t\t\tfirst = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taccumulator = fn(accumulator, val, key, this);\n\t\t}\n\n\t\t// No items iterated.\n\t\tif (first) {\n\t\t\tthrow new TypeError('Reduce of empty collection with no initial value');\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tthis.forEach(fn as (value: V, key: K, map: Map) => void, thisArg);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [k, v] of entries) {\n\t\t\tsuper.set(k, v);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of other) {\n\t\t\tif (this.has(k) && Object.is(v, this.get(k))) {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of this) {\n\t\t\tif (!other.has(k) || !Object.is(v, other.get(k))) {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of other) {\n\t\t\tif (!this.has(k)) coll.set(k, v);\n\t\t}\n\n\t\tfor (const [k, v] of this) {\n\t\t\tif (!other.has(k)) coll.set(k, v);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\t\tfor (const k of keys) {\n\t\t\tconst hasInSelf = this.has(k);\n\t\t\tconst hasInOther = other.has(k);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst r = whenInBoth(this.get(k)!, other.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst r = whenInSelf(this.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst r = whenInOther(other.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [k, v] of entries) {\n\t\t\tif (coll.has(k)) {\n\t\t\t\tcoll.set(k, combine(coll.get(k)!, v, k));\n\t\t\t} else {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsCO,IAAM,aAAN,cAA+B,IAAU;AAAA,EAWxC,OAAO,KAAQ,uBAA2D;AAChF,QAAI,KAAK,IAAI,GAAG;AAAG,aAAO,KAAK,IAAI,GAAG;AACtC,QAAI,OAAO,0BAA0B;AAAY,YAAM,IAAI,UAAU,GAAG,yCAAyC;AACjH,UAAM,eAAe,sBAAsB,KAAK,IAAI;AACpD,SAAK,IAAI,KAAK,YAAY;AAC1B,WAAO;AAAA,EACR;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,MAAM,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAAA,EACtC;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,KAAK,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAAA,EACrC;AAAA,EAUO,MAAM,QAAsC;AAClD,QAAI,OAAO,WAAW;AAAa,aAAO,KAAK,OAAO,EAAE,KAAK,EAAE;AAC/D,QAAI,SAAS;AAAG,aAAO,KAAK,KAAK,SAAS,EAAE;AAC5C,aAAS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AI,GAAG,EAAE,KAAK;AAAA,MAChC,WAAW,YAAY;AACtB,cAAM,IAAI,YAAY,MAAM,IAAI,CAAC,GAAI,CAAC;AACtC,YAAI,EAAE;AAAM,eAAK,IAAI,GAAG,EAAE,KAAK;AAAA,MAChC;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AAAA,EAeO,OAAO,kBAAoC,WAAW,aAAa;AACzE,WAAO,IAAI,KAAK,YAAY,OAAO,SAAS,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI,IAAI,OAAO,gBAAgB,IAAI,IAAI,IAAI,EAAE,CAAC;AAAA,EAC3G;AAAA,EAEO,SAAS;AAEf,WAAO,CAAC,GAAG,KAAK,OAAO,CAAC;AAAA,EACzB;AAAA,EAEA,OAAe,YAAe,YAAe,aAAwB;AACpE,WAAO,OAAO,aAAa,WAAW,KAAK,OAAO,eAAe,WAAW,IAAI;AAAA,EACjF;AAAA,EAaA,OAAc,eACb,SACA,SACmB;AACnB,UAAM,OAAO,IAAI,WAAiB;AAClC,eAAW,CAAC,GAAG,CAAC,KAAK,SAAS;AAC7B,UAAI,KAAK,IAAI,CAAC,GAAG;AAChB,aAAK,IAAI,GAAG,QAAQ,KAAK,IAAI,CAAC,GAAI,GAAG,CAAC,CAAC;AAAA,MACxC,OAAO;AACN,aAAK,IAAI,GAAG,CAAC;AAAA,MACd;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AArxBa;;;AD9BN,IAAM,UAAkB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/collection.ts"],"sourcesContent":["export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.5.1' as string;\n","/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((key) => super.has(key));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((key) => super.has(key));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (amount === undefined) return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (amount === undefined) return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tif (initialValue !== undefined) {\n\t\t\taccumulator = initialValue;\n\t\t\tfor (const [key, val] of this) accumulator = fn(accumulator, val, key, this);\n\t\t\treturn accumulator;\n\t\t}\n\n\t\tlet first = true;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (first) {\n\t\t\t\taccumulator = val as unknown as T;\n\t\t\t\tfirst = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taccumulator = fn(accumulator, val, key, this);\n\t\t}\n\n\t\t// No items iterated.\n\t\tif (first) {\n\t\t\tthrow new TypeError('Reduce of empty collection with no initial value');\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\n\t\tfor (const [key, value] of this) {\n\t\t\tfn(value, key, this);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [key, value] of entries) {\n\t\t\tsuper.set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (this.has(key) && Object.is(value, this.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key) || !Object.is(value, other.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (!this.has(key)) coll.set(key, value);\n\t\t}\n\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key)) coll.set(key, value);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\n\t\tfor (const key of keys) {\n\t\t\tconst hasInSelf = this.has(key);\n\t\t\tconst hasInOther = other.has(key);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst result = whenInBoth(this.get(key)!, other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst result = whenInSelf(this.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst result = whenInOther(other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (coll.has(key)) {\n\t\t\t\tcoll.set(key, combine(coll.get(key)!, value, key));\n\t\t\t} else {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondVal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AiB;AAClC,eAAW,CAAC,KAAK,KAAK,KAAK,SAAS;AACnC,UAAI,KAAK,IAAI,GAAG,GAAG;AAClB,aAAK,IAAI,KAAK,QAAQ,KAAK,IAAI,GAAG,GAAI,OAAO,GAAG,CAAC;AAAA,MAClD,OAAO;AACN,aAAK,IAAI,KAAK,KAAK;AAAA,MACpB;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AA1xBa;;;AD9BN,IAAM,UAAU;","names":[]} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/dist/index.mjs b/node_modules/@discordjs/collection/dist/index.mjs index 356e945..e968033 100644 --- a/node_modules/@discordjs/collection/dist/index.mjs +++ b/node_modules/@discordjs/collection/dist/index.mjs @@ -3,6 +3,16 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable: // src/collection.ts var Collection = class extends Map { + /** + * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator. + * + * @param key - The key to get if it exists, or set otherwise + * @param defaultValueGenerator - A function that generates the default value + * @example + * ```ts + * collection.ensure(guildId, () => defaultGuildConfig); + * ``` + */ ensure(key, defaultValueGenerator) { if (this.has(key)) return this.get(key); @@ -12,14 +22,26 @@ var Collection = class extends Map { this.set(key, defaultValue); return defaultValue; } + /** + * Checks if all of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if all of the elements exist, `false` if at least one does not exist. + */ hasAll(...keys) { - return keys.every((k) => super.has(k)); + return keys.every((key) => super.has(key)); } + /** + * Checks if any of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if any of the elements exist, `false` if none exist. + */ hasAny(...keys) { - return keys.some((k) => super.has(k)); + return keys.some((key) => super.has(key)); } first(amount) { - if (typeof amount === "undefined") + if (amount === void 0) return this.values().next().value; if (amount < 0) return this.last(amount * -1); @@ -28,7 +50,7 @@ var Collection = class extends Map { return Array.from({ length: amount }, () => iter.next().value); } firstKey(amount) { - if (typeof amount === "undefined") + if (amount === void 0) return this.keys().next().value; if (amount < 0) return this.lastKey(amount * -1); @@ -38,7 +60,7 @@ var Collection = class extends Map { } last(amount) { const arr = [...this.values()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[arr.length - 1]; if (amount < 0) return this.first(amount * -1); @@ -48,7 +70,7 @@ var Collection = class extends Map { } lastKey(amount) { const arr = [...this.keys()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[arr.length - 1]; if (amount < 0) return this.firstKey(amount * -1); @@ -56,11 +78,25 @@ var Collection = class extends Map { return []; return arr.slice(-amount); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the item at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the element to obtain + */ at(index) { index = Math.floor(index); const arr = [...this.values()]; return arr.at(index); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the key at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the key to obtain + */ keyAt(index) { index = Math.floor(index); const arr = [...this.keys()]; @@ -68,7 +104,7 @@ var Collection = class extends Map { } random(amount) { const arr = [...this.values()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[Math.floor(Math.random() * arr.length)]; if (!arr.length || !amount) return []; @@ -79,7 +115,7 @@ var Collection = class extends Map { } randomKey(amount) { const arr = [...this.keys()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[Math.floor(Math.random() * arr.length)]; if (!arr.length || !amount) return []; @@ -88,6 +124,10 @@ var Collection = class extends Map { () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0] ); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()} + * but returns a Collection instead of an Array. + */ reverse() { const entries = [...this.entries()].reverse(); this.clear(); @@ -98,7 +138,7 @@ var Collection = class extends Map { find(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -109,7 +149,7 @@ var Collection = class extends Map { findKey(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -120,7 +160,7 @@ var Collection = class extends Map { sweep(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const previousSize = this.size; for (const [key, val] of this) { @@ -132,7 +172,7 @@ var Collection = class extends Map { filter(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const results = new this.constructor[Symbol.species](); for (const [key, val] of this) { @@ -144,7 +184,7 @@ var Collection = class extends Map { partition(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const results = [ new this.constructor[Symbol.species](), @@ -166,7 +206,7 @@ var Collection = class extends Map { map(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const iter = this.entries(); return Array.from({ length: this.size }, () => { @@ -177,7 +217,7 @@ var Collection = class extends Map { mapValues(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const coll = new this.constructor[Symbol.species](); for (const [key, val] of this) @@ -187,7 +227,7 @@ var Collection = class extends Map { some(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -198,7 +238,7 @@ var Collection = class extends Map { every(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (!fn(val, key, this)) @@ -206,11 +246,23 @@ var Collection = class extends Map { } return true; } + /** + * Applies a function to produce a single value. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}. + * + * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, + * and `collection` + * @param initialValue - Starting value for the accumulator + * @example + * ```ts + * collection.reduce((acc, guild) => acc + guild.memberCount, 0); + * ``` + */ reduce(fn, initialValue) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); let accumulator; - if (typeof initialValue !== "undefined") { + if (initialValue !== void 0) { accumulator = initialValue; for (const [key, val] of this) accumulator = fn(accumulator, val, key, this); @@ -233,20 +285,41 @@ var Collection = class extends Map { each(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - this.forEach(fn, thisArg); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, value] of this) { + fn(value, key, this); + } return this; } tap(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); fn(this); return this; } + /** + * Creates an identical shallow copy of this collection. + * + * @example + * ```ts + * const newColl = someColl.clone(); + * ``` + */ clone() { return new this.constructor[Symbol.species](this); } + /** + * Combines this collection with others into a new collection. None of the source collections are modified. + * + * @param collections - Collections to merge + * @example + * ```ts + * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); + * ``` + */ concat(...collections) { const newColl = this.clone(); for (const coll of collections) { @@ -255,6 +328,14 @@ var Collection = class extends Map { } return newColl; } + /** + * Checks if this collection shares identical items with another. + * This is different to checking for equality using equal-signs, because + * the collections may be different objects, but contain the same data. + * + * @param collection - Collection to compare with + * @returns Whether the collections have identical contents + */ equals(collection) { if (!collection) return false; @@ -269,67 +350,135 @@ var Collection = class extends Map { } return true; } + /** + * The sort method sorts the items of a collection in place and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element. + * @example + * ```ts + * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ sort(compareFunction = Collection.defaultSort) { const entries = [...this.entries()]; entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0])); super.clear(); - for (const [k, v] of entries) { - super.set(k, v); + for (const [key, value] of entries) { + super.set(key, value); } return this; } + /** + * The intersect method returns a new structure containing items where the keys and values are present in both original structures. + * + * @param other - The other Collection to filter against + */ intersect(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of other) { - if (this.has(k) && Object.is(v, this.get(k))) { - coll.set(k, v); + for (const [key, value] of other) { + if (this.has(key) && Object.is(value, this.get(key))) { + coll.set(key, value); } } return coll; } + /** + * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other. + * + * @param other - The other Collection to filter against + */ subtract(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of this) { - if (!other.has(k) || !Object.is(v, other.get(k))) { - coll.set(k, v); + for (const [key, value] of this) { + if (!other.has(key) || !Object.is(value, other.get(key))) { + coll.set(key, value); } } return coll; } + /** + * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other. + * + * @param other - The other Collection to filter against + */ difference(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of other) { - if (!this.has(k)) - coll.set(k, v); + for (const [key, value] of other) { + if (!this.has(key)) + coll.set(key, value); } - for (const [k, v] of this) { - if (!other.has(k)) - coll.set(k, v); + for (const [key, value] of this) { + if (!other.has(key)) + coll.set(key, value); } return coll; } + /** + * Merges two Collections together into a new Collection. + * + * @param other - The other Collection to merge with + * @param whenInSelf - Function getting the result if the entry only exists in this Collection + * @param whenInOther - Function getting the result if the entry only exists in the other Collection + * @param whenInBoth - Function getting the result if the entry exists in both Collections + * @example + * ```ts + * // Sums up the entries in two collections. + * coll.merge( + * other, + * x => ({ keep: true, value: x }), + * y => ({ keep: true, value: y }), + * (x, y) => ({ keep: true, value: x + y }), + * ); + * ``` + * @example + * ```ts + * // Intersects two collections in a left-biased manner. + * coll.merge( + * other, + * x => ({ keep: false }), + * y => ({ keep: false }), + * (x, _) => ({ keep: true, value: x }), + * ); + * ``` + */ merge(other, whenInSelf, whenInOther, whenInBoth) { const coll = new this.constructor[Symbol.species](); const keys = /* @__PURE__ */ new Set([...this.keys(), ...other.keys()]); - for (const k of keys) { - const hasInSelf = this.has(k); - const hasInOther = other.has(k); + for (const key of keys) { + const hasInSelf = this.has(key); + const hasInOther = other.has(key); if (hasInSelf && hasInOther) { - const r = whenInBoth(this.get(k), other.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInBoth(this.get(key), other.get(key), key); + if (result.keep) + coll.set(key, result.value); } else if (hasInSelf) { - const r = whenInSelf(this.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInSelf(this.get(key), key); + if (result.keep) + coll.set(key, result.value); } else if (hasInOther) { - const r = whenInOther(other.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInOther(other.get(key), key); + if (result.keep) + coll.set(key, result.value); } } return coll; } + /** + * The sorted method sorts the items of a collection and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, + * according to the string conversion of each element. + * @example + * ```ts + * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ sorted(compareFunction = Collection.defaultSort) { return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk)); } @@ -339,13 +488,24 @@ var Collection = class extends Map { static defaultSort(firstValue, secondValue) { return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1; } + /** + * Creates a Collection from a list of entries. + * + * @param entries - The list of entries + * @param combine - Function to combine an existing entry with a new one + * @example + * ```ts + * Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y); + * // returns Collection { "a" => 3, "b" => 2 } + * ``` + */ static combineEntries(entries, combine) { const coll = new Collection(); - for (const [k, v] of entries) { - if (coll.has(k)) { - coll.set(k, combine(coll.get(k), v, k)); + for (const [key, value] of entries) { + if (coll.has(key)) { + coll.set(key, combine(coll.get(key), value, key)); } else { - coll.set(k, v); + coll.set(key, value); } } return coll; @@ -354,7 +514,7 @@ var Collection = class extends Map { __name(Collection, "Collection"); // src/index.ts -var version = "1.3.0"; +var version = "1.5.1"; export { Collection, version diff --git a/node_modules/@discordjs/collection/dist/index.mjs.map b/node_modules/@discordjs/collection/dist/index.mjs.map index be1999d..b736a28 100644 --- a/node_modules/@discordjs/collection/dist/index.mjs.map +++ b/node_modules/@discordjs/collection/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/collection.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable id-length */\n/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((k) => super.has(k));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((k) => super.has(k));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (typeof amount === 'undefined') return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (typeof amount === 'undefined') return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (typeof amount === 'undefined') return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (typeof amount === 'undefined') return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tif (typeof initialValue !== 'undefined') {\n\t\t\taccumulator = initialValue;\n\t\t\tfor (const [key, val] of this) accumulator = fn(accumulator, val, key, this);\n\t\t\treturn accumulator;\n\t\t}\n\n\t\tlet first = true;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (first) {\n\t\t\t\taccumulator = val as unknown as T;\n\t\t\t\tfirst = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taccumulator = fn(accumulator, val, key, this);\n\t\t}\n\n\t\t// No items iterated.\n\t\tif (first) {\n\t\t\tthrow new TypeError('Reduce of empty collection with no initial value');\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tthis.forEach(fn as (value: V, key: K, map: Map) => void, thisArg);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [k, v] of entries) {\n\t\t\tsuper.set(k, v);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of other) {\n\t\t\tif (this.has(k) && Object.is(v, this.get(k))) {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of this) {\n\t\t\tif (!other.has(k) || !Object.is(v, other.get(k))) {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of other) {\n\t\t\tif (!this.has(k)) coll.set(k, v);\n\t\t}\n\n\t\tfor (const [k, v] of this) {\n\t\t\tif (!other.has(k)) coll.set(k, v);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\t\tfor (const k of keys) {\n\t\t\tconst hasInSelf = this.has(k);\n\t\t\tconst hasInOther = other.has(k);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst r = whenInBoth(this.get(k)!, other.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst r = whenInSelf(this.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst r = whenInOther(other.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [k, v] of entries) {\n\t\t\tif (coll.has(k)) {\n\t\t\t\tcoll.set(k, combine(coll.get(k)!, v, k));\n\t\t\t} else {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;\n","export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.3.0';\n"],"mappings":";;;;AAsCO,IAA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AM,OAAO,IAAI,WAAiB;AAClC,eAAW,CAAC,GAAG,CAAC,KAAK,SAAS;AAC7B,UAAI,KAAK,IAAI,CAAC,GAAG;AAChB,aAAK,IAAI,GAAG,QAAQ,KAAK,IAAI,CAAC,GAAI,GAAG,CAAC,CAAC;AAAA,MACxC,OAAO;AACN,aAAK,IAAI,GAAG,CAAC;AAAA,MACd;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AArxBa;;;AC9BN,IAAM,UAAkB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/collection.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((key) => super.has(key));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((key) => super.has(key));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (amount === undefined) return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (amount === undefined) return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tif (initialValue !== undefined) {\n\t\t\taccumulator = initialValue;\n\t\t\tfor (const [key, val] of this) accumulator = fn(accumulator, val, key, this);\n\t\t\treturn accumulator;\n\t\t}\n\n\t\tlet first = true;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (first) {\n\t\t\t\taccumulator = val as unknown as T;\n\t\t\t\tfirst = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taccumulator = fn(accumulator, val, key, this);\n\t\t}\n\n\t\t// No items iterated.\n\t\tif (first) {\n\t\t\tthrow new TypeError('Reduce of empty collection with no initial value');\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\n\t\tfor (const [key, value] of this) {\n\t\t\tfn(value, key, this);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [key, value] of entries) {\n\t\t\tsuper.set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (this.has(key) && Object.is(value, this.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key) || !Object.is(value, other.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (!this.has(key)) coll.set(key, value);\n\t\t}\n\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key)) coll.set(key, value);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\n\t\tfor (const key of keys) {\n\t\t\tconst hasInSelf = this.has(key);\n\t\t\tconst hasInOther = other.has(key);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst result = whenInBoth(this.get(key)!, other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst result = whenInSelf(this.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst result = whenInOther(other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (coll.has(key)) {\n\t\t\t\tcoll.set(key, combine(coll.get(key)!, value, key));\n\t\t\t} else {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;\n","export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.5.1' as string;\n"],"mappings":";;;;AAqCO,IAAM,aAAN,cAA+B,IAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWxC,OAAO,KAAQ,uBAA2D;AAChF,QAAI,KAAK,IAAI,GAAG;AAAG,aAAO,KAAK,IAAI,GAAG;AACtC,QAAI,OAAO,0BAA0B;AAAY,YAAM,IAAI,UAAU,GAAG,yCAAyC;AACjH,UAAM,eAAe,sBAAsB,KAAK,IAAI;AACpD,SAAK,IAAI,KAAK,YAAY;AAC1B,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,MAAM,CAAC,QAAQ,MAAM,IAAI,GAAG,CAAC;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,KA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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeO,OAAO,kBAAoC,WAAW,aAAa;AACzE,WAAO,IAAI,KAAK,YAAY,OAAO,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI,IAAI,OAAO,gBAAgB,IAAI,IAAI,IAAI,EAAE,CAAC;AAAA,EAC3G;AAAA,EAEO,SAAS;AAEf,WAAO,CAAC,GAAG,KAAK,OAAO,CAAC;AAAA,EACzB;AAAA,EAEA,OAAe,YAAe,YAAe,aAAwB;AACpE,WAAO,OAAO,aAAa,WAAW,KAAK,OAAO,eAAe,WAAW,IAAI;AAAA,EACjF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,OAAc,eACb,SACA,SACmB;AACnB,UAAM,OAAO,IAAI,WAAiB;AAClC,eAAW,CAAC,KAAK,KAAK,KAAK,SAAS;AACnC,UAAI,KAAK,IAAI,GAAG,GAAG;AAClB,aAAK,IAAI,KAAK,QAAQ,KAAK,IAAI,GAAG,GAAI,OAAO,GAAG,CAAC;AAAA,MAClD,OAAO;AACN,aAAK,IAAI,KAAK,KAAK;AAAA,MACpB;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AA1xBa;;;AC9BN,IAAM,UAAU;","names":[]} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/package.json b/node_modules/@discordjs/collection/package.json index d79ef85..adbf426 100644 --- a/node_modules/@discordjs/collection/package.json +++ b/node_modules/@discordjs/collection/package.json @@ -1,14 +1,15 @@ { "name": "@discordjs/collection", - "version": "1.3.0", + "version": "1.5.1", "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": "api-extractor run --local", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", "prepack": "yarn lint && yarn test && yarn build", "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/collection/*'", "release": "cliff-jumper" @@ -17,9 +18,9 @@ "module": "./dist/index.mjs", "types": "./dist/index.d.ts", "exports": { + "types": "./dist/index.d.ts", "import": "./dist/index.mjs", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" + "require": "./dist/index.js" }, "directories": { "lib": "src", @@ -43,26 +44,27 @@ ], "repository": { "type": "git", - "url": "git+https://github.com/discordjs/discord.js.git" + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/collection" }, "bugs": { "url": "https://github.com/discordjs/discord.js/issues" }, "homepage": "https://discord.js.org", "devDependencies": { - "@favware/cliff-jumper": "^1.9.0", - "@microsoft/api-extractor": "^7.33.6", - "@types/node": "16.18.3", - "@vitest/coverage-c8": "^0.25.3", + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.6", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.30.1", "cross-env": "^7.0.3", - "esbuild-plugin-version-injector": "^1.0.2", - "eslint": "^8.28.0", - "eslint-config-neon": "^0.1.40", - "eslint-formatter-pretty": "^4.1.0", - "prettier": "^2.8.0", - "tsup": "^6.5.0", - "typescript": "^4.9.3", - "vitest": "^0.25.3" + "esbuild-plugin-version-injector": "^1.1.0", + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.42", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsup": "^6.7.0", + "typescript": "^5.0.4", + "vitest": "^0.29.8" }, "engines": { "node": ">=16.9.0" diff --git a/node_modules/@discordjs/formatters/CHANGELOG.md b/node_modules/@discordjs/formatters/CHANGELOG.md new file mode 100644 index 0000000..0eb93f0 --- /dev/null +++ b/node_modules/@discordjs/formatters/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@discordjs/formatters@0.3.1](https://github.com/discordjs/discord.js/compare/@discordjs/formatters@0.3.0...@discordjs/formatters@0.3.1) - (2023-05-01) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) +- **formatters:** Enhance the documentation (#9364) ([23e0ac5](https://github.com/discordjs/discord.js/commit/23e0ac56f456c39d925e2644ec3ca209d4410a99)) + +# [@discordjs/formatters@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/formatters@0.2.0...@discordjs/formatters@0.3.0) - (2023-04-01) + +## Bug Fixes + +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/formatters@0.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/formatters@0.1.0...@discordjs/formatters@0.2.0) - (2023-03-12) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) + +## Refactor + +- Compare with `undefined` directly (#9191) ([869153c](https://github.com/discordjs/discord.js/commit/869153c3fdf155783e7c0ecebd3627b087c3a026)) +- Moved the escapeX functions from discord.js to @discord.js/formatters (#8957) ([13ce78a](https://github.com/discordjs/discord.js/commit/13ce78af6e3aedc793f53a099a6a615df44311f7)) + +## Styling + +- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b)) + +# [@discordjs/formatters@0.1.0](https://github.com/discordjs/discord.js/tree/@discordjs/formatters@0.1.0) - (2022-12-16) + +## Features + +- Add `@discordjs/formatters` (#8889) ([3fca638](https://github.com/discordjs/discord.js/commit/3fca638a8470dcea2f79ddb9f18526dbc0017c88)) + diff --git a/node_modules/@discordjs/formatters/LICENSE b/node_modules/@discordjs/formatters/LICENSE new file mode 100644 index 0000000..e2baac1 --- /dev/null +++ b/node_modules/@discordjs/formatters/LICENSE @@ -0,0 +1,191 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2021 Noel Buechler + Copyright 2021 Vlad Frangu + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@discordjs/formatters/README.md b/node_modules/@discordjs/formatters/README.md new file mode 100644 index 0000000..92798d6 --- /dev/null +++ b/node_modules/@discordjs/formatters/README.md @@ -0,0 +1,80 @@ +
+
+

+ discord.js +

+
+

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

+

+ Vercel +

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

+## About + +`@discordjs/rest` is a module that allows you to easily make REST requests to the Discord API. + ## Installation **Node.js 16.9.0 or newer is required.** -```sh-session +```sh npm install @discordjs/rest yarn add @discordjs/rest pnpm add @discordjs/rest @@ -30,7 +34,7 @@ pnpm add @discordjs/rest Install all required dependencies: -```sh-session +```sh npm install @discordjs/rest discord-api-types yarn add @discordjs/rest discord-api-types pnpm add @discordjs/rest discord-api-types @@ -80,7 +84,7 @@ try { - [Website][website] ([source][website-source]) - [Documentation][documentation] - [Guide][guide] ([source][guide-source]) - See also the [Update Guide][guide-update], including updated and removed items in the library. + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. - [discord.js Discord server][discord] - [Discord API Discord server][discord-api] - [GitHub][source] @@ -95,12 +99,11 @@ See [the contribution guide][contributing] if you'd like to submit a PR. ## Help -If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle -nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. -[website]: https://discord.js.org/ +[website]: https://discord.js.org [website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website -[documentation]: https://discord.js.org/#/docs/rest +[documentation]: https://discord.js.org/docs/packages/rest/stable [guide]: https://discordjs.guide/ [guide-source]: https://github.com/discordjs/guide [guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html diff --git a/node_modules/@discordjs/rest/dist/index.d.ts b/node_modules/@discordjs/rest/dist/index.d.ts index 3536eda..5077622 100644 --- a/node_modules/@discordjs/rest/dist/index.d.ts +++ b/node_modules/@discordjs/rest/dist/index.d.ts @@ -4,7 +4,11 @@ import { EventEmitter } from 'node:events'; import { URLSearchParams } from 'node:url'; import { Collection } from '@discordjs/collection'; -declare const DefaultUserAgent = "DiscordBot (https://discord.js.org, [VI]{{inject}}[/VI])"; +declare const DefaultUserAgent: `DiscordBot (https://discord.js.org, ${string})`; +/** + * The default string to append onto the user agent. + */ +declare const DefaultUserAgentAppendix: string; declare const DefaultRestOptions: { readonly agent: Agent; readonly api: "https://discord.com/api"; @@ -17,7 +21,7 @@ declare const DefaultRestOptions: { readonly rejectOnRateLimit: null; readonly retries: 3; readonly timeout: 15000; - readonly userAgentAppendix: `Node.js ${string}`; + readonly userAgentAppendix: string; readonly version: "10"; readonly hashSweepInterval: 14400000; readonly hashLifetime: 86400000; @@ -26,7 +30,7 @@ declare const DefaultRestOptions: { /** * The events that the REST manager emits */ -declare const enum RESTEvents { +declare enum RESTEvents { Debug = "restDebug", HandlerSweep = "handlerSweep", HashSweep = "hashSweep", @@ -35,11 +39,15 @@ declare const enum RESTEvents { Response = "response" } declare const ALLOWED_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif"]; -declare const ALLOWED_STICKER_EXTENSIONS: readonly ["png", "json"]; +declare const ALLOWED_STICKER_EXTENSIONS: readonly ["png", "json", "gif"]; declare const ALLOWED_SIZES: readonly [16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; -type ImageExtension = typeof ALLOWED_EXTENSIONS[number]; -type StickerExtension = typeof ALLOWED_STICKER_EXTENSIONS[number]; -type ImageSize = typeof ALLOWED_SIZES[number]; +type ImageExtension = (typeof ALLOWED_EXTENSIONS)[number]; +type StickerExtension = (typeof ALLOWED_STICKER_EXTENSIONS)[number]; +type ImageSize = (typeof ALLOWED_SIZES)[number]; +declare const OverwrittenMimeTypes: { + readonly 'image/apng': "image/png"; +}; +declare const BurstHandlerMajorIdKey = "burst"; /** * The options used for image URLs @@ -198,6 +206,8 @@ declare class CDN { * * @param stickerId - The sticker id * @param extension - The extension of the sticker + * @privateRemarks + * Stickers cannot have a `.webp` extension, so we default to a `.png` */ sticker(stickerId: string, extension?: StickerExtension): string; /** @@ -355,7 +365,7 @@ interface RESTOptions { /** * Extra information to add to the user agent * - * @defaultValue `Node.js ${process.version}` + * @defaultValue DefaultUserAgentAppendix */ userAgentAppendix: string; /** @@ -627,7 +637,7 @@ interface RequestHeaders { /** * Possible API methods to be used when doing requests */ -declare const enum RequestMethod { +declare enum RequestMethod { Delete = "DELETE", Get = "GET", Patch = "PATCH", @@ -862,4 +872,4 @@ declare function parseResponse(res: Dispatcher.ResponseData): Promise; */ declare const version: string; -export { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, APIRequest, BaseImageURLOptions, CDN, DefaultRestOptions, DefaultUserAgent, DiscordAPIError, DiscordErrorData, HTTPError, HandlerRequestData, HashData, ImageExtension, ImageSize, ImageURLOptions, InternalRequest, InvalidRequestWarningData, MakeURLOptions, OAuthErrorData, REST, RESTEvents, RESTOptions, RateLimitData, RateLimitError, RateLimitQueueFilter, RawFile, RequestBody, RequestData, RequestHeaders, RequestManager, RequestMethod, RequestOptions, RestEvents, RouteData, RouteLike, StickerExtension, makeURLSearchParams, parseResponse, version }; +export { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, APIRequest, BaseImageURLOptions, BurstHandlerMajorIdKey, CDN, DefaultRestOptions, DefaultUserAgent, DefaultUserAgentAppendix, DiscordAPIError, DiscordErrorData, HTTPError, HandlerRequestData, HashData, ImageExtension, ImageSize, ImageURLOptions, InternalRequest, InvalidRequestWarningData, MakeURLOptions, OAuthErrorData, OverwrittenMimeTypes, REST, RESTEvents, RESTOptions, RateLimitData, RateLimitError, RateLimitQueueFilter, RawFile, RequestBody, RequestData, RequestHeaders, RequestManager, RequestMethod, RequestOptions, RestEvents, RouteData, RouteLike, StickerExtension, makeURLSearchParams, parseResponse, version }; diff --git a/node_modules/@discordjs/rest/dist/index.js b/node_modules/@discordjs/rest/dist/index.js index 513e9dc..f4e24b2 100644 --- a/node_modules/@discordjs/rest/dist/index.js +++ b/node_modules/@discordjs/rest/dist/index.js @@ -19,6 +19,10 @@ var __copyProps = (to, from, except, desc) => { return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); @@ -30,11 +34,14 @@ __export(src_exports, { ALLOWED_EXTENSIONS: () => ALLOWED_EXTENSIONS, ALLOWED_SIZES: () => ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS: () => ALLOWED_STICKER_EXTENSIONS, + BurstHandlerMajorIdKey: () => BurstHandlerMajorIdKey, CDN: () => CDN, DefaultRestOptions: () => DefaultRestOptions, DefaultUserAgent: () => DefaultUserAgent, + DefaultUserAgentAppendix: () => DefaultUserAgentAppendix, DiscordAPIError: () => DiscordAPIError, HTTPError: () => HTTPError, + OverwrittenMimeTypes: () => OverwrittenMimeTypes, REST: () => REST, RESTEvents: () => RESTEvents, RateLimitError: () => RateLimitError, @@ -53,7 +60,8 @@ var import_node_url = require("url"); var import_node_process = __toESM(require("process")); var import_v10 = require("discord-api-types/v10"); var import_undici = require("undici"); -var DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.5.0)`; +var DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.7.1)`; +var DefaultUserAgentAppendix = import_node_process.default.release?.name === "node" ? `Node.js/${import_node_process.default.version}` : ""; var DefaultRestOptions = { get agent() { return new import_undici.Agent({ @@ -72,11 +80,14 @@ var DefaultRestOptions = { rejectOnRateLimit: null, retries: 3, timeout: 15e3, - userAgentAppendix: `Node.js ${import_node_process.default.version}`, + userAgentAppendix: DefaultUserAgentAppendix, version: import_v10.APIVersion, hashSweepInterval: 144e5, + // 4 Hours hashLifetime: 864e5, + // 24 Hours handlerSweepInterval: 36e5 + // 1 Hour }; var RESTEvents = /* @__PURE__ */ ((RESTEvents2) => { RESTEvents2["Debug"] = "restDebug"; @@ -88,71 +99,204 @@ var RESTEvents = /* @__PURE__ */ ((RESTEvents2) => { return RESTEvents2; })(RESTEvents || {}); var ALLOWED_EXTENSIONS = ["webp", "png", "jpg", "jpeg", "gif"]; -var ALLOWED_STICKER_EXTENSIONS = ["png", "json"]; +var ALLOWED_STICKER_EXTENSIONS = ["png", "json", "gif"]; var ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; +var OverwrittenMimeTypes = { + // https://github.com/discordjs/discord.js/issues/8557 + "image/apng": "image/png" +}; +var BurstHandlerMajorIdKey = "burst"; // src/lib/CDN.ts var CDN = class { constructor(base = DefaultRestOptions.cdn) { this.base = base; } + /** + * Generates an app asset URL for a client's asset. + * + * @param clientId - The client id that has the asset + * @param assetHash - The hash provided by Discord for this asset + * @param options - Optional options for the asset + */ appAsset(clientId, assetHash, options) { return this.makeURL(`/app-assets/${clientId}/${assetHash}`, options); } + /** + * Generates an app icon URL for a client's icon. + * + * @param clientId - The client id that has the icon + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ appIcon(clientId, iconHash, options) { return this.makeURL(`/app-icons/${clientId}/${iconHash}`, options); } + /** + * Generates an avatar URL, e.g. for a user or a webhook. + * + * @param id - The id that has the icon + * @param avatarHash - The hash provided by Discord for this avatar + * @param options - Optional options for the avatar + */ avatar(id, avatarHash, options) { return this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options); } + /** + * Generates a banner URL, e.g. for a user or a guild. + * + * @param id - The id that has the banner splash + * @param bannerHash - The hash provided by Discord for this banner + * @param options - Optional options for the banner + */ banner(id, bannerHash, options) { return this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options); } + /** + * Generates an icon URL for a channel, e.g. a group DM. + * + * @param channelId - The channel id that has the icon + * @param iconHash - The hash provided by Discord for this channel + * @param options - Optional options for the icon + */ channelIcon(channelId, iconHash, options) { return this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options); } + /** + * Generates the default avatar URL for a discriminator. + * + * @param discriminator - The discriminator modulo 5 + */ defaultAvatar(discriminator) { return this.makeURL(`/embed/avatars/${discriminator}`, { extension: "png" }); } + /** + * Generates a discovery splash URL for a guild's discovery splash. + * + * @param guildId - The guild id that has the discovery splash + * @param splashHash - The hash provided by Discord for this splash + * @param options - Optional options for the splash + */ discoverySplash(guildId, splashHash, options) { return this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options); } + /** + * Generates an emoji's URL for an emoji. + * + * @param emojiId - The emoji id + * @param extension - The extension of the emoji + */ emoji(emojiId, extension) { return this.makeURL(`/emojis/${emojiId}`, { extension }); } + /** + * Generates a guild member avatar URL. + * + * @param guildId - The id of the guild + * @param userId - The id of the user + * @param avatarHash - The hash provided by Discord for this avatar + * @param options - Optional options for the avatar + */ guildMemberAvatar(guildId, userId, avatarHash, options) { return this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options); } + /** + * Generates a guild member banner URL. + * + * @param guildId - The id of the guild + * @param userId - The id of the user + * @param bannerHash - The hash provided by Discord for this banner + * @param options - Optional options for the banner + */ guildMemberBanner(guildId, userId, bannerHash, options) { return this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options); } + /** + * Generates an icon URL, e.g. for a guild. + * + * @param id - The id that has the icon splash + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ icon(id, iconHash, options) { return this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options); } + /** + * Generates a URL for the icon of a role + * + * @param roleId - The id of the role that has the icon + * @param roleIconHash - The hash provided by Discord for this role icon + * @param options - Optional options for the role icon + */ roleIcon(roleId, roleIconHash, options) { return this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options); } + /** + * Generates a guild invite splash URL for a guild's invite splash. + * + * @param guildId - The guild id that has the invite splash + * @param splashHash - The hash provided by Discord for this splash + * @param options - Optional options for the splash + */ splash(guildId, splashHash, options) { return this.makeURL(`/splashes/${guildId}/${splashHash}`, options); } - sticker(stickerId, extension) { - return this.makeURL(`/stickers/${stickerId}`, { - allowedExtensions: ALLOWED_STICKER_EXTENSIONS, - extension: extension ?? "png" - }); + /** + * Generates a sticker URL. + * + * @param stickerId - The sticker id + * @param extension - The extension of the sticker + * @privateRemarks + * Stickers cannot have a `.webp` extension, so we default to a `.png` + */ + sticker(stickerId, extension = "png") { + return this.makeURL(`/stickers/${stickerId}`, { allowedExtensions: ALLOWED_STICKER_EXTENSIONS, extension }); } + /** + * Generates a sticker pack banner URL. + * + * @param bannerId - The banner id + * @param options - Optional options for the banner + */ stickerPackBanner(bannerId, options) { return this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options); } + /** + * Generates a team icon URL for a team's icon. + * + * @param teamId - The team id that has the icon + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ teamIcon(teamId, iconHash, options) { return this.makeURL(`/team-icons/${teamId}/${iconHash}`, options); } + /** + * Generates a cover image for a guild scheduled event. + * + * @param scheduledEventId - The scheduled event id + * @param coverHash - The hash provided by discord for this cover image + * @param options - Optional options for the cover image + */ guildScheduledEventCover(scheduledEventId, coverHash, options) { return this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options); } + /** + * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`. + * + * @param route - The base cdn route + * @param hash - The hash provided by Discord for this icon + * @param options - Optional options for the link + */ dynamicMakeURL(route, hash, { forceStatic = false, ...options } = {}) { return this.makeURL(route, !forceStatic && hash.startsWith("a_") ? { ...options, extension: "gif" } : options); } + /** + * Constructs the URL for the resource + * + * @param route - The base cdn route + * @param options - The extension/size options for the link + */ makeURL(route, { allowedExtensions = ALLOWED_EXTENSIONS, extension = "webp", size } = {}) { extension = String(extension).toLowerCase(); if (!allowedExtensions.includes(extension)) { @@ -182,6 +326,14 @@ function isErrorResponse(error) { } __name(isErrorResponse, "isErrorResponse"); var DiscordAPIError = class extends Error { + /** + * @param rawError - The error reported by Discord + * @param code - The error code reported by Discord + * @param status - The status code of the response + * @param method - The method of the request that erred + * @param url - The url of the request that erred + * @param bodyData - The unparsed data for the request that errored + */ constructor(rawError, code, status, method, url, bodyData) { super(DiscordAPIError.getMessage(rawError)); this.rawError = rawError; @@ -192,6 +344,9 @@ var DiscordAPIError = class extends Error { this.requestBody = { files: bodyData.files, json: bodyData.body }; } requestBody; + /** + * The name of the error + */ get name() { return `${DiscordAPIError.name}[${this.code}]`; } @@ -229,6 +384,12 @@ __name(DiscordAPIError, "DiscordAPIError"); // src/lib/errors/HTTPError.ts var import_node_http = require("http"); var HTTPError = class extends Error { + /** + * @param status - The status code of the response + * @param method - The method of the request that erred + * @param url - The url of the request that erred + * @param bodyData - The unparsed data for the request that errored + */ constructor(status, method, url, bodyData) { super(import_node_http.STATUS_CODES[status]); this.status = status; @@ -262,6 +423,9 @@ var RateLimitError = class extends Error { this.majorParameter = majorParameter; this.global = global; } + /** + * The name of the error + */ get name() { return `${RateLimitError.name}[${this.route}]`; } @@ -277,11 +441,8 @@ var import_util = require("@discordjs/util"); var import_snowflake = require("@sapphire/snowflake"); var import_undici4 = require("undici"); -// src/lib/handlers/SequentialHandler.ts -var import_node_timers = require("timers"); +// src/lib/handlers/BurstHandler.ts var import_promises = require("timers/promises"); -var import_async_queue = require("@sapphire/async-queue"); -var import_undici3 = require("undici"); // src/lib/utils/utils.ts var import_node_buffer = require("buffer"); @@ -392,56 +553,293 @@ function shouldRetry(error) { return "code" in error && error.code === "ECONNRESET" || error.message.includes("ECONNRESET"); } __name(shouldRetry, "shouldRetry"); +async function onRateLimit(manager, rateLimitData) { + const { options } = manager; + if (!options.rejectOnRateLimit) + return; + const shouldThrow = typeof options.rejectOnRateLimit === "function" ? await options.rejectOnRateLimit(rateLimitData) : options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase())); + if (shouldThrow) { + throw new RateLimitError(rateLimitData); + } +} +__name(onRateLimit, "onRateLimit"); -// src/lib/handlers/SequentialHandler.ts +// src/lib/handlers/Shared.ts +var import_node_timers = require("timers"); +var import_undici3 = require("undici"); var invalidCount = 0; var invalidCountResetTime = null; -var SequentialHandler = class { +function incrementInvalidCount(manager) { + if (!invalidCountResetTime || invalidCountResetTime < Date.now()) { + invalidCountResetTime = Date.now() + 1e3 * 60 * 10; + invalidCount = 0; + } + invalidCount++; + const emitInvalid = manager.options.invalidRequestWarningInterval > 0 && invalidCount % manager.options.invalidRequestWarningInterval === 0; + if (emitInvalid) { + manager.emit("invalidRequestWarning" /* InvalidRequestWarning */, { + count: invalidCount, + remainingTime: invalidCountResetTime - Date.now() + }); + } +} +__name(incrementInvalidCount, "incrementInvalidCount"); +async function makeNetworkRequest(manager, routeId, url, options, requestData, retries) { + const controller = new AbortController(); + const timeout = (0, import_node_timers.setTimeout)(() => controller.abort(), manager.options.timeout).unref(); + if (requestData.signal) { + const signal = requestData.signal; + if (signal.aborted) + controller.abort(); + else + signal.addEventListener("abort", () => controller.abort()); + } + let res; + try { + res = await (0, import_undici3.request)(url, { ...options, signal: controller.signal }); + } catch (error) { + if (!(error instanceof Error)) + throw error; + if (shouldRetry(error) && retries !== manager.options.retries) { + return null; + } + throw error; + } finally { + (0, import_node_timers.clearTimeout)(timeout); + } + if (manager.listenerCount("response" /* Response */)) { + manager.emit( + "response" /* Response */, + { + method: options.method ?? "get", + path: routeId.original, + route: routeId.bucketRoute, + options, + data: requestData, + retries + }, + { ...res } + ); + } + return res; +} +__name(makeNetworkRequest, "makeNetworkRequest"); +async function handleErrors(manager, res, method, url, requestData, retries) { + const status = res.statusCode; + if (status >= 500 && status < 600) { + if (retries !== manager.options.retries) { + return null; + } + throw new HTTPError(status, method, url, requestData); + } else { + if (status >= 400 && status < 500) { + if (status === 401 && requestData.auth) { + manager.setToken(null); + } + const data = await parseResponse(res); + throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData); + } + return res; + } +} +__name(handleErrors, "handleErrors"); + +// src/lib/handlers/BurstHandler.ts +var BurstHandler = class { + /** + * @param manager - The request manager + * @param hash - The hash that this RequestHandler handles + * @param majorParameter - The major parameter for this handler + */ constructor(manager, hash, majorParameter) { this.manager = manager; this.hash = hash; this.majorParameter = majorParameter; this.id = `${hash}:${majorParameter}`; } + /** + * {@inheritdoc IHandler.id} + */ id; - reset = -1; - remaining = 1; - limit = Number.POSITIVE_INFINITY; - #asyncQueue = new import_async_queue.AsyncQueue(); - #sublimitedQueue = null; - #sublimitPromise = null; - #shiftSublimit = false; - get inactive() { - return this.#asyncQueue.remaining === 0 && (this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) && !this.limited; - } - get globalLimited() { - return this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset; - } - get localLimited() { - return this.remaining <= 0 && Date.now() < this.reset; - } - get limited() { - return this.globalLimited || this.localLimited; - } - get timeToReset() { - return this.reset + this.manager.options.offset - Date.now(); - } + /** + * {@inheritDoc IHandler.inactive} + */ + inactive = false; + /** + * Emits a debug message + * + * @param message - The message to debug + */ debug(message) { this.manager.emit("restDebug" /* Debug */, `[REST ${this.id}] ${message}`); } - async globalDelayFor(time) { - await (0, import_promises.setTimeout)(time); - this.manager.globalDelay = null; + /** + * {@inheritDoc IHandler.queueRequest} + */ + async queueRequest(routeId, url, options, requestData) { + return this.runRequest(routeId, url, options, requestData); } - async onRateLimit(rateLimitData) { - const { options } = this.manager; - if (!options.rejectOnRateLimit) - return; - const shouldThrow = typeof options.rejectOnRateLimit === "function" ? await options.rejectOnRateLimit(rateLimitData) : options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase())); - if (shouldThrow) { - throw new RateLimitError(rateLimitData); + /** + * The method that actually makes the request to the API, and updates info about the bucket accordingly + * + * @param routeId - The generalized API route with literal ids for major parameters + * @param url - The fully resolved URL to make the request to + * @param options - The fetch options needed to make the request + * @param requestData - Extra data from the user's request needed for errors and additional processing + * @param retries - The number of retries this request has already attempted (recursion) + */ + async runRequest(routeId, url, options, requestData, retries = 0) { + const method = options.method ?? "get"; + const res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries); + if (res === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); + } + const status = res.statusCode; + let retryAfter = 0; + const retry = parseHeader(res.headers["retry-after"]); + if (retry) + retryAfter = Number(retry) * 1e3 + this.manager.options.offset; + if (status === 401 || status === 403 || status === 429) { + incrementInvalidCount(this.manager); + } + if (status >= 200 && status < 300) { + return res; + } else if (status === 429) { + const isGlobal = res.headers["x-ratelimit-global"] !== void 0; + await onRateLimit(this.manager, { + timeToReset: retryAfter, + limit: Number.POSITIVE_INFINITY, + method, + hash: this.hash, + url, + route: routeId.bucketRoute, + majorParameter: this.majorParameter, + global: isGlobal + }); + this.debug( + [ + "Encountered unexpected 429 rate limit", + ` Global : ${isGlobal}`, + ` Method : ${method}`, + ` URL : ${url}`, + ` Bucket : ${routeId.bucketRoute}`, + ` Major parameter: ${routeId.majorParameter}`, + ` Hash : ${this.hash}`, + ` Limit : ${Number.POSITIVE_INFINITY}`, + ` Retry After : ${retryAfter}ms`, + ` Sublimit : None` + ].join("\n") + ); + await (0, import_promises.setTimeout)(retryAfter); + return this.runRequest(routeId, url, options, requestData, retries); + } else { + const handled = await handleErrors(this.manager, res, method, url, requestData, retries); + if (handled === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); + } + return handled; } } +}; +__name(BurstHandler, "BurstHandler"); + +// src/lib/handlers/SequentialHandler.ts +var import_promises2 = require("timers/promises"); +var import_async_queue = require("@sapphire/async-queue"); +var SequentialHandler = class { + /** + * @param manager - The request manager + * @param hash - The hash that this RequestHandler handles + * @param majorParameter - The major parameter for this handler + */ + constructor(manager, hash, majorParameter) { + this.manager = manager; + this.hash = hash; + this.majorParameter = majorParameter; + this.id = `${hash}:${majorParameter}`; + } + /** + * {@inheritDoc IHandler.id} + */ + id; + /** + * The time this rate limit bucket will reset + */ + reset = -1; + /** + * The remaining requests that can be made before we are rate limited + */ + remaining = 1; + /** + * The total number of requests that can be made before we are rate limited + */ + limit = Number.POSITIVE_INFINITY; + /** + * The interface used to sequence async requests sequentially + */ + #asyncQueue = new import_async_queue.AsyncQueue(); + /** + * The interface used to sequence sublimited async requests sequentially + */ + #sublimitedQueue = null; + /** + * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed + */ + #sublimitPromise = null; + /** + * Whether the sublimit queue needs to be shifted in the finally block + */ + #shiftSublimit = false; + /** + * {@inheritDoc IHandler.inactive} + */ + get inactive() { + return this.#asyncQueue.remaining === 0 && (this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) && !this.limited; + } + /** + * If the rate limit bucket is currently limited by the global limit + */ + get globalLimited() { + return this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset; + } + /** + * If the rate limit bucket is currently limited by its limit + */ + get localLimited() { + return this.remaining <= 0 && Date.now() < this.reset; + } + /** + * If the rate limit bucket is currently limited + */ + get limited() { + return this.globalLimited || this.localLimited; + } + /** + * The time until queued requests can continue + */ + get timeToReset() { + return this.reset + this.manager.options.offset - Date.now(); + } + /** + * Emits a debug message + * + * @param message - The message to debug + */ + debug(message) { + this.manager.emit("restDebug" /* Debug */, `[REST ${this.id}] ${message}`); + } + /** + * Delay all requests for the specified amount of time, handling global rate limits + * + * @param time - The amount of time to delay all requests for + */ + async globalDelayFor(time) { + await (0, import_promises2.setTimeout)(time); + this.manager.globalDelay = null; + } + /** + * {@inheritDoc IHandler.queueRequest} + */ async queueRequest(routeId, url, options, requestData) { let queue = this.#asyncQueue; let queueType = 0 /* Standard */; @@ -474,26 +872,35 @@ var SequentialHandler = class { } } } + /** + * The method that actually makes the request to the api, and updates info about the bucket accordingly + * + * @param routeId - The generalized api route with literal ids for major parameters + * @param url - The fully resolved url to make the request to + * @param options - The fetch options needed to make the request + * @param requestData - Extra data from the user's request needed for errors and additional processing + * @param retries - The number of retries this request has already attempted (recursion) + */ async runRequest(routeId, url, options, requestData, retries = 0) { while (this.limited) { const isGlobal = this.globalLimited; let limit2; - let timeout2; + let timeout; let delay; if (isGlobal) { limit2 = this.manager.options.globalRequestsPerSecond; - timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + timeout = this.manager.globalReset + this.manager.options.offset - Date.now(); if (!this.manager.globalDelay) { - this.manager.globalDelay = this.globalDelayFor(timeout2); + this.manager.globalDelay = this.globalDelayFor(timeout); } delay = this.manager.globalDelay; } else { limit2 = this.limit; - timeout2 = this.timeToReset; - delay = (0, import_promises.setTimeout)(timeout2); + timeout = this.timeToReset; + delay = (0, import_promises2.setTimeout)(timeout); } const rateLimitData = { - timeToReset: timeout2, + timeToReset: timeout, limit: limit2, method: options.method ?? "get", hash: this.hash, @@ -503,11 +910,11 @@ var SequentialHandler = class { global: isGlobal }; this.manager.emit("rateLimited" /* RateLimited */, rateLimitData); - await this.onRateLimit(rateLimitData); + await onRateLimit(this.manager, rateLimitData); if (isGlobal) { - this.debug(`Global rate limit hit, blocking all requests for ${timeout2}ms`); + this.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`); } else { - this.debug(`Waiting ${timeout2}ms for rate limit to pass`); + this.debug(`Waiting ${timeout}ms for rate limit to pass`); } await delay; } @@ -517,41 +924,9 @@ var SequentialHandler = class { } this.manager.globalRemaining--; const method = options.method ?? "get"; - const controller = new AbortController(); - const timeout = (0, import_node_timers.setTimeout)(() => controller.abort(), this.manager.options.timeout).unref(); - if (requestData.signal) { - const signal = requestData.signal; - if (signal.aborted) - controller.abort(); - else - signal.addEventListener("abort", () => controller.abort()); - } - let res; - try { - res = await (0, import_undici3.request)(url, { ...options, signal: controller.signal }); - } catch (error) { - if (!(error instanceof Error)) - throw error; - if (shouldRetry(error) && retries !== this.manager.options.retries) { - return await this.runRequest(routeId, url, options, requestData, ++retries); - } - throw error; - } finally { - (0, import_node_timers.clearTimeout)(timeout); - } - if (this.manager.listenerCount("response" /* Response */)) { - this.manager.emit( - "response" /* Response */, - { - method, - path: routeId.original, - route: routeId.bucketRoute, - options, - data: requestData, - retries - }, - { ...res } - ); + const res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries); + if (res === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); } const status = res.statusCode; let retryAfter = 0; @@ -584,34 +959,23 @@ var SequentialHandler = class { } } if (status === 401 || status === 403 || status === 429) { - if (!invalidCountResetTime || invalidCountResetTime < Date.now()) { - invalidCountResetTime = Date.now() + 1e3 * 60 * 10; - invalidCount = 0; - } - invalidCount++; - const emitInvalid = this.manager.options.invalidRequestWarningInterval > 0 && invalidCount % this.manager.options.invalidRequestWarningInterval === 0; - if (emitInvalid) { - this.manager.emit("invalidRequestWarning" /* InvalidRequestWarning */, { - count: invalidCount, - remainingTime: invalidCountResetTime - Date.now() - }); - } + incrementInvalidCount(this.manager); } if (status >= 200 && status < 300) { return res; } else if (status === 429) { const isGlobal = this.globalLimited; let limit2; - let timeout2; + let timeout; if (isGlobal) { limit2 = this.manager.options.globalRequestsPerSecond; - timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + timeout = this.manager.globalReset + this.manager.options.offset - Date.now(); } else { limit2 = this.limit; - timeout2 = this.timeToReset; + timeout = this.timeToReset; } - await this.onRateLimit({ - timeToReset: timeout2, + await onRateLimit(this.manager, { + timeToReset: timeout, limit: limit2, method, hash: this.hash, @@ -643,7 +1007,7 @@ var SequentialHandler = class { } this.#sublimitPromise?.resolve(); this.#sublimitPromise = null; - await (0, import_promises.setTimeout)(sublimitTimeout); + await (0, import_promises2.setTimeout)(sublimitTimeout); let resolve; const promise = new Promise((res2) => resolve = res2); this.#sublimitPromise = { promise, resolve }; @@ -653,20 +1017,12 @@ var SequentialHandler = class { } } return this.runRequest(routeId, url, options, requestData, retries); - } else if (status >= 500 && status < 600) { - if (retries !== this.manager.options.retries) { + } else { + const handled = await handleErrors(this.manager, res, method, url, requestData, retries); + if (handled === null) { return this.runRequest(routeId, url, options, requestData, ++retries); } - throw new HTTPError(status, method, url, requestData); - } else { - if (status >= 400 && status < 500) { - if (status === 401 && requestData.auth) { - this.manager.setToken(null); - } - const data = await parseResponse(res); - throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData); - } - return res; + return handled; } } }; @@ -683,11 +1039,30 @@ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => { return RequestMethod2; })(RequestMethod || {}); var RequestManager = class extends import_node_events.EventEmitter { + /** + * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests + * performed by this manager. + */ agent = null; + /** + * The number of requests remaining in the global bucket + */ globalRemaining; + /** + * The promise used to wait out the global rate limit + */ globalDelay = null; + /** + * The timestamp at which the global bucket resets + */ globalReset = -1; + /** + * API bucket hashes that are cached from provided routes + */ hashes = new import_collection.Collection(); + /** + * Request handlers created from the bucket hash and the major parameters + */ handlers = new import_collection.Collection(); #token = null; hashTimer; @@ -741,14 +1116,30 @@ var RequestManager = class extends import_node_events.EventEmitter { }, this.options.handlerSweepInterval).unref(); } } + /** + * Sets the default agent to use for requests performed by this manager + * + * @param agent - The agent to use + */ setAgent(agent) { this.agent = agent; return this; } + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ setToken(token) { this.#token = token; return this; } + /** + * Queues a request to be sent + * + * @param request - All the information needed to make a request + * @returns The response from the api request + */ async queueRequest(request2) { const routeId = RequestManager.generateRouteData(request2.fullRoute, request2.method); const hash = this.hashes.get(`${request2.method}:${routeId.bucketRoute}`) ?? { @@ -764,11 +1155,23 @@ var RequestManager = class extends import_node_events.EventEmitter { signal: request2.signal }); } + /** + * Creates a new rate limit handler from a hash, based on the hash and the major parameter + * + * @param hash - The hash for the route + * @param majorParameter - The major parameter for this handler + * @internal + */ createHandler(hash, majorParameter) { - const queue = new SequentialHandler(this, hash, majorParameter); + const queue = majorParameter === BurstHandlerMajorIdKey ? new BurstHandler(this, hash, majorParameter) : new SequentialHandler(this, hash, majorParameter); this.handlers.set(queue.id, queue); return queue; } + /** + * Formats the request data to a usable format for fetch + * + * @param request - The request data + */ async resolveRequest(request2) { const { options } = this; let query = ""; @@ -800,7 +1203,13 @@ var RequestManager = class extends import_node_events.EventEmitter { const fileKey = file.key ?? `files[${index}]`; if (import_node_buffer2.Buffer.isBuffer(file.data)) { const { fileTypeFromBuffer } = await getFileType(); - const contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime; + let contentType = file.contentType; + if (!contentType) { + const parsedType = (await fileTypeFromBuffer(file.data))?.mime; + if (parsedType) { + contentType = OverwrittenMimeTypes[parsedType] ?? parsedType; + } + } formData.append(fileKey, new import_node_buffer2.Blob([file.data], { type: contentType }), file.name); } else { formData.append(fileKey, new import_node_buffer2.Blob([`${file.data}`], { type: file.contentType }), file.name); @@ -835,19 +1244,39 @@ var RequestManager = class extends import_node_events.EventEmitter { fetchOptions.dispatcher = request2.dispatcher ?? this.agent ?? void 0; return { url, fetchOptions }; } + /** + * Stops the hash sweeping interval + */ clearHashSweeper() { (0, import_node_timers2.clearInterval)(this.hashTimer); } + /** + * Stops the request handler sweeping interval + */ clearHandlerSweeper() { (0, import_node_timers2.clearInterval)(this.handlerTimer); } + /** + * Generates route data for an endpoint:method + * + * @param endpoint - The raw endpoint to generalize + * @param method - The HTTP method this endpoint is called without + * @internal + */ static generateRouteData(endpoint, method) { - const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{16,19})/.exec(endpoint); + if (endpoint.startsWith("/interactions/") && endpoint.endsWith("/callback")) { + return { + majorParameter: BurstHandlerMajorIdKey, + bucketRoute: "/interactions/:id/:token/callback", + original: endpoint + }; + } + const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{17,19})/.exec(endpoint); const majorId = majorIdMatch?.[1] ?? "global"; - const baseRoute = endpoint.replaceAll(/\d{16,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); + const baseRoute = endpoint.replaceAll(/\d{17,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); let exceptions = ""; if (method === "DELETE" /* Delete */ && baseRoute === "/channels/:id/messages/:id") { - const id = /\d{16,19}$/.exec(endpoint)[0]; + const id = /\d{17,19}$/.exec(endpoint)[0]; const timestamp = import_snowflake.DiscordSnowflake.timestampFrom(id); if (Date.now() - timestamp > 1e3 * 60 * 60 * 24 * 14) { exceptions += "/Delete Old Message"; @@ -880,36 +1309,89 @@ var REST = class extends import_node_events2.EventEmitter { this.requestManager.off(name, listener); }); } + /** + * Gets the agent set for this instance + */ getAgent() { return this.requestManager.agent; } + /** + * Sets the default agent to use for requests performed by this instance + * + * @param agent - Sets the agent to use + */ setAgent(agent) { this.requestManager.setAgent(agent); return this; } + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ setToken(token) { this.requestManager.setToken(token); return this; } + /** + * Runs a get request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async get(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "GET" /* Get */ }); } + /** + * Runs a delete request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async delete(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "DELETE" /* Delete */ }); } + /** + * Runs a post request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async post(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "POST" /* Post */ }); } + /** + * Runs a put request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async put(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "PUT" /* Put */ }); } + /** + * Runs a patch request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async patch(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "PATCH" /* Patch */ }); } + /** + * Runs a request from the api + * + * @param options - Request options + */ async request(options) { const response = await this.raw(options); return parseResponse(response); } + /** + * Runs a request from the API, yielding the raw Response object + * + * @param options - Request options + */ async raw(options) { return this.requestManager.queueRequest(options); } @@ -917,17 +1399,20 @@ var REST = class extends import_node_events2.EventEmitter { __name(REST, "REST"); // src/index.ts -var version = "1.5.0"; +var version = "1.7.1"; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, + BurstHandlerMajorIdKey, CDN, DefaultRestOptions, DefaultUserAgent, + DefaultUserAgentAppendix, DiscordAPIError, HTTPError, + OverwrittenMimeTypes, REST, RESTEvents, RateLimitError, diff --git a/node_modules/@discordjs/rest/dist/index.js.map b/node_modules/@discordjs/rest/dist/index.js.map index b21a0eb..f01c8dd 100644 --- a/node_modules/@discordjs/rest/dist/index.js.map +++ b/node_modules/@discordjs/rest/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/lib/CDN.ts","../src/lib/utils/constants.ts","../src/lib/errors/DiscordAPIError.ts","../src/lib/errors/HTTPError.ts","../src/lib/errors/RateLimitError.ts","../src/lib/RequestManager.ts","../src/lib/handlers/SequentialHandler.ts","../src/lib/utils/utils.ts","../src/lib/REST.ts"],"sourcesContent":["export * from './lib/CDN.js';\nexport * from './lib/errors/DiscordAPIError.js';\nexport * from './lib/errors/HTTPError.js';\nexport * from './lib/errors/RateLimitError.js';\nexport * from './lib/RequestManager.js';\nexport * from './lib/REST.js';\nexport * from './lib/utils/constants.js';\nexport { makeURLSearchParams, parseResponse } from './lib/utils/utils.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.5.0';\n","/* eslint-disable jsdoc/check-param-names */\nimport { URL } from 'node:url';\nimport {\n\tALLOWED_EXTENSIONS,\n\tALLOWED_SIZES,\n\tALLOWED_STICKER_EXTENSIONS,\n\tDefaultRestOptions,\n\ttype ImageExtension,\n\ttype ImageSize,\n\ttype StickerExtension,\n} from './utils/constants.js';\n\n/**\n * The options used for image URLs\n */\nexport interface BaseImageURLOptions {\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: ImageExtension;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The options used for image URLs with animated content\n */\nexport interface ImageURLOptions extends BaseImageURLOptions {\n\t/**\n\t * Whether or not to prefer the static version of an image asset.\n\t */\n\tforceStatic?: boolean;\n}\n\n/**\n * The options to use when making a CDN URL\n */\nexport interface MakeURLOptions {\n\t/**\n\t * The allowed extensions that can be used\n\t */\n\tallowedExtensions?: readonly string[];\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: string | undefined;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The CDN link builder\n */\nexport class CDN {\n\tpublic constructor(private readonly base: string = DefaultRestOptions.cdn) {}\n\n\t/**\n\t * Generates an app asset URL for a client's asset.\n\t *\n\t * @param clientId - The client id that has the asset\n\t * @param assetHash - The hash provided by Discord for this asset\n\t * @param options - Optional options for the asset\n\t */\n\tpublic appAsset(clientId: string, assetHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/${clientId}/${assetHash}`, options);\n\t}\n\n\t/**\n\t * Generates an app icon URL for a client's icon.\n\t *\n\t * @param clientId - The client id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic appIcon(clientId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-icons/${clientId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates an avatar URL, e.g. for a user or a webhook.\n\t *\n\t * @param id - The id that has the icon\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic avatar(id: string, avatarHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a banner URL, e.g. for a user or a guild.\n\t *\n\t * @param id - The id that has the banner splash\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic banner(id: string, bannerHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL for a channel, e.g. a group DM.\n\t *\n\t * @param channelId - The channel id that has the icon\n\t * @param iconHash - The hash provided by Discord for this channel\n\t * @param options - Optional options for the icon\n\t */\n\tpublic channelIcon(channelId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates the default avatar URL for a discriminator.\n\t *\n\t * @param discriminator - The discriminator modulo 5\n\t */\n\tpublic defaultAvatar(discriminator: number): string {\n\t\treturn this.makeURL(`/embed/avatars/${discriminator}`, { extension: 'png' });\n\t}\n\n\t/**\n\t * Generates a discovery splash URL for a guild's discovery splash.\n\t *\n\t * @param guildId - The guild id that has the discovery splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic discoverySplash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates an emoji's URL for an emoji.\n\t *\n\t * @param emojiId - The emoji id\n\t * @param extension - The extension of the emoji\n\t */\n\tpublic emoji(emojiId: string, extension?: ImageExtension): string {\n\t\treturn this.makeURL(`/emojis/${emojiId}`, { extension });\n\t}\n\n\t/**\n\t * Generates a guild member avatar URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic guildMemberAvatar(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tavatarHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a guild member banner URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic guildMemberBanner(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tbannerHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL, e.g. for a guild.\n\t *\n\t * @param id - The id that has the icon splash\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic icon(id: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options);\n\t}\n\n\t/**\n\t * Generates a URL for the icon of a role\n\t *\n\t * @param roleId - The id of the role that has the icon\n\t * @param roleIconHash - The hash provided by Discord for this role icon\n\t * @param options - Optional options for the role icon\n\t */\n\tpublic roleIcon(roleId: string, roleIconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a guild invite splash URL for a guild's invite splash.\n\t *\n\t * @param guildId - The guild id that has the invite splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic splash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates a sticker URL.\n\t *\n\t * @param stickerId - The sticker id\n\t * @param extension - The extension of the sticker\n\t */\n\tpublic sticker(stickerId: string, extension?: StickerExtension): string {\n\t\treturn this.makeURL(`/stickers/${stickerId}`, {\n\t\t\tallowedExtensions: ALLOWED_STICKER_EXTENSIONS,\n\t\t\textension: extension ?? 'png', // Stickers cannot have a `.webp` extension, so we default to a `.png`\n\t\t});\n\t}\n\n\t/**\n\t * Generates a sticker pack banner URL.\n\t *\n\t * @param bannerId - The banner id\n\t * @param options - Optional options for the banner\n\t */\n\tpublic stickerPackBanner(bannerId: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options);\n\t}\n\n\t/**\n\t * Generates a team icon URL for a team's icon.\n\t *\n\t * @param teamId - The team id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic teamIcon(teamId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/team-icons/${teamId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a cover image for a guild scheduled event.\n\t *\n\t * @param scheduledEventId - The scheduled event id\n\t * @param coverHash - The hash provided by discord for this cover image\n\t * @param options - Optional options for the cover image\n\t */\n\tpublic guildScheduledEventCover(\n\t\tscheduledEventId: string,\n\t\tcoverHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`.\n\t *\n\t * @param route - The base cdn route\n\t * @param hash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the link\n\t */\n\tprivate dynamicMakeURL(\n\t\troute: string,\n\t\thash: string,\n\t\t{ forceStatic = false, ...options }: Readonly = {},\n\t): string {\n\t\treturn this.makeURL(route, !forceStatic && hash.startsWith('a_') ? { ...options, extension: 'gif' } : options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource\n\t *\n\t * @param route - The base cdn route\n\t * @param options - The extension/size options for the link\n\t */\n\tprivate makeURL(\n\t\troute: string,\n\t\t{ allowedExtensions = ALLOWED_EXTENSIONS, extension = 'webp', size }: Readonly = {},\n\t): string {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\textension = String(extension).toLowerCase();\n\n\t\tif (!allowedExtensions.includes(extension)) {\n\t\t\tthrow new RangeError(`Invalid extension provided: ${extension}\\nMust be one of: ${allowedExtensions.join(', ')}`);\n\t\t}\n\n\t\tif (size && !ALLOWED_SIZES.includes(size)) {\n\t\t\tthrow new RangeError(`Invalid size provided: ${size}\\nMust be one of: ${ALLOWED_SIZES.join(', ')}`);\n\t\t}\n\n\t\tconst url = new URL(`${this.base}${route}.${extension}`);\n\n\t\tif (size) {\n\t\t\turl.searchParams.set('size', String(size));\n\t\t}\n\n\t\treturn url.toString();\n\t}\n}\n","import process from 'node:process';\nimport { APIVersion } from 'discord-api-types/v10';\nimport { Agent } from 'undici';\nimport type { RESTOptions } from '../REST.js';\n\nexport const DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.5.0)`;\n\nexport const DefaultRestOptions = {\n\tget agent() {\n\t\treturn new Agent({\n\t\t\tconnect: {\n\t\t\t\ttimeout: 30_000,\n\t\t\t},\n\t\t});\n\t},\n\tapi: 'https://discord.com/api',\n\tauthPrefix: 'Bot',\n\tcdn: 'https://cdn.discordapp.com',\n\theaders: {},\n\tinvalidRequestWarningInterval: 0,\n\tglobalRequestsPerSecond: 50,\n\toffset: 50,\n\trejectOnRateLimit: null,\n\tretries: 3,\n\ttimeout: 15_000,\n\tuserAgentAppendix: `Node.js ${process.version}`,\n\tversion: APIVersion,\n\thashSweepInterval: 14_400_000, // 4 Hours\n\thashLifetime: 86_400_000, // 24 Hours\n\thandlerSweepInterval: 3_600_000, // 1 Hour\n} as const satisfies Required;\n\n/**\n * The events that the REST manager emits\n */\nexport const enum RESTEvents {\n\tDebug = 'restDebug',\n\tHandlerSweep = 'handlerSweep',\n\tHashSweep = 'hashSweep',\n\tInvalidRequestWarning = 'invalidRequestWarning',\n\tRateLimited = 'rateLimited',\n\tResponse = 'response',\n}\n\nexport const ALLOWED_EXTENSIONS = ['webp', 'png', 'jpg', 'jpeg', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_STICKER_EXTENSIONS = ['png', 'json'] as const satisfies readonly string[];\nexport const ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1_024, 2_048, 4_096] as const satisfies readonly number[];\n\nexport type ImageExtension = typeof ALLOWED_EXTENSIONS[number];\nexport type StickerExtension = typeof ALLOWED_STICKER_EXTENSIONS[number];\nexport type ImageSize = typeof ALLOWED_SIZES[number];\n","import type { InternalRequest, RawFile } from '../RequestManager.js';\n\ninterface DiscordErrorFieldInformation {\n\tcode: string;\n\tmessage: string;\n}\n\ninterface DiscordErrorGroupWrapper {\n\t_errors: DiscordError[];\n}\n\ntype DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | { [k: string]: DiscordError };\n\nexport interface DiscordErrorData {\n\tcode: number;\n\terrors?: DiscordError;\n\tmessage: string;\n}\n\nexport interface OAuthErrorData {\n\terror: string;\n\terror_description?: string;\n}\n\nexport interface RequestBody {\n\tfiles: RawFile[] | undefined;\n\tjson: unknown | undefined;\n}\n\nfunction isErrorGroupWrapper(error: DiscordError): error is DiscordErrorGroupWrapper {\n\treturn Reflect.has(error as Record, '_errors');\n}\n\nfunction isErrorResponse(error: DiscordError): error is DiscordErrorFieldInformation {\n\treturn typeof Reflect.get(error as Record, 'message') === 'string';\n}\n\n/**\n * Represents an API error returned by Discord\n */\nexport class DiscordAPIError extends Error {\n\tpublic requestBody: RequestBody;\n\n\t/**\n\t * @param rawError - The error reported by Discord\n\t * @param code - The error code reported by Discord\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic rawError: DiscordErrorData | OAuthErrorData,\n\t\tpublic code: number | string,\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(DiscordAPIError.getMessage(rawError));\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${DiscordAPIError.name}[${this.code}]`;\n\t}\n\n\tprivate static getMessage(error: DiscordErrorData | OAuthErrorData) {\n\t\tlet flattened = '';\n\t\tif ('code' in error) {\n\t\t\tif (error.errors) {\n\t\t\t\tflattened = [...this.flattenDiscordError(error.errors)].join('\\n');\n\t\t\t}\n\n\t\t\treturn error.message && flattened\n\t\t\t\t? `${error.message}\\n${flattened}`\n\t\t\t\t: error.message || flattened || 'Unknown Error';\n\t\t}\n\n\t\treturn error.error_description ?? 'No Description';\n\t}\n\n\tprivate static *flattenDiscordError(obj: DiscordError, key = ''): IterableIterator {\n\t\tif (isErrorResponse(obj)) {\n\t\t\treturn yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();\n\t\t}\n\n\t\tfor (const [otherKey, val] of Object.entries(obj)) {\n\t\t\tconst nextKey = otherKey.startsWith('_')\n\t\t\t\t? key\n\t\t\t\t: key\n\t\t\t\t? Number.isNaN(Number(otherKey))\n\t\t\t\t\t? `${key}.${otherKey}`\n\t\t\t\t\t: `${key}[${otherKey}]`\n\t\t\t\t: otherKey;\n\n\t\t\tif (typeof val === 'string') {\n\t\t\t\tyield val;\n\t\t\t} else if (isErrorGroupWrapper(val)) {\n\t\t\t\tfor (const error of val._errors) {\n\t\t\t\t\tyield* this.flattenDiscordError(error, nextKey);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield* this.flattenDiscordError(val, nextKey);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { STATUS_CODES } from 'node:http';\nimport type { InternalRequest } from '../RequestManager.js';\nimport type { RequestBody } from './DiscordAPIError.js';\n\n/**\n * Represents a HTTP error\n */\nexport class HTTPError extends Error {\n\tpublic requestBody: RequestBody;\n\n\tpublic override name = HTTPError.name;\n\n\t/**\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(STATUS_CODES[status]);\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n}\n","import type { RateLimitData } from '../REST';\n\nexport class RateLimitError extends Error implements RateLimitData {\n\tpublic timeToReset: number;\n\n\tpublic limit: number;\n\n\tpublic method: string;\n\n\tpublic hash: string;\n\n\tpublic url: string;\n\n\tpublic route: string;\n\n\tpublic majorParameter: string;\n\n\tpublic global: boolean;\n\n\tpublic constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData) {\n\t\tsuper();\n\t\tthis.timeToReset = timeToReset;\n\t\tthis.limit = limit;\n\t\tthis.method = method;\n\t\tthis.hash = hash;\n\t\tthis.url = url;\n\t\tthis.route = route;\n\t\tthis.majorParameter = majorParameter;\n\t\tthis.global = global;\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${RateLimitError.name}[${this.route}]`;\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { setInterval, clearInterval } from 'node:timers';\nimport type { URLSearchParams } from 'node:url';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { DiscordSnowflake } from '@sapphire/snowflake';\nimport { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';\nimport type { RESTOptions, RestEvents, RequestOptions } from './REST.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { SequentialHandler } from './handlers/SequentialHandler.js';\nimport { DefaultRestOptions, DefaultUserAgent, RESTEvents } from './utils/constants.js';\nimport { resolveBody } from './utils/utils.js';\n\n// Make this a lazy dynamic import as file-type is a pure ESM package\nconst getFileType = lazy(async () => import('file-type'));\n\n/**\n * Represents a file to be added to the request\n */\nexport interface RawFile {\n\t/**\n\t * Content-Type of the file\n\t */\n\tcontentType?: string;\n\t/**\n\t * The actual data for the file\n\t */\n\tdata: Buffer | boolean | number | string;\n\t/**\n\t * An explicit key to use for key of the formdata field for this file.\n\t * When not provided, the index of the file in the files array is used in the form `files[${index}]`.\n\t * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)\n\t */\n\tkey?: string;\n\t/**\n\t * The name of the file\n\t */\n\tname: string;\n}\n\n/**\n * Represents possible data to be given to an endpoint\n */\nexport interface RequestData {\n\t/**\n\t * Whether to append JSON data to form data instead of `payload_json` when sending files\n\t */\n\tappendToFormData?: boolean;\n\t/**\n\t * If this request needs the `Authorization` header\n\t *\n\t * @defaultValue `true`\n\t */\n\tauth?: boolean;\n\t/**\n\t * The authorization prefix to use for this request, useful if you use this with bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix?: 'Bearer' | 'Bot';\n\t/**\n\t * The body to send to this request.\n\t * If providing as BodyInit, set `passThroughBody: true`\n\t */\n\tbody?: BodyInit | unknown;\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.\n\t */\n\tdispatcher?: Agent;\n\t/**\n\t * Files to be attached to this request\n\t */\n\tfiles?: RawFile[] | undefined;\n\t/**\n\t * Additional headers to add to this request\n\t */\n\theaders?: Record;\n\t/**\n\t * Whether to pass-through the body property directly to `fetch()`.\n\t * This only applies when files is NOT present\n\t */\n\tpassThroughBody?: boolean;\n\t/**\n\t * Query string parameters to append to the called endpoint\n\t */\n\tquery?: URLSearchParams;\n\t/**\n\t * Reason to show in the audit logs\n\t */\n\treason?: string | undefined;\n\t/**\n\t * The signal to abort the queue entry or the REST call, where applicable\n\t */\n\tsignal?: AbortSignal | undefined;\n\t/**\n\t * If this request should be versioned\n\t *\n\t * @defaultValue `true`\n\t */\n\tversioned?: boolean;\n}\n\n/**\n * Possible headers for an API call\n */\nexport interface RequestHeaders {\n\tAuthorization?: string;\n\t'User-Agent': string;\n\t'X-Audit-Log-Reason'?: string;\n}\n\n/**\n * Possible API methods to be used when doing requests\n */\nexport const enum RequestMethod {\n\tDelete = 'DELETE',\n\tGet = 'GET',\n\tPatch = 'PATCH',\n\tPost = 'POST',\n\tPut = 'PUT',\n}\n\nexport type RouteLike = `/${string}`;\n\n/**\n * Internal request options\n *\n * @internal\n */\nexport interface InternalRequest extends RequestData {\n\tfullRoute: RouteLike;\n\tmethod: RequestMethod;\n}\n\nexport type HandlerRequestData = Pick;\n\n/**\n * Parsed route data for an endpoint\n *\n * @internal\n */\nexport interface RouteData {\n\tbucketRoute: string;\n\tmajorParameter: string;\n\toriginal: RouteLike;\n}\n\n/**\n * Represents a hash and its associated fields\n *\n * @internal\n */\nexport interface HashData {\n\tlastAccess: number;\n\tvalue: string;\n}\n\nexport interface RequestManager {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\n/**\n * Represents the class that manages handlers for endpoints\n */\nexport class RequestManager extends EventEmitter {\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests\n\t * performed by this manager.\n\t */\n\tpublic agent: Dispatcher | null = null;\n\n\t/**\n\t * The number of requests remaining in the global bucket\n\t */\n\tpublic globalRemaining: number;\n\n\t/**\n\t * The promise used to wait out the global rate limit\n\t */\n\tpublic globalDelay: Promise | null = null;\n\n\t/**\n\t * The timestamp at which the global bucket resets\n\t */\n\tpublic globalReset = -1;\n\n\t/**\n\t * API bucket hashes that are cached from provided routes\n\t */\n\tpublic readonly hashes = new Collection();\n\n\t/**\n\t * Request handlers created from the bucket hash and the major parameters\n\t */\n\tpublic readonly handlers = new Collection();\n\n\t#token: string | null = null;\n\n\tprivate hashTimer!: NodeJS.Timer;\n\n\tprivate handlerTimer!: NodeJS.Timer;\n\n\tpublic readonly options: RESTOptions;\n\n\tpublic constructor(options: Partial) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultRestOptions, ...options };\n\t\tthis.options.offset = Math.max(0, this.options.offset);\n\t\tthis.globalRemaining = this.options.globalRequestsPerSecond;\n\t\tthis.agent = options.agent ?? null;\n\n\t\t// Start sweepers\n\t\tthis.setupSweepers();\n\t}\n\n\tprivate setupSweepers() {\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\tconst validateMaxInterval = (interval: number) => {\n\t\t\tif (interval > 14_400_000) {\n\t\t\t\tthrow new Error('Cannot set an interval greater than 4 hours');\n\t\t\t}\n\t\t};\n\n\t\tif (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.hashSweepInterval);\n\t\t\tthis.hashTimer = setInterval(() => {\n\t\t\t\tconst sweptHashes = new Collection();\n\t\t\t\tconst currentDate = Date.now();\n\n\t\t\t\t// Begin sweeping hash based on lifetimes\n\t\t\t\tthis.hashes.sweep((val, key) => {\n\t\t\t\t\t// `-1` indicates a global hash\n\t\t\t\t\tif (val.lastAccess === -1) return false;\n\n\t\t\t\t\t// Check if lifetime has been exceeded\n\t\t\t\t\tconst shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime;\n\n\t\t\t\t\t// Add hash to collection of swept hashes\n\t\t\t\t\tif (shouldSweep) {\n\t\t\t\t\t\t// Add to swept hashes\n\t\t\t\t\t\tsweptHashes.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit debug information\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`);\n\n\t\t\t\t\treturn shouldSweep;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HashSweep, sweptHashes);\n\t\t\t}, this.options.hashSweepInterval).unref();\n\t\t}\n\n\t\tif (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.handlerSweepInterval);\n\t\t\tthis.handlerTimer = setInterval(() => {\n\t\t\t\tconst sweptHandlers = new Collection();\n\n\t\t\t\t// Begin sweeping handlers based on activity\n\t\t\t\tthis.handlers.sweep((val, key) => {\n\t\t\t\t\tconst { inactive } = val;\n\n\t\t\t\t\t// Collect inactive handlers\n\t\t\t\t\tif (inactive) {\n\t\t\t\t\t\tsweptHandlers.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`);\n\t\t\t\t\treturn inactive;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HandlerSweep, sweptHandlers);\n\t\t\t}, this.options.handlerSweepInterval).unref();\n\t\t}\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this manager\n\t *\n\t * @param agent - The agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.agent = agent;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.#token = token;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Queues a request to be sent\n\t *\n\t * @param request - All the information needed to make a request\n\t * @returns The response from the api request\n\t */\n\tpublic async queueRequest(request: InternalRequest): Promise {\n\t\t// Generalize the endpoint to its route data\n\t\tconst routeId = RequestManager.generateRouteData(request.fullRoute, request.method);\n\t\t// Get the bucket hash for the generic route, or point to a global route otherwise\n\t\tconst hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {\n\t\t\tvalue: `Global(${request.method}:${routeId.bucketRoute})`,\n\t\t\tlastAccess: -1,\n\t\t};\n\n\t\t// Get the request handler for the obtained hash, with its major parameter\n\t\tconst handler =\n\t\t\tthis.handlers.get(`${hash.value}:${routeId.majorParameter}`) ??\n\t\t\tthis.createHandler(hash.value, routeId.majorParameter);\n\n\t\t// Resolve the request into usable fetch options\n\t\tconst { url, fetchOptions } = await this.resolveRequest(request);\n\n\t\t// Queue the request\n\t\treturn handler.queueRequest(routeId, url, fetchOptions, {\n\t\t\tbody: request.body,\n\t\t\tfiles: request.files,\n\t\t\tauth: request.auth !== false,\n\t\t\tsignal: request.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new rate limit handler from a hash, based on the hash and the major parameter\n\t *\n\t * @param hash - The hash for the route\n\t * @param majorParameter - The major parameter for this handler\n\t * @internal\n\t */\n\tprivate createHandler(hash: string, majorParameter: string) {\n\t\t// Create the async request queue to handle requests\n\t\tconst queue = new SequentialHandler(this, hash, majorParameter);\n\t\t// Save the queue based on its id\n\t\tthis.handlers.set(queue.id, queue);\n\n\t\treturn queue;\n\t}\n\n\t/**\n\t * Formats the request data to a usable format for fetch\n\t *\n\t * @param request - The request data\n\t */\n\tprivate async resolveRequest(request: InternalRequest): Promise<{ fetchOptions: RequestOptions; url: string }> {\n\t\tconst { options } = this;\n\n\t\tlet query = '';\n\n\t\t// If a query option is passed, use it\n\t\tif (request.query) {\n\t\t\tconst resolvedQuery = request.query.toString();\n\t\t\tif (resolvedQuery !== '') {\n\t\t\t\tquery = `?${resolvedQuery}`;\n\t\t\t}\n\t\t}\n\n\t\t// Create the required headers\n\t\tconst headers: RequestHeaders = {\n\t\t\t...this.options.headers,\n\t\t\t'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),\n\t\t};\n\n\t\t// If this request requires authorization (allowing non-\"authorized\" requests for webhooks)\n\t\tif (request.auth !== false) {\n\t\t\t// If we haven't received a token, throw an error\n\t\t\tif (!this.#token) {\n\t\t\t\tthrow new Error('Expected token to be set for this request, but none was present');\n\t\t\t}\n\n\t\t\theaders.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${this.#token}`;\n\t\t}\n\n\t\t// If a reason was set, set it's appropriate header\n\t\tif (request.reason?.length) {\n\t\t\theaders['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);\n\t\t}\n\n\t\t// Format the full request URL (api base, optional version, endpoint, optional querystring)\n\t\tconst url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${\n\t\t\trequest.fullRoute\n\t\t}${query}`;\n\n\t\tlet finalBody: RequestInit['body'];\n\t\tlet additionalHeaders: Record = {};\n\n\t\tif (request.files?.length) {\n\t\t\tconst formData = new FormData();\n\n\t\t\t// Attach all files to the request\n\t\t\tfor (const [index, file] of request.files.entries()) {\n\t\t\t\tconst fileKey = file.key ?? `files[${index}]`;\n\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#parameters\n\t\t\t\t// FormData.append only accepts a string or Blob.\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters\n\t\t\t\t// The Blob constructor accepts TypedArray/ArrayBuffer, strings, and Blobs.\n\t\t\t\tif (Buffer.isBuffer(file.data)) {\n\t\t\t\t\t// Try to infer the content type from the buffer if one isn't passed\n\t\t\t\t\tconst { fileTypeFromBuffer } = await getFileType();\n\t\t\t\t\tconst contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime;\n\t\t\t\t\tformData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);\n\t\t\t\t} else {\n\t\t\t\t\tformData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (request.body != null) {\n\t\t\t\tif (request.appendToFormData) {\n\t\t\t\t\tfor (const [key, value] of Object.entries(request.body as Record)) {\n\t\t\t\t\t\tformData.append(key, value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.append('payload_json', JSON.stringify(request.body));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set the final body to the form data\n\t\t\tfinalBody = formData;\n\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t} else if (request.body != null) {\n\t\t\tif (request.passThroughBody) {\n\t\t\t\tfinalBody = request.body as BodyInit;\n\t\t\t} else {\n\t\t\t\t// Stringify the JSON data\n\t\t\t\tfinalBody = JSON.stringify(request.body);\n\t\t\t\t// Set the additional headers to specify the content-type\n\t\t\t\tadditionalHeaders = { 'Content-Type': 'application/json' };\n\t\t\t}\n\t\t}\n\n\t\tfinalBody = await resolveBody(finalBody);\n\n\t\tconst fetchOptions: RequestOptions = {\n\t\t\theaders: { ...request.headers, ...additionalHeaders, ...headers } as Record,\n\t\t\tmethod: request.method.toUpperCase() as Dispatcher.HttpMethod,\n\t\t};\n\n\t\tif (finalBody !== undefined) {\n\t\t\tfetchOptions.body = finalBody as Exclude;\n\t\t}\n\n\t\t// Prioritize setting an agent per request, use the agent for this instance otherwise.\n\t\tfetchOptions.dispatcher = request.dispatcher ?? this.agent ?? undefined!;\n\n\t\treturn { url, fetchOptions };\n\t}\n\n\t/**\n\t * Stops the hash sweeping interval\n\t */\n\tpublic clearHashSweeper() {\n\t\tclearInterval(this.hashTimer);\n\t}\n\n\t/**\n\t * Stops the request handler sweeping interval\n\t */\n\tpublic clearHandlerSweeper() {\n\t\tclearInterval(this.handlerTimer);\n\t}\n\n\t/**\n\t * Generates route data for an endpoint:method\n\t *\n\t * @param endpoint - The raw endpoint to generalize\n\t * @param method - The HTTP method this endpoint is called without\n\t * @internal\n\t */\n\tprivate static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {\n\t\tconst majorIdMatch = /^\\/(?:channels|guilds|webhooks)\\/(\\d{16,19})/.exec(endpoint);\n\n\t\t// Get the major id for this route - global otherwise\n\t\tconst majorId = majorIdMatch?.[1] ?? 'global';\n\n\t\tconst baseRoute = endpoint\n\t\t\t// Strip out all ids\n\t\t\t.replaceAll(/\\d{16,19}/g, ':id')\n\t\t\t// Strip out reaction as they fall under the same bucket\n\t\t\t.replace(/\\/reactions\\/(.*)/, '/reactions/:reaction');\n\n\t\tlet exceptions = '';\n\n\t\t// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)\n\t\t// https://github.com/discord/discord-api-docs/issues/1295\n\t\tif (method === RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {\n\t\t\tconst id = /\\d{16,19}$/.exec(endpoint)![0]!;\n\t\t\tconst timestamp = DiscordSnowflake.timestampFrom(id);\n\t\t\tif (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {\n\t\t\t\texceptions += '/Delete Old Message';\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmajorParameter: majorId,\n\t\t\tbucketRoute: baseRoute + exceptions,\n\t\t\toriginal: endpoint,\n\t\t};\n\t}\n}\n","import { setTimeout, clearTimeout } from 'node:timers';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport { request, type Dispatcher } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager';\nimport { DiscordAPIError, type DiscordErrorData, type OAuthErrorData } from '../errors/DiscordAPIError.js';\nimport { HTTPError } from '../errors/HTTPError.js';\nimport { RateLimitError } from '../errors/RateLimitError.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { hasSublimit, parseHeader, parseResponse, shouldRetry } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\n\n/**\n * Invalid request limiting is done on a per-IP basis, not a per-token basis.\n * The best we can do is track invalid counts process-wide (on the theory that\n * users could have multiple bots run from one process) rather than per-bot.\n * Therefore, store these at file scope here rather than in the client's\n * RESTManager object.\n */\nlet invalidCount = 0;\nlet invalidCountResetTime: number | null = null;\n\nconst enum QueueType {\n\tStandard,\n\tSublimit,\n}\n\n/**\n * The structure used to handle requests for a given bucket\n */\nexport class SequentialHandler implements IHandler {\n\t/**\n\t * {@inheritDoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * The time this rate limit bucket will reset\n\t */\n\tprivate reset = -1;\n\n\t/**\n\t * The remaining requests that can be made before we are rate limited\n\t */\n\tprivate remaining = 1;\n\n\t/**\n\t * The total number of requests that can be made before we are rate limited\n\t */\n\tprivate limit = Number.POSITIVE_INFINITY;\n\n\t/**\n\t * The interface used to sequence async requests sequentially\n\t */\n\t#asyncQueue = new AsyncQueue();\n\n\t/**\n\t * The interface used to sequence sublimited async requests sequentially\n\t */\n\t#sublimitedQueue: AsyncQueue | null = null;\n\n\t/**\n\t * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed\n\t */\n\t#sublimitPromise: { promise: Promise; resolve(): void } | null = null;\n\n\t/**\n\t * Whether the sublimit queue needs to be shifted in the finally block\n\t */\n\t#shiftSublimit = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic get inactive(): boolean {\n\t\treturn (\n\t\t\tthis.#asyncQueue.remaining === 0 &&\n\t\t\t(this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) &&\n\t\t\t!this.limited\n\t\t);\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by the global limit\n\t */\n\tprivate get globalLimited(): boolean {\n\t\treturn this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by its limit\n\t */\n\tprivate get localLimited(): boolean {\n\t\treturn this.remaining <= 0 && Date.now() < this.reset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited\n\t */\n\tprivate get limited(): boolean {\n\t\treturn this.globalLimited || this.localLimited;\n\t}\n\n\t/**\n\t * The time until queued requests can continue\n\t */\n\tprivate get timeToReset(): number {\n\t\treturn this.reset + this.manager.options.offset - Date.now();\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * Delay all requests for the specified amount of time, handling global rate limits\n\t *\n\t * @param time - The amount of time to delay all requests for\n\t */\n\tprivate async globalDelayFor(time: number): Promise {\n\t\tawait sleep(time);\n\t\tthis.manager.globalDelay = null;\n\t}\n\n\t/*\n\t * Determines whether the request should be queued or whether a RateLimitError should be thrown\n\t */\n\tprivate async onRateLimit(rateLimitData: RateLimitData) {\n\t\tconst { options } = this.manager;\n\t\tif (!options.rejectOnRateLimit) return;\n\n\t\tconst shouldThrow =\n\t\t\ttypeof options.rejectOnRateLimit === 'function'\n\t\t\t\t? await options.rejectOnRateLimit(rateLimitData)\n\t\t\t\t: options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase()));\n\t\tif (shouldThrow) {\n\t\t\tthrow new RateLimitError(rateLimitData);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\tlet queue = this.#asyncQueue;\n\t\tlet queueType = QueueType.Standard;\n\t\t// Separate sublimited requests when already sublimited\n\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\tqueueType = QueueType.Sublimit;\n\t\t}\n\n\t\t// Wait for any previous requests to be completed before this one is run\n\t\tawait queue.wait({ signal: requestData.signal });\n\t\t// This set handles retroactively sublimiting requests\n\t\tif (queueType === QueueType.Standard) {\n\t\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\t\t/**\n\t\t\t\t * Remove the request from the standard queue, it should never be possible to get here while processing the\n\t\t\t\t * sublimit queue so there is no need to worry about shifting the wrong request\n\t\t\t\t */\n\t\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\t\tconst wait = queue.wait();\n\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\tawait wait;\n\t\t\t} else if (this.#sublimitPromise) {\n\t\t\t\t// Stall requests while the sublimit queue gets processed\n\t\t\t\tawait this.#sublimitPromise.promise;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request, and return the results\n\t\t\treturn await this.runRequest(routeId, url, options, requestData);\n\t\t} finally {\n\t\t\t// Allow the next request to fire\n\t\t\tqueue.shift();\n\t\t\tif (this.#shiftSublimit) {\n\t\t\t\tthis.#shiftSublimit = false;\n\t\t\t\tthis.#sublimitedQueue?.shift();\n\t\t\t}\n\n\t\t\t// If this request is the last request in a sublimit\n\t\t\tif (this.#sublimitedQueue?.remaining === 0) {\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitedQueue = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The method that actually makes the request to the api, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized api route with literal ids for major parameters\n\t * @param url - The fully resolved url to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\t/*\n\t\t * After calculations have been done, pre-emptively stop further requests\n\t\t * Potentially loop until this task can run if e.g. the global rate limit is hit twice\n\t\t */\n\t\twhile (this.limited) {\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\t\t\tlet delay: Promise;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t\t// If this is the first task to reach the global timeout, set the global delay\n\t\t\t\tif (!this.manager.globalDelay) {\n\t\t\t\t\t// The global delay function clears the global delay state when it is resolved\n\t\t\t\t\tthis.manager.globalDelay = this.globalDelayFor(timeout);\n\t\t\t\t}\n\n\t\t\t\tdelay = this.manager.globalDelay;\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t\tdelay = sleep(timeout);\n\t\t\t}\n\n\t\t\tconst rateLimitData: RateLimitData = {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t};\n\t\t\t// Let library users know they have hit a rate limit\n\t\t\tthis.manager.emit(RESTEvents.RateLimited, rateLimitData);\n\t\t\t// Determine whether a RateLimitError should be thrown\n\t\t\tawait this.onRateLimit(rateLimitData);\n\t\t\t// When not erroring, emit debug for what is happening\n\t\t\tif (isGlobal) {\n\t\t\t\tthis.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`);\n\t\t\t} else {\n\t\t\t\tthis.debug(`Waiting ${timeout}ms for rate limit to pass`);\n\t\t\t}\n\n\t\t\t// Wait the remaining time left before the rate limit resets\n\t\t\tawait delay;\n\t\t}\n\n\t\t// As the request goes out, update the global usage information\n\t\tif (!this.manager.globalReset || this.manager.globalReset < Date.now()) {\n\t\t\tthis.manager.globalReset = Date.now() + 1_000;\n\t\t\tthis.manager.globalRemaining = this.manager.options.globalRequestsPerSecond;\n\t\t}\n\n\t\tthis.manager.globalRemaining--;\n\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst controller = new AbortController();\n\t\tconst timeout = setTimeout(() => controller.abort(), this.manager.options.timeout).unref();\n\t\tif (requestData.signal) {\n\t\t\t// The type polyfill is required because Node.js's types are incomplete.\n\t\t\tconst signal = requestData.signal as PolyFillAbortSignal;\n\t\t\t// If the user signal was aborted, abort the controller, else abort the local signal.\n\t\t\t// The reason why we don't re-use the user's signal, is because users may use the same signal for multiple\n\t\t\t// requests, and we do not want to cause unexpected side-effects.\n\t\t\tif (signal.aborted) controller.abort();\n\t\t\telse signal.addEventListener('abort', () => controller.abort());\n\t\t}\n\n\t\tlet res: Dispatcher.ResponseData;\n\t\ttry {\n\t\t\tres = await request(url, { ...options, signal: controller.signal });\n\t\t} catch (error: unknown) {\n\t\t\tif (!(error instanceof Error)) throw error;\n\t\t\t// Retry the specified number of times if needed\n\t\t\tif (shouldRetry(error) && retries !== this.manager.options.retries) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn await this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t}\n\n\t\tif (this.manager.listenerCount(RESTEvents.Response)) {\n\t\t\tthis.manager.emit(\n\t\t\t\tRESTEvents.Response,\n\t\t\t\t{\n\t\t\t\t\tmethod,\n\t\t\t\t\tpath: routeId.original,\n\t\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\t\toptions,\n\t\t\t\t\tdata: requestData,\n\t\t\t\t\tretries,\n\t\t\t\t},\n\t\t\t\t{ ...res },\n\t\t\t);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\n\t\tconst limit = parseHeader(res.headers['x-ratelimit-limit']);\n\t\tconst remaining = parseHeader(res.headers['x-ratelimit-remaining']);\n\t\tconst reset = parseHeader(res.headers['x-ratelimit-reset-after']);\n\t\tconst hash = parseHeader(res.headers['x-ratelimit-bucket']);\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Update the total number of requests that can be made before the rate limit resets\n\t\tthis.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY;\n\t\t// Update the number of remaining requests that can be made before the rate limit resets\n\t\tthis.remaining = remaining ? Number(remaining) : 1;\n\t\t// Update the time when this rate limit resets (reset-after is in seconds)\n\t\tthis.reset = reset ? Number(reset) * 1_000 + Date.now() + this.manager.options.offset : Date.now();\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Handle buckets via the hash header retroactively\n\t\tif (hash && hash !== this.hash) {\n\t\t\t// Let library users know when rate limit buckets have been updated\n\t\t\tthis.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\\n'));\n\t\t\t// This queue will eventually be eliminated via attrition\n\t\t\tthis.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { value: hash, lastAccess: Date.now() });\n\t\t} else if (hash) {\n\t\t\t// Handle the case where hash value doesn't change\n\t\t\t// Fetch the hash data from the manager\n\t\t\tconst hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`);\n\n\t\t\t// When fetched, update the last access of the hash\n\t\t\tif (hashData) {\n\t\t\t\thashData.lastAccess = Date.now();\n\t\t\t}\n\t\t}\n\n\t\t// Handle retryAfter, which means we have actually hit a rate limit\n\t\tlet sublimitTimeout: number | null = null;\n\t\tif (retryAfter > 0) {\n\t\t\tif (res.headers['x-ratelimit-global'] !== undefined) {\n\t\t\t\tthis.manager.globalRemaining = 0;\n\t\t\t\tthis.manager.globalReset = Date.now() + retryAfter;\n\t\t\t} else if (!this.localLimited) {\n\t\t\t\t/*\n\t\t\t\t * This is a sublimit (e.g. 2 channel name changes/10 minutes) since the headers don't indicate a\n\t\t\t\t * route-wide rate limit. Don't update remaining or reset to avoid rate limiting the whole\n\t\t\t\t * endpoint, just set a reset time on the request itself to avoid retrying too soon.\n\t\t\t\t */\n\t\t\t\tsublimitTimeout = retryAfter;\n\t\t\t}\n\t\t}\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tif (!invalidCountResetTime || invalidCountResetTime < Date.now()) {\n\t\t\t\tinvalidCountResetTime = Date.now() + 1_000 * 60 * 10;\n\t\t\t\tinvalidCount = 0;\n\t\t\t}\n\n\t\t\tinvalidCount++;\n\n\t\t\tconst emitInvalid =\n\t\t\t\tthis.manager.options.invalidRequestWarningInterval > 0 &&\n\t\t\t\tinvalidCount % this.manager.options.invalidRequestWarningInterval === 0;\n\t\t\tif (emitInvalid) {\n\t\t\t\t// Let library users know periodically about invalid requests\n\t\t\t\tthis.manager.emit(RESTEvents.InvalidRequestWarning, {\n\t\t\t\t\tcount: invalidCount,\n\t\t\t\t\tremainingTime: invalidCountResetTime - Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t}\n\n\t\t\tawait this.onRateLimit({\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal.toString()}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${limit}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\t\t\t// If caused by a sublimit, wait it out here so other requests on the route can be handled\n\t\t\tif (sublimitTimeout) {\n\t\t\t\t// Normally the sublimit queue will not exist, however, if a sublimit is hit while in the sublimit queue, it will\n\t\t\t\tconst firstSublimit = !this.#sublimitedQueue;\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\tthis.#sublimitedQueue = new AsyncQueue();\n\t\t\t\t\tvoid this.#sublimitedQueue.wait();\n\t\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\t}\n\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitPromise = null;\n\t\t\t\tawait sleep(sublimitTimeout);\n\t\t\t\tlet resolve: () => void;\n\t\t\t\t// eslint-disable-next-line promise/param-names, no-promise-executor-return\n\t\t\t\tconst promise = new Promise((res) => (resolve = res));\n\t\t\t\tthis.#sublimitPromise = { promise, resolve: resolve! };\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\t// Re-queue this request so it can be shifted by the finally\n\t\t\t\t\tawait this.#asyncQueue.wait();\n\t\t\t\t\tthis.#shiftSublimit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else if (status >= 500 && status < 600) {\n\t\t\t// Retry the specified number of times for possible server side issues\n\t\t\tif (retries !== this.manager.options.retries) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\t// We are out of retries, throw an error\n\t\t\tthrow new HTTPError(status, method, url, requestData);\n\t\t} else {\n\t\t\t// Handle possible malformed requests\n\t\t\tif (status >= 400 && status < 500) {\n\t\t\t\t// If we receive this status code, it means the token we had is no longer valid.\n\t\t\t\tif (status === 401 && requestData.auth) {\n\t\t\t\t\tthis.manager.setToken(null!);\n\t\t\t\t}\n\n\t\t\t\t// The request will not succeed for some reason, parse the error returned from the api\n\t\t\t\tconst data = (await parseResponse(res)) as DiscordErrorData | OAuthErrorData;\n\t\t\t\t// throw the API error\n\t\t\t\tthrow new DiscordAPIError(data, 'code' in data ? data.code : data.error, status, method, url, requestData);\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\t}\n}\n\ninterface PolyFillAbortSignal {\n\treadonly aborted: boolean;\n\taddEventListener(type: 'abort', listener: () => void): void;\n\tremoveEventListener(type: 'abort', listener: () => void): void;\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { URLSearchParams } from 'node:url';\nimport { types } from 'node:util';\nimport type { RESTPatchAPIChannelJSONBody } from 'discord-api-types/v10';\nimport { FormData, type Dispatcher, type RequestInit } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport { RequestMethod } from '../RequestManager.js';\n\nexport function parseHeader(header: string[] | string | undefined): string | undefined {\n\tif (header === undefined || typeof header === 'string') {\n\t\treturn header;\n\t}\n\n\treturn header.join(';');\n}\n\nfunction serializeSearchParam(value: unknown): string | null {\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn value;\n\t\tcase 'number':\n\t\tcase 'bigint':\n\t\tcase 'boolean':\n\t\t\treturn value.toString();\n\t\tcase 'object':\n\t\t\tif (value === null) return null;\n\t\t\tif (value instanceof Date) {\n\t\t\t\treturn Number.isNaN(value.getTime()) ? null : value.toISOString();\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-base-to-string\n\t\t\tif (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) return value.toString();\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Creates and populates an URLSearchParams instance from an object, stripping\n * out null and undefined values, while also coercing non-strings to strings.\n *\n * @param options - The options to use\n * @returns A populated URLSearchParams instance\n */\nexport function makeURLSearchParams(options?: Readonly) {\n\tconst params = new URLSearchParams();\n\tif (!options) return params;\n\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tconst serialized = serializeSearchParam(value);\n\t\tif (serialized !== null) params.append(key, serialized);\n\t}\n\n\treturn params;\n}\n\n/**\n * Converts the response to usable data\n *\n * @param res - The fetch response\n */\nexport async function parseResponse(res: Dispatcher.ResponseData): Promise {\n\tconst header = parseHeader(res.headers['content-type']);\n\tif (header?.startsWith('application/json')) {\n\t\treturn res.body.json();\n\t}\n\n\treturn res.body.arrayBuffer();\n}\n\n/**\n * Check whether a request falls under a sublimit\n *\n * @param bucketRoute - The buckets route identifier\n * @param body - The options provided as JSON data\n * @param method - The HTTP method that will be used to make the request\n * @returns Whether the request falls under a sublimit\n */\nexport function hasSublimit(bucketRoute: string, body?: unknown, method?: string): boolean {\n\t// TODO: Update for new sublimits\n\t// Currently known sublimits:\n\t// Editing channel `name` or `topic`\n\tif (bucketRoute === '/channels/:id') {\n\t\tif (typeof body !== 'object' || body === null) return false;\n\t\t// This should never be a POST body, but just in case\n\t\tif (method !== RequestMethod.Patch) return false;\n\t\tconst castedBody = body as RESTPatchAPIChannelJSONBody;\n\t\treturn ['name', 'topic'].some((key) => Reflect.has(castedBody, key));\n\t}\n\n\t// If we are checking if a request has a sublimit on a route not checked above, sublimit all requests to avoid a flood of 429s\n\treturn true;\n}\n\nexport async function resolveBody(body: RequestInit['body']): Promise {\n\t// eslint-disable-next-line no-eq-null, eqeqeq\n\tif (body == null) {\n\t\treturn null;\n\t} else if (typeof body === 'string') {\n\t\treturn body;\n\t} else if (types.isUint8Array(body)) {\n\t\treturn body;\n\t} else if (types.isArrayBuffer(body)) {\n\t\treturn new Uint8Array(body);\n\t} else if (body instanceof URLSearchParams) {\n\t\treturn body.toString();\n\t} else if (body instanceof DataView) {\n\t\treturn new Uint8Array(body.buffer);\n\t} else if (body instanceof Blob) {\n\t\treturn new Uint8Array(await body.arrayBuffer());\n\t} else if (body instanceof FormData) {\n\t\treturn body;\n\t} else if ((body as Iterable)[Symbol.iterator]) {\n\t\tconst chunks = [...(body as Iterable)];\n\t\tconst length = chunks.reduce((a, b) => a + b.length, 0);\n\n\t\tconst uint8 = new Uint8Array(length);\n\t\tlet lengthUsed = 0;\n\n\t\treturn chunks.reduce((a, b) => {\n\t\t\ta.set(b, lengthUsed);\n\t\t\tlengthUsed += b.length;\n\t\t\treturn a;\n\t\t}, uint8);\n\t} else if ((body as AsyncIterable)[Symbol.asyncIterator]) {\n\t\tconst chunks: Uint8Array[] = [];\n\n\t\tfor await (const chunk of body as AsyncIterable) {\n\t\t\tchunks.push(chunk);\n\t\t}\n\n\t\treturn Buffer.concat(chunks);\n\t}\n\n\tthrow new TypeError(`Unable to resolve body.`);\n}\n\n/**\n * Check whether an error indicates that a retry can be attempted\n *\n * @param error - The error thrown by the network request\n * @returns Whether the error indicates a retry should be attempted\n */\nexport function shouldRetry(error: Error | NodeJS.ErrnoException) {\n\t// Retry for possible timed out requests\n\tif (error.name === 'AbortError') return true;\n\t// Downlevel ECONNRESET to retry as it may be recoverable\n\treturn ('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET');\n}\n","import { EventEmitter } from 'node:events';\nimport type { Collection } from '@discordjs/collection';\nimport type { request, Dispatcher } from 'undici';\nimport { CDN } from './CDN.js';\nimport {\n\tRequestManager,\n\tRequestMethod,\n\ttype HashData,\n\ttype HandlerRequestData,\n\ttype InternalRequest,\n\ttype RequestData,\n\ttype RouteLike,\n} from './RequestManager.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { DefaultRestOptions, RESTEvents } from './utils/constants.js';\nimport { parseResponse } from './utils/utils.js';\n\n/**\n * Options to be passed when creating the REST instance\n */\nexport interface RESTOptions {\n\t/**\n\t * The agent to set globally\n\t */\n\tagent: Dispatcher;\n\t/**\n\t * The base api path, without version\n\t *\n\t * @defaultValue `'https://discord.com/api'`\n\t */\n\tapi: string;\n\t/**\n\t * The authorization prefix to use for requests, useful if you want to use\n\t * bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix: 'Bearer' | 'Bot';\n\t/**\n\t * The cdn path\n\t *\n\t * @defaultValue 'https://cdn.discordapp.com'\n\t */\n\tcdn: string;\n\t/**\n\t * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)\n\t *\n\t * @defaultValue `50`\n\t */\n\tglobalRequestsPerSecond: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)\n\t *\n\t * @defaultValue `3_600_000`\n\t */\n\thandlerSweepInterval: number;\n\t/**\n\t * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)\n\t *\n\t * @defaultValue `86_400_000`\n\t */\n\thashLifetime: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)\n\t *\n\t * @defaultValue `14_400_000`\n\t */\n\thashSweepInterval: number;\n\t/**\n\t * Additional headers to send for all API requests\n\t *\n\t * @defaultValue `{}`\n\t */\n\theaders: Record;\n\t/**\n\t * The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).\n\t * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.\n\t *\n\t * @defaultValue `0`\n\t */\n\tinvalidRequestWarningInterval: number;\n\t/**\n\t * The extra offset to add to rate limits in milliseconds\n\t *\n\t * @defaultValue `50`\n\t */\n\toffset: number;\n\t/**\n\t * Determines how rate limiting and pre-emptive throttling should be handled.\n\t * When an array of strings, each element is treated as a prefix for the request route\n\t * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)\n\t * for which to throw {@link RateLimitError}s. All other request routes will be queued normally\n\t *\n\t * @defaultValue `null`\n\t */\n\trejectOnRateLimit: RateLimitQueueFilter | string[] | null;\n\t/**\n\t * The number of retries for errors with the 500 code, or errors\n\t * that timeout\n\t *\n\t * @defaultValue `3`\n\t */\n\tretries: number;\n\t/**\n\t * The time to wait in milliseconds before a request is aborted\n\t *\n\t * @defaultValue `15_000`\n\t */\n\ttimeout: number;\n\t/**\n\t * Extra information to add to the user agent\n\t *\n\t * @defaultValue `Node.js ${process.version}`\n\t */\n\tuserAgentAppendix: string;\n\t/**\n\t * The version of the API to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\n/**\n * Data emitted on `RESTEvents.RateLimited`\n */\nexport interface RateLimitData {\n\t/**\n\t * Whether the rate limit that was reached was the global limit\n\t */\n\tglobal: boolean;\n\t/**\n\t * The bucket hash for this request\n\t */\n\thash: string;\n\t/**\n\t * The amount of requests we can perform before locking requests\n\t */\n\tlimit: number;\n\t/**\n\t * The major parameter of the route\n\t *\n\t * For example, in `/channels/x`, this will be `x`.\n\t * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.\n\t */\n\tmajorParameter: string;\n\t/**\n\t * The HTTP method being performed\n\t */\n\tmethod: string;\n\t/**\n\t * The route being hit in this request\n\t */\n\troute: string;\n\t/**\n\t * The time, in milliseconds, until the request-lock is reset\n\t */\n\ttimeToReset: number;\n\t/**\n\t * The full URL for this request\n\t */\n\turl: string;\n}\n\n/**\n * A function that determines whether the rate limit hit should throw an Error\n */\nexport type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise | boolean;\n\nexport interface APIRequest {\n\t/**\n\t * The data that was used to form the body of this request\n\t */\n\tdata: HandlerRequestData;\n\t/**\n\t * The HTTP method used in this request\n\t */\n\tmethod: string;\n\t/**\n\t * Additional HTTP options for this request\n\t */\n\toptions: RequestOptions;\n\t/**\n\t * The full path used to make the request\n\t */\n\tpath: RouteLike;\n\t/**\n\t * The number of times this request has been attempted\n\t */\n\tretries: number;\n\t/**\n\t * The API route identifying the ratelimit for this request\n\t */\n\troute: string;\n}\n\nexport interface InvalidRequestWarningData {\n\t/**\n\t * Number of invalid requests that have been made in the window\n\t */\n\tcount: number;\n\t/**\n\t * Time in milliseconds remaining before the count resets\n\t */\n\tremainingTime: number;\n}\n\nexport interface RestEvents {\n\thandlerSweep: [sweptHandlers: Collection];\n\thashSweep: [sweptHashes: Collection];\n\tinvalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];\n\tnewListener: [name: string, listener: (...args: any) => void];\n\trateLimited: [rateLimitInfo: RateLimitData];\n\tremoveListener: [name: string, listener: (...args: any) => void];\n\tresponse: [request: APIRequest, response: Dispatcher.ResponseData];\n\trestDebug: [info: string];\n}\n\nexport interface REST {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\nexport type RequestOptions = Exclude[1], undefined>;\n\nexport class REST extends EventEmitter {\n\tpublic readonly cdn: CDN;\n\n\tpublic readonly requestManager: RequestManager;\n\n\tpublic constructor(options: Partial = {}) {\n\t\tsuper();\n\t\tthis.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn);\n\t\tthis.requestManager = new RequestManager(options)\n\t\t\t.on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug))\n\t\t\t.on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited))\n\t\t\t.on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning))\n\t\t\t.on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep));\n\n\t\tthis.on('newListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.on(name, listener);\n\t\t});\n\t\tthis.on('removeListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.off(name, listener);\n\t\t});\n\t}\n\n\t/**\n\t * Gets the agent set for this instance\n\t */\n\tpublic getAgent() {\n\t\treturn this.requestManager.agent;\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this instance\n\t *\n\t * @param agent - Sets the agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.requestManager.setAgent(agent);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.requestManager.setToken(token);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a get request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async get(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Get });\n\t}\n\n\t/**\n\t * Runs a delete request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async delete(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Delete });\n\t}\n\n\t/**\n\t * Runs a post request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async post(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Post });\n\t}\n\n\t/**\n\t * Runs a put request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async put(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Put });\n\t}\n\n\t/**\n\t * Runs a patch request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async patch(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Patch });\n\t}\n\n\t/**\n\t * Runs a request from the api\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async request(options: InternalRequest) {\n\t\tconst response = await this.raw(options);\n\t\treturn parseResponse(response);\n\t}\n\n\t/**\n\t * Runs a request from the API, yielding the raw Response object\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async raw(options: InternalRequest) {\n\t\treturn this.requestManager.queueRequest(options);\n\t}\n}\n"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EAC1E;AAAA,EAQA,MAAa,IAAI,WAAsB,UAAuB,CAAC,GAAG;AACjE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,wBAA0B,CAAC;AAAA,EACzE;AAAA,EAQA,MAAa,MAAM,WAAsB,UAAuB,CAAC,GAAG;AACnE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,4BAA4B,CAAC;AAAA,EAC3E;AAAA,EAOA,MAAa,QAAQ,SAA0B;AAC9C,UAAM,WAAW,MAAM,KAAK,IAAI,OAAO;AACvC,WAAO,cAAc,QAAQ;AAAA,EAC9B;AAAA,EAOA,MAAa,IAAI,SAA0B;AAC1C,WAAO,KAAK,eAAe,aAAa,OAAO;AAAA,EAChD;AACD;AArHa;;;AT9NN,IAAM,UAAkB;","names":["process","RESTEvents","import_node_buffer","import_node_timers","import_undici","import_undici","import_node_url","import_undici","sleep","limit","timeout","res","RequestMethod","request","import_node_events"]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/lib/CDN.ts","../src/lib/utils/constants.ts","../src/lib/errors/DiscordAPIError.ts","../src/lib/errors/HTTPError.ts","../src/lib/errors/RateLimitError.ts","../src/lib/RequestManager.ts","../src/lib/handlers/BurstHandler.ts","../src/lib/utils/utils.ts","../src/lib/handlers/Shared.ts","../src/lib/handlers/SequentialHandler.ts","../src/lib/REST.ts"],"sourcesContent":["export * from './lib/CDN.js';\nexport * from './lib/errors/DiscordAPIError.js';\nexport * from './lib/errors/HTTPError.js';\nexport * from './lib/errors/RateLimitError.js';\nexport * from './lib/RequestManager.js';\nexport * from './lib/REST.js';\nexport * from './lib/utils/constants.js';\nexport { makeURLSearchParams, parseResponse } from './lib/utils/utils.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.7.1' as string;\n","/* eslint-disable jsdoc/check-param-names */\nimport { URL } from 'node:url';\nimport {\n\tALLOWED_EXTENSIONS,\n\tALLOWED_SIZES,\n\tALLOWED_STICKER_EXTENSIONS,\n\tDefaultRestOptions,\n\ttype ImageExtension,\n\ttype ImageSize,\n\ttype StickerExtension,\n} from './utils/constants.js';\n\n/**\n * The options used for image URLs\n */\nexport interface BaseImageURLOptions {\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: ImageExtension;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The options used for image URLs with animated content\n */\nexport interface ImageURLOptions extends BaseImageURLOptions {\n\t/**\n\t * Whether or not to prefer the static version of an image asset.\n\t */\n\tforceStatic?: boolean;\n}\n\n/**\n * The options to use when making a CDN URL\n */\nexport interface MakeURLOptions {\n\t/**\n\t * The allowed extensions that can be used\n\t */\n\tallowedExtensions?: readonly string[];\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: string | undefined;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The CDN link builder\n */\nexport class CDN {\n\tpublic constructor(private readonly base: string = DefaultRestOptions.cdn) {}\n\n\t/**\n\t * Generates an app asset URL for a client's asset.\n\t *\n\t * @param clientId - The client id that has the asset\n\t * @param assetHash - The hash provided by Discord for this asset\n\t * @param options - Optional options for the asset\n\t */\n\tpublic appAsset(clientId: string, assetHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/${clientId}/${assetHash}`, options);\n\t}\n\n\t/**\n\t * Generates an app icon URL for a client's icon.\n\t *\n\t * @param clientId - The client id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic appIcon(clientId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-icons/${clientId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates an avatar URL, e.g. for a user or a webhook.\n\t *\n\t * @param id - The id that has the icon\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic avatar(id: string, avatarHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a banner URL, e.g. for a user or a guild.\n\t *\n\t * @param id - The id that has the banner splash\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic banner(id: string, bannerHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL for a channel, e.g. a group DM.\n\t *\n\t * @param channelId - The channel id that has the icon\n\t * @param iconHash - The hash provided by Discord for this channel\n\t * @param options - Optional options for the icon\n\t */\n\tpublic channelIcon(channelId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates the default avatar URL for a discriminator.\n\t *\n\t * @param discriminator - The discriminator modulo 5\n\t */\n\tpublic defaultAvatar(discriminator: number): string {\n\t\treturn this.makeURL(`/embed/avatars/${discriminator}`, { extension: 'png' });\n\t}\n\n\t/**\n\t * Generates a discovery splash URL for a guild's discovery splash.\n\t *\n\t * @param guildId - The guild id that has the discovery splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic discoverySplash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates an emoji's URL for an emoji.\n\t *\n\t * @param emojiId - The emoji id\n\t * @param extension - The extension of the emoji\n\t */\n\tpublic emoji(emojiId: string, extension?: ImageExtension): string {\n\t\treturn this.makeURL(`/emojis/${emojiId}`, { extension });\n\t}\n\n\t/**\n\t * Generates a guild member avatar URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic guildMemberAvatar(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tavatarHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a guild member banner URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic guildMemberBanner(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tbannerHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL, e.g. for a guild.\n\t *\n\t * @param id - The id that has the icon splash\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic icon(id: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options);\n\t}\n\n\t/**\n\t * Generates a URL for the icon of a role\n\t *\n\t * @param roleId - The id of the role that has the icon\n\t * @param roleIconHash - The hash provided by Discord for this role icon\n\t * @param options - Optional options for the role icon\n\t */\n\tpublic roleIcon(roleId: string, roleIconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a guild invite splash URL for a guild's invite splash.\n\t *\n\t * @param guildId - The guild id that has the invite splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic splash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates a sticker URL.\n\t *\n\t * @param stickerId - The sticker id\n\t * @param extension - The extension of the sticker\n\t * @privateRemarks\n\t * Stickers cannot have a `.webp` extension, so we default to a `.png`\n\t */\n\tpublic sticker(stickerId: string, extension: StickerExtension = 'png'): string {\n\t\treturn this.makeURL(`/stickers/${stickerId}`, { allowedExtensions: ALLOWED_STICKER_EXTENSIONS, extension });\n\t}\n\n\t/**\n\t * Generates a sticker pack banner URL.\n\t *\n\t * @param bannerId - The banner id\n\t * @param options - Optional options for the banner\n\t */\n\tpublic stickerPackBanner(bannerId: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options);\n\t}\n\n\t/**\n\t * Generates a team icon URL for a team's icon.\n\t *\n\t * @param teamId - The team id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic teamIcon(teamId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/team-icons/${teamId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a cover image for a guild scheduled event.\n\t *\n\t * @param scheduledEventId - The scheduled event id\n\t * @param coverHash - The hash provided by discord for this cover image\n\t * @param options - Optional options for the cover image\n\t */\n\tpublic guildScheduledEventCover(\n\t\tscheduledEventId: string,\n\t\tcoverHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`.\n\t *\n\t * @param route - The base cdn route\n\t * @param hash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the link\n\t */\n\tprivate dynamicMakeURL(\n\t\troute: string,\n\t\thash: string,\n\t\t{ forceStatic = false, ...options }: Readonly = {},\n\t): string {\n\t\treturn this.makeURL(route, !forceStatic && hash.startsWith('a_') ? { ...options, extension: 'gif' } : options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource\n\t *\n\t * @param route - The base cdn route\n\t * @param options - The extension/size options for the link\n\t */\n\tprivate makeURL(\n\t\troute: string,\n\t\t{ allowedExtensions = ALLOWED_EXTENSIONS, extension = 'webp', size }: Readonly = {},\n\t): string {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\textension = String(extension).toLowerCase();\n\n\t\tif (!allowedExtensions.includes(extension)) {\n\t\t\tthrow new RangeError(`Invalid extension provided: ${extension}\\nMust be one of: ${allowedExtensions.join(', ')}`);\n\t\t}\n\n\t\tif (size && !ALLOWED_SIZES.includes(size)) {\n\t\t\tthrow new RangeError(`Invalid size provided: ${size}\\nMust be one of: ${ALLOWED_SIZES.join(', ')}`);\n\t\t}\n\n\t\tconst url = new URL(`${this.base}${route}.${extension}`);\n\n\t\tif (size) {\n\t\t\turl.searchParams.set('size', String(size));\n\t\t}\n\n\t\treturn url.toString();\n\t}\n}\n","import process from 'node:process';\nimport { APIVersion } from 'discord-api-types/v10';\nimport { Agent } from 'undici';\nimport type { RESTOptions } from '../REST.js';\n\nexport const DefaultUserAgent =\n\t`DiscordBot (https://discord.js.org, 1.7.1)` as `DiscordBot (https://discord.js.org, ${string})`;\n\n/**\n * The default string to append onto the user agent.\n */\nexport const DefaultUserAgentAppendix = process.release?.name === 'node' ? `Node.js/${process.version}` : '';\n\nexport const DefaultRestOptions = {\n\tget agent() {\n\t\treturn new Agent({\n\t\t\tconnect: {\n\t\t\t\ttimeout: 30_000,\n\t\t\t},\n\t\t});\n\t},\n\tapi: 'https://discord.com/api',\n\tauthPrefix: 'Bot',\n\tcdn: 'https://cdn.discordapp.com',\n\theaders: {},\n\tinvalidRequestWarningInterval: 0,\n\tglobalRequestsPerSecond: 50,\n\toffset: 50,\n\trejectOnRateLimit: null,\n\tretries: 3,\n\ttimeout: 15_000,\n\tuserAgentAppendix: DefaultUserAgentAppendix,\n\tversion: APIVersion,\n\thashSweepInterval: 14_400_000, // 4 Hours\n\thashLifetime: 86_400_000, // 24 Hours\n\thandlerSweepInterval: 3_600_000, // 1 Hour\n} as const satisfies Required;\n\n/**\n * The events that the REST manager emits\n */\nexport enum RESTEvents {\n\tDebug = 'restDebug',\n\tHandlerSweep = 'handlerSweep',\n\tHashSweep = 'hashSweep',\n\tInvalidRequestWarning = 'invalidRequestWarning',\n\tRateLimited = 'rateLimited',\n\tResponse = 'response',\n}\n\nexport const ALLOWED_EXTENSIONS = ['webp', 'png', 'jpg', 'jpeg', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_STICKER_EXTENSIONS = ['png', 'json', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1_024, 2_048, 4_096] as const satisfies readonly number[];\n\nexport type ImageExtension = (typeof ALLOWED_EXTENSIONS)[number];\nexport type StickerExtension = (typeof ALLOWED_STICKER_EXTENSIONS)[number];\nexport type ImageSize = (typeof ALLOWED_SIZES)[number];\n\nexport const OverwrittenMimeTypes = {\n\t// https://github.com/discordjs/discord.js/issues/8557\n\t'image/apng': 'image/png',\n} as const satisfies Readonly>;\n\nexport const BurstHandlerMajorIdKey = 'burst';\n","import type { InternalRequest, RawFile } from '../RequestManager.js';\n\ninterface DiscordErrorFieldInformation {\n\tcode: string;\n\tmessage: string;\n}\n\ninterface DiscordErrorGroupWrapper {\n\t_errors: DiscordError[];\n}\n\ntype DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | { [k: string]: DiscordError };\n\nexport interface DiscordErrorData {\n\tcode: number;\n\terrors?: DiscordError;\n\tmessage: string;\n}\n\nexport interface OAuthErrorData {\n\terror: string;\n\terror_description?: string;\n}\n\nexport interface RequestBody {\n\tfiles: RawFile[] | undefined;\n\tjson: unknown | undefined;\n}\n\nfunction isErrorGroupWrapper(error: DiscordError): error is DiscordErrorGroupWrapper {\n\treturn Reflect.has(error as Record, '_errors');\n}\n\nfunction isErrorResponse(error: DiscordError): error is DiscordErrorFieldInformation {\n\treturn typeof Reflect.get(error as Record, 'message') === 'string';\n}\n\n/**\n * Represents an API error returned by Discord\n */\nexport class DiscordAPIError extends Error {\n\tpublic requestBody: RequestBody;\n\n\t/**\n\t * @param rawError - The error reported by Discord\n\t * @param code - The error code reported by Discord\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic rawError: DiscordErrorData | OAuthErrorData,\n\t\tpublic code: number | string,\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(DiscordAPIError.getMessage(rawError));\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${DiscordAPIError.name}[${this.code}]`;\n\t}\n\n\tprivate static getMessage(error: DiscordErrorData | OAuthErrorData) {\n\t\tlet flattened = '';\n\t\tif ('code' in error) {\n\t\t\tif (error.errors) {\n\t\t\t\tflattened = [...this.flattenDiscordError(error.errors)].join('\\n');\n\t\t\t}\n\n\t\t\treturn error.message && flattened\n\t\t\t\t? `${error.message}\\n${flattened}`\n\t\t\t\t: error.message || flattened || 'Unknown Error';\n\t\t}\n\n\t\treturn error.error_description ?? 'No Description';\n\t}\n\n\tprivate static *flattenDiscordError(obj: DiscordError, key = ''): IterableIterator {\n\t\tif (isErrorResponse(obj)) {\n\t\t\treturn yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();\n\t\t}\n\n\t\tfor (const [otherKey, val] of Object.entries(obj)) {\n\t\t\tconst nextKey = otherKey.startsWith('_')\n\t\t\t\t? key\n\t\t\t\t: key\n\t\t\t\t? Number.isNaN(Number(otherKey))\n\t\t\t\t\t? `${key}.${otherKey}`\n\t\t\t\t\t: `${key}[${otherKey}]`\n\t\t\t\t: otherKey;\n\n\t\t\tif (typeof val === 'string') {\n\t\t\t\tyield val;\n\t\t\t} else if (isErrorGroupWrapper(val)) {\n\t\t\t\tfor (const error of val._errors) {\n\t\t\t\t\tyield* this.flattenDiscordError(error, nextKey);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield* this.flattenDiscordError(val, nextKey);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { STATUS_CODES } from 'node:http';\nimport type { InternalRequest } from '../RequestManager.js';\nimport type { RequestBody } from './DiscordAPIError.js';\n\n/**\n * Represents a HTTP error\n */\nexport class HTTPError extends Error {\n\tpublic requestBody: RequestBody;\n\n\tpublic override name = HTTPError.name;\n\n\t/**\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(STATUS_CODES[status]);\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n}\n","import type { RateLimitData } from '../REST.js';\n\nexport class RateLimitError extends Error implements RateLimitData {\n\tpublic timeToReset: number;\n\n\tpublic limit: number;\n\n\tpublic method: string;\n\n\tpublic hash: string;\n\n\tpublic url: string;\n\n\tpublic route: string;\n\n\tpublic majorParameter: string;\n\n\tpublic global: boolean;\n\n\tpublic constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData) {\n\t\tsuper();\n\t\tthis.timeToReset = timeToReset;\n\t\tthis.limit = limit;\n\t\tthis.method = method;\n\t\tthis.hash = hash;\n\t\tthis.url = url;\n\t\tthis.route = route;\n\t\tthis.majorParameter = majorParameter;\n\t\tthis.global = global;\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${RateLimitError.name}[${this.route}]`;\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { setInterval, clearInterval } from 'node:timers';\nimport type { URLSearchParams } from 'node:url';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { DiscordSnowflake } from '@sapphire/snowflake';\nimport { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';\nimport type { RESTOptions, RestEvents, RequestOptions } from './REST.js';\nimport { BurstHandler } from './handlers/BurstHandler.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { SequentialHandler } from './handlers/SequentialHandler.js';\nimport {\n\tBurstHandlerMajorIdKey,\n\tDefaultRestOptions,\n\tDefaultUserAgent,\n\tOverwrittenMimeTypes,\n\tRESTEvents,\n} from './utils/constants.js';\nimport { resolveBody } from './utils/utils.js';\n\n// Make this a lazy dynamic import as file-type is a pure ESM package\nconst getFileType = lazy(async () => import('file-type'));\n\n/**\n * Represents a file to be added to the request\n */\nexport interface RawFile {\n\t/**\n\t * Content-Type of the file\n\t */\n\tcontentType?: string;\n\t/**\n\t * The actual data for the file\n\t */\n\tdata: Buffer | boolean | number | string;\n\t/**\n\t * An explicit key to use for key of the formdata field for this file.\n\t * When not provided, the index of the file in the files array is used in the form `files[${index}]`.\n\t * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)\n\t */\n\tkey?: string;\n\t/**\n\t * The name of the file\n\t */\n\tname: string;\n}\n\n/**\n * Represents possible data to be given to an endpoint\n */\nexport interface RequestData {\n\t/**\n\t * Whether to append JSON data to form data instead of `payload_json` when sending files\n\t */\n\tappendToFormData?: boolean;\n\t/**\n\t * If this request needs the `Authorization` header\n\t *\n\t * @defaultValue `true`\n\t */\n\tauth?: boolean;\n\t/**\n\t * The authorization prefix to use for this request, useful if you use this with bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix?: 'Bearer' | 'Bot';\n\t/**\n\t * The body to send to this request.\n\t * If providing as BodyInit, set `passThroughBody: true`\n\t */\n\tbody?: BodyInit | unknown;\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.\n\t */\n\tdispatcher?: Agent;\n\t/**\n\t * Files to be attached to this request\n\t */\n\tfiles?: RawFile[] | undefined;\n\t/**\n\t * Additional headers to add to this request\n\t */\n\theaders?: Record;\n\t/**\n\t * Whether to pass-through the body property directly to `fetch()`.\n\t * This only applies when files is NOT present\n\t */\n\tpassThroughBody?: boolean;\n\t/**\n\t * Query string parameters to append to the called endpoint\n\t */\n\tquery?: URLSearchParams;\n\t/**\n\t * Reason to show in the audit logs\n\t */\n\treason?: string | undefined;\n\t/**\n\t * The signal to abort the queue entry or the REST call, where applicable\n\t */\n\tsignal?: AbortSignal | undefined;\n\t/**\n\t * If this request should be versioned\n\t *\n\t * @defaultValue `true`\n\t */\n\tversioned?: boolean;\n}\n\n/**\n * Possible headers for an API call\n */\nexport interface RequestHeaders {\n\tAuthorization?: string;\n\t'User-Agent': string;\n\t'X-Audit-Log-Reason'?: string;\n}\n\n/**\n * Possible API methods to be used when doing requests\n */\nexport enum RequestMethod {\n\tDelete = 'DELETE',\n\tGet = 'GET',\n\tPatch = 'PATCH',\n\tPost = 'POST',\n\tPut = 'PUT',\n}\n\nexport type RouteLike = `/${string}`;\n\n/**\n * Internal request options\n *\n * @internal\n */\nexport interface InternalRequest extends RequestData {\n\tfullRoute: RouteLike;\n\tmethod: RequestMethod;\n}\n\nexport type HandlerRequestData = Pick;\n\n/**\n * Parsed route data for an endpoint\n *\n * @internal\n */\nexport interface RouteData {\n\tbucketRoute: string;\n\tmajorParameter: string;\n\toriginal: RouteLike;\n}\n\n/**\n * Represents a hash and its associated fields\n *\n * @internal\n */\nexport interface HashData {\n\tlastAccess: number;\n\tvalue: string;\n}\n\nexport interface RequestManager {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\n/**\n * Represents the class that manages handlers for endpoints\n */\nexport class RequestManager extends EventEmitter {\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests\n\t * performed by this manager.\n\t */\n\tpublic agent: Dispatcher | null = null;\n\n\t/**\n\t * The number of requests remaining in the global bucket\n\t */\n\tpublic globalRemaining: number;\n\n\t/**\n\t * The promise used to wait out the global rate limit\n\t */\n\tpublic globalDelay: Promise | null = null;\n\n\t/**\n\t * The timestamp at which the global bucket resets\n\t */\n\tpublic globalReset = -1;\n\n\t/**\n\t * API bucket hashes that are cached from provided routes\n\t */\n\tpublic readonly hashes = new Collection();\n\n\t/**\n\t * Request handlers created from the bucket hash and the major parameters\n\t */\n\tpublic readonly handlers = new Collection();\n\n\t#token: string | null = null;\n\n\tprivate hashTimer!: NodeJS.Timer;\n\n\tprivate handlerTimer!: NodeJS.Timer;\n\n\tpublic readonly options: RESTOptions;\n\n\tpublic constructor(options: Partial) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultRestOptions, ...options };\n\t\tthis.options.offset = Math.max(0, this.options.offset);\n\t\tthis.globalRemaining = this.options.globalRequestsPerSecond;\n\t\tthis.agent = options.agent ?? null;\n\n\t\t// Start sweepers\n\t\tthis.setupSweepers();\n\t}\n\n\tprivate setupSweepers() {\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\tconst validateMaxInterval = (interval: number) => {\n\t\t\tif (interval > 14_400_000) {\n\t\t\t\tthrow new Error('Cannot set an interval greater than 4 hours');\n\t\t\t}\n\t\t};\n\n\t\tif (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.hashSweepInterval);\n\t\t\tthis.hashTimer = setInterval(() => {\n\t\t\t\tconst sweptHashes = new Collection();\n\t\t\t\tconst currentDate = Date.now();\n\n\t\t\t\t// Begin sweeping hash based on lifetimes\n\t\t\t\tthis.hashes.sweep((val, key) => {\n\t\t\t\t\t// `-1` indicates a global hash\n\t\t\t\t\tif (val.lastAccess === -1) return false;\n\n\t\t\t\t\t// Check if lifetime has been exceeded\n\t\t\t\t\tconst shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime;\n\n\t\t\t\t\t// Add hash to collection of swept hashes\n\t\t\t\t\tif (shouldSweep) {\n\t\t\t\t\t\t// Add to swept hashes\n\t\t\t\t\t\tsweptHashes.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit debug information\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`);\n\n\t\t\t\t\treturn shouldSweep;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HashSweep, sweptHashes);\n\t\t\t}, this.options.hashSweepInterval).unref();\n\t\t}\n\n\t\tif (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.handlerSweepInterval);\n\t\t\tthis.handlerTimer = setInterval(() => {\n\t\t\t\tconst sweptHandlers = new Collection();\n\n\t\t\t\t// Begin sweeping handlers based on activity\n\t\t\t\tthis.handlers.sweep((val, key) => {\n\t\t\t\t\tconst { inactive } = val;\n\n\t\t\t\t\t// Collect inactive handlers\n\t\t\t\t\tif (inactive) {\n\t\t\t\t\t\tsweptHandlers.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`);\n\t\t\t\t\treturn inactive;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HandlerSweep, sweptHandlers);\n\t\t\t}, this.options.handlerSweepInterval).unref();\n\t\t}\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this manager\n\t *\n\t * @param agent - The agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.agent = agent;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.#token = token;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Queues a request to be sent\n\t *\n\t * @param request - All the information needed to make a request\n\t * @returns The response from the api request\n\t */\n\tpublic async queueRequest(request: InternalRequest): Promise {\n\t\t// Generalize the endpoint to its route data\n\t\tconst routeId = RequestManager.generateRouteData(request.fullRoute, request.method);\n\t\t// Get the bucket hash for the generic route, or point to a global route otherwise\n\t\tconst hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {\n\t\t\tvalue: `Global(${request.method}:${routeId.bucketRoute})`,\n\t\t\tlastAccess: -1,\n\t\t};\n\n\t\t// Get the request handler for the obtained hash, with its major parameter\n\t\tconst handler =\n\t\t\tthis.handlers.get(`${hash.value}:${routeId.majorParameter}`) ??\n\t\t\tthis.createHandler(hash.value, routeId.majorParameter);\n\n\t\t// Resolve the request into usable fetch options\n\t\tconst { url, fetchOptions } = await this.resolveRequest(request);\n\n\t\t// Queue the request\n\t\treturn handler.queueRequest(routeId, url, fetchOptions, {\n\t\t\tbody: request.body,\n\t\t\tfiles: request.files,\n\t\t\tauth: request.auth !== false,\n\t\t\tsignal: request.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new rate limit handler from a hash, based on the hash and the major parameter\n\t *\n\t * @param hash - The hash for the route\n\t * @param majorParameter - The major parameter for this handler\n\t * @internal\n\t */\n\tprivate createHandler(hash: string, majorParameter: string) {\n\t\t// Create the async request queue to handle requests\n\t\tconst queue =\n\t\t\tmajorParameter === BurstHandlerMajorIdKey\n\t\t\t\t? new BurstHandler(this, hash, majorParameter)\n\t\t\t\t: new SequentialHandler(this, hash, majorParameter);\n\t\t// Save the queue based on its id\n\t\tthis.handlers.set(queue.id, queue);\n\n\t\treturn queue;\n\t}\n\n\t/**\n\t * Formats the request data to a usable format for fetch\n\t *\n\t * @param request - The request data\n\t */\n\tprivate async resolveRequest(request: InternalRequest): Promise<{ fetchOptions: RequestOptions; url: string }> {\n\t\tconst { options } = this;\n\n\t\tlet query = '';\n\n\t\t// If a query option is passed, use it\n\t\tif (request.query) {\n\t\t\tconst resolvedQuery = request.query.toString();\n\t\t\tif (resolvedQuery !== '') {\n\t\t\t\tquery = `?${resolvedQuery}`;\n\t\t\t}\n\t\t}\n\n\t\t// Create the required headers\n\t\tconst headers: RequestHeaders = {\n\t\t\t...this.options.headers,\n\t\t\t'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),\n\t\t};\n\n\t\t// If this request requires authorization (allowing non-\"authorized\" requests for webhooks)\n\t\tif (request.auth !== false) {\n\t\t\t// If we haven't received a token, throw an error\n\t\t\tif (!this.#token) {\n\t\t\t\tthrow new Error('Expected token to be set for this request, but none was present');\n\t\t\t}\n\n\t\t\theaders.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${this.#token}`;\n\t\t}\n\n\t\t// If a reason was set, set it's appropriate header\n\t\tif (request.reason?.length) {\n\t\t\theaders['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);\n\t\t}\n\n\t\t// Format the full request URL (api base, optional version, endpoint, optional querystring)\n\t\tconst url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${\n\t\t\trequest.fullRoute\n\t\t}${query}`;\n\n\t\tlet finalBody: RequestInit['body'];\n\t\tlet additionalHeaders: Record = {};\n\n\t\tif (request.files?.length) {\n\t\t\tconst formData = new FormData();\n\n\t\t\t// Attach all files to the request\n\t\t\tfor (const [index, file] of request.files.entries()) {\n\t\t\t\tconst fileKey = file.key ?? `files[${index}]`;\n\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#parameters\n\t\t\t\t// FormData.append only accepts a string or Blob.\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters\n\t\t\t\t// The Blob constructor accepts TypedArray/ArrayBuffer, strings, and Blobs.\n\t\t\t\tif (Buffer.isBuffer(file.data)) {\n\t\t\t\t\t// Try to infer the content type from the buffer if one isn't passed\n\t\t\t\t\tconst { fileTypeFromBuffer } = await getFileType();\n\t\t\t\t\tlet contentType = file.contentType;\n\t\t\t\t\tif (!contentType) {\n\t\t\t\t\t\tconst parsedType = (await fileTypeFromBuffer(file.data))?.mime;\n\t\t\t\t\t\tif (parsedType) {\n\t\t\t\t\t\t\tcontentType = OverwrittenMimeTypes[parsedType as keyof typeof OverwrittenMimeTypes] ?? parsedType;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tformData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);\n\t\t\t\t} else {\n\t\t\t\t\tformData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (request.body != null) {\n\t\t\t\tif (request.appendToFormData) {\n\t\t\t\t\tfor (const [key, value] of Object.entries(request.body as Record)) {\n\t\t\t\t\t\tformData.append(key, value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.append('payload_json', JSON.stringify(request.body));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set the final body to the form data\n\t\t\tfinalBody = formData;\n\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t} else if (request.body != null) {\n\t\t\tif (request.passThroughBody) {\n\t\t\t\tfinalBody = request.body as BodyInit;\n\t\t\t} else {\n\t\t\t\t// Stringify the JSON data\n\t\t\t\tfinalBody = JSON.stringify(request.body);\n\t\t\t\t// Set the additional headers to specify the content-type\n\t\t\t\tadditionalHeaders = { 'Content-Type': 'application/json' };\n\t\t\t}\n\t\t}\n\n\t\tfinalBody = await resolveBody(finalBody);\n\n\t\tconst fetchOptions: RequestOptions = {\n\t\t\theaders: { ...request.headers, ...additionalHeaders, ...headers } as Record,\n\t\t\tmethod: request.method.toUpperCase() as Dispatcher.HttpMethod,\n\t\t};\n\n\t\tif (finalBody !== undefined) {\n\t\t\tfetchOptions.body = finalBody as Exclude;\n\t\t}\n\n\t\t// Prioritize setting an agent per request, use the agent for this instance otherwise.\n\t\tfetchOptions.dispatcher = request.dispatcher ?? this.agent ?? undefined!;\n\n\t\treturn { url, fetchOptions };\n\t}\n\n\t/**\n\t * Stops the hash sweeping interval\n\t */\n\tpublic clearHashSweeper() {\n\t\tclearInterval(this.hashTimer);\n\t}\n\n\t/**\n\t * Stops the request handler sweeping interval\n\t */\n\tpublic clearHandlerSweeper() {\n\t\tclearInterval(this.handlerTimer);\n\t}\n\n\t/**\n\t * Generates route data for an endpoint:method\n\t *\n\t * @param endpoint - The raw endpoint to generalize\n\t * @param method - The HTTP method this endpoint is called without\n\t * @internal\n\t */\n\tprivate static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {\n\t\tif (endpoint.startsWith('/interactions/') && endpoint.endsWith('/callback')) {\n\t\t\treturn {\n\t\t\t\tmajorParameter: BurstHandlerMajorIdKey,\n\t\t\t\tbucketRoute: '/interactions/:id/:token/callback',\n\t\t\t\toriginal: endpoint,\n\t\t\t};\n\t\t}\n\n\t\tconst majorIdMatch = /^\\/(?:channels|guilds|webhooks)\\/(\\d{17,19})/.exec(endpoint);\n\n\t\t// Get the major id for this route - global otherwise\n\t\tconst majorId = majorIdMatch?.[1] ?? 'global';\n\n\t\tconst baseRoute = endpoint\n\t\t\t// Strip out all ids\n\t\t\t.replaceAll(/\\d{17,19}/g, ':id')\n\t\t\t// Strip out reaction as they fall under the same bucket\n\t\t\t.replace(/\\/reactions\\/(.*)/, '/reactions/:reaction');\n\n\t\tlet exceptions = '';\n\n\t\t// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)\n\t\t// https://github.com/discord/discord-api-docs/issues/1295\n\t\tif (method === RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {\n\t\t\tconst id = /\\d{17,19}$/.exec(endpoint)![0]!;\n\t\t\tconst timestamp = DiscordSnowflake.timestampFrom(id);\n\t\t\tif (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {\n\t\t\t\texceptions += '/Delete Old Message';\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmajorParameter: majorId,\n\t\t\tbucketRoute: baseRoute + exceptions,\n\t\t\toriginal: endpoint,\n\t\t};\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport type { Dispatcher } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { onRateLimit, parseHeader } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\nimport { handleErrors, incrementInvalidCount, makeNetworkRequest } from './Shared.js';\n\n/**\n * The structure used to handle burst requests for a given bucket.\n * Burst requests have no ratelimit handling but allow for pre- and post-processing\n * of data in the same manner as sequentially queued requests.\n *\n * @remarks\n * This queue may still emit a rate limit error if an unexpected 429 is hit\n */\nexport class BurstHandler implements IHandler {\n\t/**\n\t * {@inheritdoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic inactive = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\treturn this.runRequest(routeId, url, options, requestData);\n\t}\n\n\t/**\n\t * The method that actually makes the request to the API, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized API route with literal ids for major parameters\n\t * @param url - The fully resolved URL to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries);\n\n\t\t// Retry requested\n\t\tif (res === null) {\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tincrementInvalidCount(this.manager);\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// Unexpected ratelimit\n\t\t\tconst isGlobal = res.headers['x-ratelimit-global'] !== undefined;\n\t\t\tawait onRateLimit(this.manager, {\n\t\t\t\ttimeToReset: retryAfter,\n\t\t\t\tlimit: Number.POSITIVE_INFINITY,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${Number.POSITIVE_INFINITY}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : None`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\n\t\t\t// We are bypassing all other limits, but an encountered limit should be respected (it's probably a non-punished rate limit anyways)\n\t\t\tawait sleep(retryAfter);\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else {\n\t\t\tconst handled = await handleErrors(this.manager, res, method, url, requestData, retries);\n\t\t\tif (handled === null) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\treturn handled;\n\t\t}\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { URLSearchParams } from 'node:url';\nimport { types } from 'node:util';\nimport type { RESTPatchAPIChannelJSONBody } from 'discord-api-types/v10';\nimport { FormData, type Dispatcher, type RequestInit } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST.js';\nimport { type RequestManager, RequestMethod } from '../RequestManager.js';\nimport { RateLimitError } from '../errors/RateLimitError.js';\n\nexport function parseHeader(header: string[] | string | undefined): string | undefined {\n\tif (header === undefined || typeof header === 'string') {\n\t\treturn header;\n\t}\n\n\treturn header.join(';');\n}\n\nfunction serializeSearchParam(value: unknown): string | null {\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn value;\n\t\tcase 'number':\n\t\tcase 'bigint':\n\t\tcase 'boolean':\n\t\t\treturn value.toString();\n\t\tcase 'object':\n\t\t\tif (value === null) return null;\n\t\t\tif (value instanceof Date) {\n\t\t\t\treturn Number.isNaN(value.getTime()) ? null : value.toISOString();\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-base-to-string\n\t\t\tif (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) return value.toString();\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Creates and populates an URLSearchParams instance from an object, stripping\n * out null and undefined values, while also coercing non-strings to strings.\n *\n * @param options - The options to use\n * @returns A populated URLSearchParams instance\n */\nexport function makeURLSearchParams(options?: Readonly) {\n\tconst params = new URLSearchParams();\n\tif (!options) return params;\n\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tconst serialized = serializeSearchParam(value);\n\t\tif (serialized !== null) params.append(key, serialized);\n\t}\n\n\treturn params;\n}\n\n/**\n * Converts the response to usable data\n *\n * @param res - The fetch response\n */\nexport async function parseResponse(res: Dispatcher.ResponseData): Promise {\n\tconst header = parseHeader(res.headers['content-type']);\n\tif (header?.startsWith('application/json')) {\n\t\treturn res.body.json();\n\t}\n\n\treturn res.body.arrayBuffer();\n}\n\n/**\n * Check whether a request falls under a sublimit\n *\n * @param bucketRoute - The buckets route identifier\n * @param body - The options provided as JSON data\n * @param method - The HTTP method that will be used to make the request\n * @returns Whether the request falls under a sublimit\n */\nexport function hasSublimit(bucketRoute: string, body?: unknown, method?: string): boolean {\n\t// TODO: Update for new sublimits\n\t// Currently known sublimits:\n\t// Editing channel `name` or `topic`\n\tif (bucketRoute === '/channels/:id') {\n\t\tif (typeof body !== 'object' || body === null) return false;\n\t\t// This should never be a POST body, but just in case\n\t\tif (method !== RequestMethod.Patch) return false;\n\t\tconst castedBody = body as RESTPatchAPIChannelJSONBody;\n\t\treturn ['name', 'topic'].some((key) => Reflect.has(castedBody, key));\n\t}\n\n\t// If we are checking if a request has a sublimit on a route not checked above, sublimit all requests to avoid a flood of 429s\n\treturn true;\n}\n\nexport async function resolveBody(body: RequestInit['body']): Promise {\n\t// eslint-disable-next-line no-eq-null, eqeqeq\n\tif (body == null) {\n\t\treturn null;\n\t} else if (typeof body === 'string') {\n\t\treturn body;\n\t} else if (types.isUint8Array(body)) {\n\t\treturn body;\n\t} else if (types.isArrayBuffer(body)) {\n\t\treturn new Uint8Array(body);\n\t} else if (body instanceof URLSearchParams) {\n\t\treturn body.toString();\n\t} else if (body instanceof DataView) {\n\t\treturn new Uint8Array(body.buffer);\n\t} else if (body instanceof Blob) {\n\t\treturn new Uint8Array(await body.arrayBuffer());\n\t} else if (body instanceof FormData) {\n\t\treturn body;\n\t} else if ((body as Iterable)[Symbol.iterator]) {\n\t\tconst chunks = [...(body as Iterable)];\n\t\tconst length = chunks.reduce((a, b) => a + b.length, 0);\n\n\t\tconst uint8 = new Uint8Array(length);\n\t\tlet lengthUsed = 0;\n\n\t\treturn chunks.reduce((a, b) => {\n\t\t\ta.set(b, lengthUsed);\n\t\t\tlengthUsed += b.length;\n\t\t\treturn a;\n\t\t}, uint8);\n\t} else if ((body as AsyncIterable)[Symbol.asyncIterator]) {\n\t\tconst chunks: Uint8Array[] = [];\n\n\t\tfor await (const chunk of body as AsyncIterable) {\n\t\t\tchunks.push(chunk);\n\t\t}\n\n\t\treturn Buffer.concat(chunks);\n\t}\n\n\tthrow new TypeError(`Unable to resolve body.`);\n}\n\n/**\n * Check whether an error indicates that a retry can be attempted\n *\n * @param error - The error thrown by the network request\n * @returns Whether the error indicates a retry should be attempted\n */\nexport function shouldRetry(error: Error | NodeJS.ErrnoException) {\n\t// Retry for possible timed out requests\n\tif (error.name === 'AbortError') return true;\n\t// Downlevel ECONNRESET to retry as it may be recoverable\n\treturn ('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET');\n}\n\n/**\n * Determines whether the request should be queued or whether a RateLimitError should be thrown\n *\n * @internal\n */\nexport async function onRateLimit(manager: RequestManager, rateLimitData: RateLimitData) {\n\tconst { options } = manager;\n\tif (!options.rejectOnRateLimit) return;\n\n\tconst shouldThrow =\n\t\ttypeof options.rejectOnRateLimit === 'function'\n\t\t\t? await options.rejectOnRateLimit(rateLimitData)\n\t\t\t: options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase()));\n\tif (shouldThrow) {\n\t\tthrow new RateLimitError(rateLimitData);\n\t}\n}\n","import { setTimeout, clearTimeout } from 'node:timers';\nimport { request, type Dispatcher } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport type { DiscordErrorData, OAuthErrorData } from '../errors/DiscordAPIError.js';\nimport { DiscordAPIError } from '../errors/DiscordAPIError.js';\nimport { HTTPError } from '../errors/HTTPError.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { parseResponse, shouldRetry } from '../utils/utils.js';\nimport type { PolyFillAbortSignal } from './IHandler.js';\n\n/**\n * Invalid request limiting is done on a per-IP basis, not a per-token basis.\n * The best we can do is track invalid counts process-wide (on the theory that\n * users could have multiple bots run from one process) rather than per-bot.\n * Therefore, store these at file scope here rather than in the client's\n * RESTManager object.\n */\nlet invalidCount = 0;\nlet invalidCountResetTime: number | null = null;\n\n/**\n * Increment the invalid request count and emit warning if necessary\n *\n * @internal\n */\nexport function incrementInvalidCount(manager: RequestManager) {\n\tif (!invalidCountResetTime || invalidCountResetTime < Date.now()) {\n\t\tinvalidCountResetTime = Date.now() + 1_000 * 60 * 10;\n\t\tinvalidCount = 0;\n\t}\n\n\tinvalidCount++;\n\n\tconst emitInvalid =\n\t\tmanager.options.invalidRequestWarningInterval > 0 &&\n\t\tinvalidCount % manager.options.invalidRequestWarningInterval === 0;\n\tif (emitInvalid) {\n\t\t// Let library users know periodically about invalid requests\n\t\tmanager.emit(RESTEvents.InvalidRequestWarning, {\n\t\t\tcount: invalidCount,\n\t\t\tremainingTime: invalidCountResetTime - Date.now(),\n\t\t});\n\t}\n}\n\n/**\n * Performs the actual network request for a request handler\n *\n * @param manager - The manager that holds options and emits informational events\n * @param routeId - The generalized api route with literal ids for major parameters\n * @param url - The fully resolved url to make the request to\n * @param options - The fetch options needed to make the request\n * @param requestData - Extra data from the user's request needed for errors and additional processing\n * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)\n * @returns The respond from the network or `null` when the request should be retried\n * @internal\n */\nexport async function makeNetworkRequest(\n\tmanager: RequestManager,\n\trouteId: RouteData,\n\turl: string,\n\toptions: RequestOptions,\n\trequestData: HandlerRequestData,\n\tretries: number,\n) {\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(() => controller.abort(), manager.options.timeout).unref();\n\tif (requestData.signal) {\n\t\t// The type polyfill is required because Node.js's types are incomplete.\n\t\tconst signal = requestData.signal as unknown as PolyFillAbortSignal;\n\t\t// If the user signal was aborted, abort the controller, else abort the local signal.\n\t\t// The reason why we don't re-use the user's signal, is because users may use the same signal for multiple\n\t\t// requests, and we do not want to cause unexpected side-effects.\n\t\tif (signal.aborted) controller.abort();\n\t\telse signal.addEventListener('abort', () => controller.abort());\n\t}\n\n\tlet res: Dispatcher.ResponseData;\n\ttry {\n\t\tres = await request(url, { ...options, signal: controller.signal });\n\t} catch (error: unknown) {\n\t\tif (!(error instanceof Error)) throw error;\n\t\t// Retry the specified number of times if needed\n\t\tif (shouldRetry(error) && retries !== manager.options.retries) {\n\t\t\t// Retry is handled by the handler upon receiving null\n\t\t\treturn null;\n\t\t}\n\n\t\tthrow error;\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n\n\tif (manager.listenerCount(RESTEvents.Response)) {\n\t\tmanager.emit(\n\t\t\tRESTEvents.Response,\n\t\t\t{\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\tpath: routeId.original,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\toptions,\n\t\t\t\tdata: requestData,\n\t\t\t\tretries,\n\t\t\t},\n\t\t\t{ ...res },\n\t\t);\n\t}\n\n\treturn res;\n}\n\n/**\n * Handles 5xx and 4xx errors (not 429's) conventionally. 429's should be handled before calling this function\n *\n * @param manager - The manager that holds options and emits informational events\n * @param res - The response received from {@link makeNetworkRequest}\n * @param method - The method used to make the request\n * @param url - The fully resolved url to make the request to\n * @param requestData - Extra data from the user's request needed for errors and additional processing\n * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)\n * @returns - The response if the status code is not handled or null to request a retry\n */\nexport async function handleErrors(\n\tmanager: RequestManager,\n\tres: Dispatcher.ResponseData,\n\tmethod: string,\n\turl: string,\n\trequestData: HandlerRequestData,\n\tretries: number,\n) {\n\tconst status = res.statusCode;\n\tif (status >= 500 && status < 600) {\n\t\t// Retry the specified number of times for possible server side issues\n\t\tif (retries !== manager.options.retries) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// We are out of retries, throw an error\n\t\tthrow new HTTPError(status, method, url, requestData);\n\t} else {\n\t\t// Handle possible malformed requests\n\t\tif (status >= 400 && status < 500) {\n\t\t\t// If we receive this status code, it means the token we had is no longer valid.\n\t\t\tif (status === 401 && requestData.auth) {\n\t\t\t\tmanager.setToken(null!);\n\t\t\t}\n\n\t\t\t// The request will not succeed for some reason, parse the error returned from the api\n\t\t\tconst data = (await parseResponse(res)) as DiscordErrorData | OAuthErrorData;\n\t\t\t// throw the API error\n\t\t\tthrow new DiscordAPIError(data, 'code' in data ? data.code : data.error, status, method, url, requestData);\n\t\t}\n\n\t\treturn res;\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport type { Dispatcher } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { hasSublimit, onRateLimit, parseHeader } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\nimport { handleErrors, incrementInvalidCount, makeNetworkRequest } from './Shared.js';\n\nconst enum QueueType {\n\tStandard,\n\tSublimit,\n}\n\n/**\n * The structure used to handle sequential requests for a given bucket\n */\nexport class SequentialHandler implements IHandler {\n\t/**\n\t * {@inheritDoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * The time this rate limit bucket will reset\n\t */\n\tprivate reset = -1;\n\n\t/**\n\t * The remaining requests that can be made before we are rate limited\n\t */\n\tprivate remaining = 1;\n\n\t/**\n\t * The total number of requests that can be made before we are rate limited\n\t */\n\tprivate limit = Number.POSITIVE_INFINITY;\n\n\t/**\n\t * The interface used to sequence async requests sequentially\n\t */\n\t#asyncQueue = new AsyncQueue();\n\n\t/**\n\t * The interface used to sequence sublimited async requests sequentially\n\t */\n\t#sublimitedQueue: AsyncQueue | null = null;\n\n\t/**\n\t * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed\n\t */\n\t#sublimitPromise: { promise: Promise; resolve(): void } | null = null;\n\n\t/**\n\t * Whether the sublimit queue needs to be shifted in the finally block\n\t */\n\t#shiftSublimit = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic get inactive(): boolean {\n\t\treturn (\n\t\t\tthis.#asyncQueue.remaining === 0 &&\n\t\t\t(this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) &&\n\t\t\t!this.limited\n\t\t);\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by the global limit\n\t */\n\tprivate get globalLimited(): boolean {\n\t\treturn this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by its limit\n\t */\n\tprivate get localLimited(): boolean {\n\t\treturn this.remaining <= 0 && Date.now() < this.reset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited\n\t */\n\tprivate get limited(): boolean {\n\t\treturn this.globalLimited || this.localLimited;\n\t}\n\n\t/**\n\t * The time until queued requests can continue\n\t */\n\tprivate get timeToReset(): number {\n\t\treturn this.reset + this.manager.options.offset - Date.now();\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * Delay all requests for the specified amount of time, handling global rate limits\n\t *\n\t * @param time - The amount of time to delay all requests for\n\t */\n\tprivate async globalDelayFor(time: number): Promise {\n\t\tawait sleep(time);\n\t\tthis.manager.globalDelay = null;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\tlet queue = this.#asyncQueue;\n\t\tlet queueType = QueueType.Standard;\n\t\t// Separate sublimited requests when already sublimited\n\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\tqueueType = QueueType.Sublimit;\n\t\t}\n\n\t\t// Wait for any previous requests to be completed before this one is run\n\t\tawait queue.wait({ signal: requestData.signal });\n\t\t// This set handles retroactively sublimiting requests\n\t\tif (queueType === QueueType.Standard) {\n\t\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\t\t/**\n\t\t\t\t * Remove the request from the standard queue, it should never be possible to get here while processing the\n\t\t\t\t * sublimit queue so there is no need to worry about shifting the wrong request\n\t\t\t\t */\n\t\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\t\tconst wait = queue.wait();\n\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\tawait wait;\n\t\t\t} else if (this.#sublimitPromise) {\n\t\t\t\t// Stall requests while the sublimit queue gets processed\n\t\t\t\tawait this.#sublimitPromise.promise;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request, and return the results\n\t\t\treturn await this.runRequest(routeId, url, options, requestData);\n\t\t} finally {\n\t\t\t// Allow the next request to fire\n\t\t\tqueue.shift();\n\t\t\tif (this.#shiftSublimit) {\n\t\t\t\tthis.#shiftSublimit = false;\n\t\t\t\tthis.#sublimitedQueue?.shift();\n\t\t\t}\n\n\t\t\t// If this request is the last request in a sublimit\n\t\t\tif (this.#sublimitedQueue?.remaining === 0) {\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitedQueue = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The method that actually makes the request to the api, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized api route with literal ids for major parameters\n\t * @param url - The fully resolved url to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\t/*\n\t\t * After calculations have been done, pre-emptively stop further requests\n\t\t * Potentially loop until this task can run if e.g. the global rate limit is hit twice\n\t\t */\n\t\twhile (this.limited) {\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\t\t\tlet delay: Promise;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t\t// If this is the first task to reach the global timeout, set the global delay\n\t\t\t\tif (!this.manager.globalDelay) {\n\t\t\t\t\t// The global delay function clears the global delay state when it is resolved\n\t\t\t\t\tthis.manager.globalDelay = this.globalDelayFor(timeout);\n\t\t\t\t}\n\n\t\t\t\tdelay = this.manager.globalDelay;\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t\tdelay = sleep(timeout);\n\t\t\t}\n\n\t\t\tconst rateLimitData: RateLimitData = {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t};\n\t\t\t// Let library users know they have hit a rate limit\n\t\t\tthis.manager.emit(RESTEvents.RateLimited, rateLimitData);\n\t\t\t// Determine whether a RateLimitError should be thrown\n\t\t\tawait onRateLimit(this.manager, rateLimitData);\n\t\t\t// When not erroring, emit debug for what is happening\n\t\t\tif (isGlobal) {\n\t\t\t\tthis.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`);\n\t\t\t} else {\n\t\t\t\tthis.debug(`Waiting ${timeout}ms for rate limit to pass`);\n\t\t\t}\n\n\t\t\t// Wait the remaining time left before the rate limit resets\n\t\t\tawait delay;\n\t\t}\n\n\t\t// As the request goes out, update the global usage information\n\t\tif (!this.manager.globalReset || this.manager.globalReset < Date.now()) {\n\t\t\tthis.manager.globalReset = Date.now() + 1_000;\n\t\t\tthis.manager.globalRemaining = this.manager.options.globalRequestsPerSecond;\n\t\t}\n\n\t\tthis.manager.globalRemaining--;\n\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries);\n\n\t\t// Retry requested\n\t\tif (res === null) {\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\n\t\tconst limit = parseHeader(res.headers['x-ratelimit-limit']);\n\t\tconst remaining = parseHeader(res.headers['x-ratelimit-remaining']);\n\t\tconst reset = parseHeader(res.headers['x-ratelimit-reset-after']);\n\t\tconst hash = parseHeader(res.headers['x-ratelimit-bucket']);\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Update the total number of requests that can be made before the rate limit resets\n\t\tthis.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY;\n\t\t// Update the number of remaining requests that can be made before the rate limit resets\n\t\tthis.remaining = remaining ? Number(remaining) : 1;\n\t\t// Update the time when this rate limit resets (reset-after is in seconds)\n\t\tthis.reset = reset ? Number(reset) * 1_000 + Date.now() + this.manager.options.offset : Date.now();\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Handle buckets via the hash header retroactively\n\t\tif (hash && hash !== this.hash) {\n\t\t\t// Let library users know when rate limit buckets have been updated\n\t\t\tthis.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\\n'));\n\t\t\t// This queue will eventually be eliminated via attrition\n\t\t\tthis.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { value: hash, lastAccess: Date.now() });\n\t\t} else if (hash) {\n\t\t\t// Handle the case where hash value doesn't change\n\t\t\t// Fetch the hash data from the manager\n\t\t\tconst hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`);\n\n\t\t\t// When fetched, update the last access of the hash\n\t\t\tif (hashData) {\n\t\t\t\thashData.lastAccess = Date.now();\n\t\t\t}\n\t\t}\n\n\t\t// Handle retryAfter, which means we have actually hit a rate limit\n\t\tlet sublimitTimeout: number | null = null;\n\t\tif (retryAfter > 0) {\n\t\t\tif (res.headers['x-ratelimit-global'] !== undefined) {\n\t\t\t\tthis.manager.globalRemaining = 0;\n\t\t\t\tthis.manager.globalReset = Date.now() + retryAfter;\n\t\t\t} else if (!this.localLimited) {\n\t\t\t\t/*\n\t\t\t\t * This is a sublimit (e.g. 2 channel name changes/10 minutes) since the headers don't indicate a\n\t\t\t\t * route-wide rate limit. Don't update remaining or reset to avoid rate limiting the whole\n\t\t\t\t * endpoint, just set a reset time on the request itself to avoid retrying too soon.\n\t\t\t\t */\n\t\t\t\tsublimitTimeout = retryAfter;\n\t\t\t}\n\t\t}\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tincrementInvalidCount(this.manager);\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t}\n\n\t\t\tawait onRateLimit(this.manager, {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal.toString()}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${limit}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\t\t\t// If caused by a sublimit, wait it out here so other requests on the route can be handled\n\t\t\tif (sublimitTimeout) {\n\t\t\t\t// Normally the sublimit queue will not exist, however, if a sublimit is hit while in the sublimit queue, it will\n\t\t\t\tconst firstSublimit = !this.#sublimitedQueue;\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\tthis.#sublimitedQueue = new AsyncQueue();\n\t\t\t\t\tvoid this.#sublimitedQueue.wait();\n\t\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\t}\n\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitPromise = null;\n\t\t\t\tawait sleep(sublimitTimeout);\n\t\t\t\tlet resolve: () => void;\n\t\t\t\t// eslint-disable-next-line promise/param-names, no-promise-executor-return\n\t\t\t\tconst promise = new Promise((res) => (resolve = res));\n\t\t\t\tthis.#sublimitPromise = { promise, resolve: resolve! };\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\t// Re-queue this request so it can be shifted by the finally\n\t\t\t\t\tawait this.#asyncQueue.wait();\n\t\t\t\t\tthis.#shiftSublimit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else {\n\t\t\tconst handled = await handleErrors(this.manager, res, method, url, requestData, retries);\n\t\t\tif (handled === null) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\treturn handled;\n\t\t}\n\t}\n}\n","import { EventEmitter } from 'node:events';\nimport type { Collection } from '@discordjs/collection';\nimport type { request, Dispatcher } from 'undici';\nimport { CDN } from './CDN.js';\nimport {\n\tRequestManager,\n\tRequestMethod,\n\ttype HashData,\n\ttype HandlerRequestData,\n\ttype InternalRequest,\n\ttype RequestData,\n\ttype RouteLike,\n} from './RequestManager.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { DefaultRestOptions, RESTEvents } from './utils/constants.js';\nimport { parseResponse } from './utils/utils.js';\n\n/**\n * Options to be passed when creating the REST instance\n */\nexport interface RESTOptions {\n\t/**\n\t * The agent to set globally\n\t */\n\tagent: Dispatcher;\n\t/**\n\t * The base api path, without version\n\t *\n\t * @defaultValue `'https://discord.com/api'`\n\t */\n\tapi: string;\n\t/**\n\t * The authorization prefix to use for requests, useful if you want to use\n\t * bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix: 'Bearer' | 'Bot';\n\t/**\n\t * The cdn path\n\t *\n\t * @defaultValue 'https://cdn.discordapp.com'\n\t */\n\tcdn: string;\n\t/**\n\t * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)\n\t *\n\t * @defaultValue `50`\n\t */\n\tglobalRequestsPerSecond: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)\n\t *\n\t * @defaultValue `3_600_000`\n\t */\n\thandlerSweepInterval: number;\n\t/**\n\t * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)\n\t *\n\t * @defaultValue `86_400_000`\n\t */\n\thashLifetime: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)\n\t *\n\t * @defaultValue `14_400_000`\n\t */\n\thashSweepInterval: number;\n\t/**\n\t * Additional headers to send for all API requests\n\t *\n\t * @defaultValue `{}`\n\t */\n\theaders: Record;\n\t/**\n\t * The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).\n\t * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.\n\t *\n\t * @defaultValue `0`\n\t */\n\tinvalidRequestWarningInterval: number;\n\t/**\n\t * The extra offset to add to rate limits in milliseconds\n\t *\n\t * @defaultValue `50`\n\t */\n\toffset: number;\n\t/**\n\t * Determines how rate limiting and pre-emptive throttling should be handled.\n\t * When an array of strings, each element is treated as a prefix for the request route\n\t * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)\n\t * for which to throw {@link RateLimitError}s. All other request routes will be queued normally\n\t *\n\t * @defaultValue `null`\n\t */\n\trejectOnRateLimit: RateLimitQueueFilter | string[] | null;\n\t/**\n\t * The number of retries for errors with the 500 code, or errors\n\t * that timeout\n\t *\n\t * @defaultValue `3`\n\t */\n\tretries: number;\n\t/**\n\t * The time to wait in milliseconds before a request is aborted\n\t *\n\t * @defaultValue `15_000`\n\t */\n\ttimeout: number;\n\t/**\n\t * Extra information to add to the user agent\n\t *\n\t * @defaultValue DefaultUserAgentAppendix\n\t */\n\tuserAgentAppendix: string;\n\t/**\n\t * The version of the API to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\n/**\n * Data emitted on `RESTEvents.RateLimited`\n */\nexport interface RateLimitData {\n\t/**\n\t * Whether the rate limit that was reached was the global limit\n\t */\n\tglobal: boolean;\n\t/**\n\t * The bucket hash for this request\n\t */\n\thash: string;\n\t/**\n\t * The amount of requests we can perform before locking requests\n\t */\n\tlimit: number;\n\t/**\n\t * The major parameter of the route\n\t *\n\t * For example, in `/channels/x`, this will be `x`.\n\t * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.\n\t */\n\tmajorParameter: string;\n\t/**\n\t * The HTTP method being performed\n\t */\n\tmethod: string;\n\t/**\n\t * The route being hit in this request\n\t */\n\troute: string;\n\t/**\n\t * The time, in milliseconds, until the request-lock is reset\n\t */\n\ttimeToReset: number;\n\t/**\n\t * The full URL for this request\n\t */\n\turl: string;\n}\n\n/**\n * A function that determines whether the rate limit hit should throw an Error\n */\nexport type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise | boolean;\n\nexport interface APIRequest {\n\t/**\n\t * The data that was used to form the body of this request\n\t */\n\tdata: HandlerRequestData;\n\t/**\n\t * The HTTP method used in this request\n\t */\n\tmethod: string;\n\t/**\n\t * Additional HTTP options for this request\n\t */\n\toptions: RequestOptions;\n\t/**\n\t * The full path used to make the request\n\t */\n\tpath: RouteLike;\n\t/**\n\t * The number of times this request has been attempted\n\t */\n\tretries: number;\n\t/**\n\t * The API route identifying the ratelimit for this request\n\t */\n\troute: string;\n}\n\nexport interface InvalidRequestWarningData {\n\t/**\n\t * Number of invalid requests that have been made in the window\n\t */\n\tcount: number;\n\t/**\n\t * Time in milliseconds remaining before the count resets\n\t */\n\tremainingTime: number;\n}\n\nexport interface RestEvents {\n\thandlerSweep: [sweptHandlers: Collection];\n\thashSweep: [sweptHashes: Collection];\n\tinvalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];\n\tnewListener: [name: string, listener: (...args: any) => void];\n\trateLimited: [rateLimitInfo: RateLimitData];\n\tremoveListener: [name: string, listener: (...args: any) => void];\n\tresponse: [request: APIRequest, response: Dispatcher.ResponseData];\n\trestDebug: [info: string];\n}\n\nexport interface REST {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\nexport type RequestOptions = Exclude[1], undefined>;\n\nexport class REST extends EventEmitter {\n\tpublic readonly cdn: CDN;\n\n\tpublic readonly requestManager: RequestManager;\n\n\tpublic constructor(options: Partial = {}) {\n\t\tsuper();\n\t\tthis.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn);\n\t\tthis.requestManager = new RequestManager(options)\n\t\t\t.on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug))\n\t\t\t.on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited))\n\t\t\t.on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning))\n\t\t\t.on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep));\n\n\t\tthis.on('newListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.on(name, listener);\n\t\t});\n\t\tthis.on('removeListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.off(name, listener);\n\t\t});\n\t}\n\n\t/**\n\t * Gets the agent set for this instance\n\t */\n\tpublic getAgent() {\n\t\treturn this.requestManager.agent;\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this instance\n\t *\n\t * @param agent - Sets the agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.requestManager.setAgent(agent);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.requestManager.setToken(token);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a get request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async get(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Get });\n\t}\n\n\t/**\n\t * Runs a delete request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async delete(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Delete });\n\t}\n\n\t/**\n\t * Runs a post request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async post(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Post });\n\t}\n\n\t/**\n\t * Runs a put request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async put(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Put });\n\t}\n\n\t/**\n\t * Runs a patch request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async patch(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Patch });\n\t}\n\n\t/**\n\t * Runs a request from the api\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async request(options: InternalRequest) {\n\t\tconst response = await this.raw(options);\n\t\treturn parseResponse(response);\n\t}\n\n\t/**\n\t * Runs a request from the API, yielding the raw Response object\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async raw(options: InternalRequest) {\n\t\treturn this.requestManager.queueRequest(options);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,sBAAoB;;;ACDpB,0BAAoB;AACpB,iBAA2B;AAC3B,oBAAsB;AAGf,IAAM,mBACZ;AAKM,IAAM,2BAA2B,oBAAAA,QAAQ,SAAS,SAAS,SAAS,WAAW,oBAAAA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UAAM,WAAW,MAAM,KAAK,IAAI,OAAO;AACvC,WAAO,cAAc,QAAQ;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAa,IAAI,SAA0B;AAC1C,WAAO,KAAK,eAAe,aAAa,OAAO;AAAA,EAChD;AACD;AArHa;;;AX/NN,IAAM,UAAU;","names":["process","RESTEvents","import_node_buffer","import_node_timers","import_undici","import_node_url","import_undici","import_undici","sleep","import_promises","sleep","limit","res","RequestMethod","request","import_node_events"]} \ No newline at end of file diff --git a/node_modules/@discordjs/rest/dist/index.mjs b/node_modules/@discordjs/rest/dist/index.mjs index 053523a..850f466 100644 --- a/node_modules/@discordjs/rest/dist/index.mjs +++ b/node_modules/@discordjs/rest/dist/index.mjs @@ -8,7 +8,8 @@ import { URL } from "node:url"; import process from "node:process"; import { APIVersion } from "discord-api-types/v10"; import { Agent } from "undici"; -var DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.5.0)`; +var DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.7.1)`; +var DefaultUserAgentAppendix = process.release?.name === "node" ? `Node.js/${process.version}` : ""; var DefaultRestOptions = { get agent() { return new Agent({ @@ -27,11 +28,14 @@ var DefaultRestOptions = { rejectOnRateLimit: null, retries: 3, timeout: 15e3, - userAgentAppendix: `Node.js ${process.version}`, + userAgentAppendix: DefaultUserAgentAppendix, version: APIVersion, hashSweepInterval: 144e5, + // 4 Hours hashLifetime: 864e5, + // 24 Hours handlerSweepInterval: 36e5 + // 1 Hour }; var RESTEvents = /* @__PURE__ */ ((RESTEvents2) => { RESTEvents2["Debug"] = "restDebug"; @@ -43,71 +47,204 @@ var RESTEvents = /* @__PURE__ */ ((RESTEvents2) => { return RESTEvents2; })(RESTEvents || {}); var ALLOWED_EXTENSIONS = ["webp", "png", "jpg", "jpeg", "gif"]; -var ALLOWED_STICKER_EXTENSIONS = ["png", "json"]; +var ALLOWED_STICKER_EXTENSIONS = ["png", "json", "gif"]; var ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; +var OverwrittenMimeTypes = { + // https://github.com/discordjs/discord.js/issues/8557 + "image/apng": "image/png" +}; +var BurstHandlerMajorIdKey = "burst"; // src/lib/CDN.ts var CDN = class { constructor(base = DefaultRestOptions.cdn) { this.base = base; } + /** + * Generates an app asset URL for a client's asset. + * + * @param clientId - The client id that has the asset + * @param assetHash - The hash provided by Discord for this asset + * @param options - Optional options for the asset + */ appAsset(clientId, assetHash, options) { return this.makeURL(`/app-assets/${clientId}/${assetHash}`, options); } + /** + * Generates an app icon URL for a client's icon. + * + * @param clientId - The client id that has the icon + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ appIcon(clientId, iconHash, options) { return this.makeURL(`/app-icons/${clientId}/${iconHash}`, options); } + /** + * Generates an avatar URL, e.g. for a user or a webhook. + * + * @param id - The id that has the icon + * @param avatarHash - The hash provided by Discord for this avatar + * @param options - Optional options for the avatar + */ avatar(id, avatarHash, options) { return this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options); } + /** + * Generates a banner URL, e.g. for a user or a guild. + * + * @param id - The id that has the banner splash + * @param bannerHash - The hash provided by Discord for this banner + * @param options - Optional options for the banner + */ banner(id, bannerHash, options) { return this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options); } + /** + * Generates an icon URL for a channel, e.g. a group DM. + * + * @param channelId - The channel id that has the icon + * @param iconHash - The hash provided by Discord for this channel + * @param options - Optional options for the icon + */ channelIcon(channelId, iconHash, options) { return this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options); } + /** + * Generates the default avatar URL for a discriminator. + * + * @param discriminator - The discriminator modulo 5 + */ defaultAvatar(discriminator) { return this.makeURL(`/embed/avatars/${discriminator}`, { extension: "png" }); } + /** + * Generates a discovery splash URL for a guild's discovery splash. + * + * @param guildId - The guild id that has the discovery splash + * @param splashHash - The hash provided by Discord for this splash + * @param options - Optional options for the splash + */ discoverySplash(guildId, splashHash, options) { return this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options); } + /** + * Generates an emoji's URL for an emoji. + * + * @param emojiId - The emoji id + * @param extension - The extension of the emoji + */ emoji(emojiId, extension) { return this.makeURL(`/emojis/${emojiId}`, { extension }); } + /** + * Generates a guild member avatar URL. + * + * @param guildId - The id of the guild + * @param userId - The id of the user + * @param avatarHash - The hash provided by Discord for this avatar + * @param options - Optional options for the avatar + */ guildMemberAvatar(guildId, userId, avatarHash, options) { return this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options); } + /** + * Generates a guild member banner URL. + * + * @param guildId - The id of the guild + * @param userId - The id of the user + * @param bannerHash - The hash provided by Discord for this banner + * @param options - Optional options for the banner + */ guildMemberBanner(guildId, userId, bannerHash, options) { return this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options); } + /** + * Generates an icon URL, e.g. for a guild. + * + * @param id - The id that has the icon splash + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ icon(id, iconHash, options) { return this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options); } + /** + * Generates a URL for the icon of a role + * + * @param roleId - The id of the role that has the icon + * @param roleIconHash - The hash provided by Discord for this role icon + * @param options - Optional options for the role icon + */ roleIcon(roleId, roleIconHash, options) { return this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options); } + /** + * Generates a guild invite splash URL for a guild's invite splash. + * + * @param guildId - The guild id that has the invite splash + * @param splashHash - The hash provided by Discord for this splash + * @param options - Optional options for the splash + */ splash(guildId, splashHash, options) { return this.makeURL(`/splashes/${guildId}/${splashHash}`, options); } - sticker(stickerId, extension) { - return this.makeURL(`/stickers/${stickerId}`, { - allowedExtensions: ALLOWED_STICKER_EXTENSIONS, - extension: extension ?? "png" - }); + /** + * Generates a sticker URL. + * + * @param stickerId - The sticker id + * @param extension - The extension of the sticker + * @privateRemarks + * Stickers cannot have a `.webp` extension, so we default to a `.png` + */ + sticker(stickerId, extension = "png") { + return this.makeURL(`/stickers/${stickerId}`, { allowedExtensions: ALLOWED_STICKER_EXTENSIONS, extension }); } + /** + * Generates a sticker pack banner URL. + * + * @param bannerId - The banner id + * @param options - Optional options for the banner + */ stickerPackBanner(bannerId, options) { return this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options); } + /** + * Generates a team icon URL for a team's icon. + * + * @param teamId - The team id that has the icon + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ teamIcon(teamId, iconHash, options) { return this.makeURL(`/team-icons/${teamId}/${iconHash}`, options); } + /** + * Generates a cover image for a guild scheduled event. + * + * @param scheduledEventId - The scheduled event id + * @param coverHash - The hash provided by discord for this cover image + * @param options - Optional options for the cover image + */ guildScheduledEventCover(scheduledEventId, coverHash, options) { return this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options); } + /** + * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`. + * + * @param route - The base cdn route + * @param hash - The hash provided by Discord for this icon + * @param options - Optional options for the link + */ dynamicMakeURL(route, hash, { forceStatic = false, ...options } = {}) { return this.makeURL(route, !forceStatic && hash.startsWith("a_") ? { ...options, extension: "gif" } : options); } + /** + * Constructs the URL for the resource + * + * @param route - The base cdn route + * @param options - The extension/size options for the link + */ makeURL(route, { allowedExtensions = ALLOWED_EXTENSIONS, extension = "webp", size } = {}) { extension = String(extension).toLowerCase(); if (!allowedExtensions.includes(extension)) { @@ -137,6 +274,14 @@ function isErrorResponse(error) { } __name(isErrorResponse, "isErrorResponse"); var DiscordAPIError = class extends Error { + /** + * @param rawError - The error reported by Discord + * @param code - The error code reported by Discord + * @param status - The status code of the response + * @param method - The method of the request that erred + * @param url - The url of the request that erred + * @param bodyData - The unparsed data for the request that errored + */ constructor(rawError, code, status, method, url, bodyData) { super(DiscordAPIError.getMessage(rawError)); this.rawError = rawError; @@ -147,6 +292,9 @@ var DiscordAPIError = class extends Error { this.requestBody = { files: bodyData.files, json: bodyData.body }; } requestBody; + /** + * The name of the error + */ get name() { return `${DiscordAPIError.name}[${this.code}]`; } @@ -184,6 +332,12 @@ __name(DiscordAPIError, "DiscordAPIError"); // src/lib/errors/HTTPError.ts import { STATUS_CODES } from "node:http"; var HTTPError = class extends Error { + /** + * @param status - The status code of the response + * @param method - The method of the request that erred + * @param url - The url of the request that erred + * @param bodyData - The unparsed data for the request that errored + */ constructor(status, method, url, bodyData) { super(STATUS_CODES[status]); this.status = status; @@ -217,6 +371,9 @@ var RateLimitError = class extends Error { this.majorParameter = majorParameter; this.global = global; } + /** + * The name of the error + */ get name() { return `${RateLimitError.name}[${this.route}]`; } @@ -232,11 +389,8 @@ import { lazy } from "@discordjs/util"; import { DiscordSnowflake } from "@sapphire/snowflake"; import { FormData as FormData2 } from "undici"; -// src/lib/handlers/SequentialHandler.ts -import { setTimeout, clearTimeout } from "node:timers"; +// src/lib/handlers/BurstHandler.ts import { setTimeout as sleep } from "node:timers/promises"; -import { AsyncQueue } from "@sapphire/async-queue"; -import { request } from "undici"; // src/lib/utils/utils.ts import { Blob, Buffer as Buffer2 } from "node:buffer"; @@ -347,56 +501,293 @@ function shouldRetry(error) { return "code" in error && error.code === "ECONNRESET" || error.message.includes("ECONNRESET"); } __name(shouldRetry, "shouldRetry"); +async function onRateLimit(manager, rateLimitData) { + const { options } = manager; + if (!options.rejectOnRateLimit) + return; + const shouldThrow = typeof options.rejectOnRateLimit === "function" ? await options.rejectOnRateLimit(rateLimitData) : options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase())); + if (shouldThrow) { + throw new RateLimitError(rateLimitData); + } +} +__name(onRateLimit, "onRateLimit"); -// src/lib/handlers/SequentialHandler.ts +// src/lib/handlers/Shared.ts +import { setTimeout, clearTimeout } from "node:timers"; +import { request } from "undici"; var invalidCount = 0; var invalidCountResetTime = null; -var SequentialHandler = class { +function incrementInvalidCount(manager) { + if (!invalidCountResetTime || invalidCountResetTime < Date.now()) { + invalidCountResetTime = Date.now() + 1e3 * 60 * 10; + invalidCount = 0; + } + invalidCount++; + const emitInvalid = manager.options.invalidRequestWarningInterval > 0 && invalidCount % manager.options.invalidRequestWarningInterval === 0; + if (emitInvalid) { + manager.emit("invalidRequestWarning" /* InvalidRequestWarning */, { + count: invalidCount, + remainingTime: invalidCountResetTime - Date.now() + }); + } +} +__name(incrementInvalidCount, "incrementInvalidCount"); +async function makeNetworkRequest(manager, routeId, url, options, requestData, retries) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), manager.options.timeout).unref(); + if (requestData.signal) { + const signal = requestData.signal; + if (signal.aborted) + controller.abort(); + else + signal.addEventListener("abort", () => controller.abort()); + } + let res; + try { + res = await request(url, { ...options, signal: controller.signal }); + } catch (error) { + if (!(error instanceof Error)) + throw error; + if (shouldRetry(error) && retries !== manager.options.retries) { + return null; + } + throw error; + } finally { + clearTimeout(timeout); + } + if (manager.listenerCount("response" /* Response */)) { + manager.emit( + "response" /* Response */, + { + method: options.method ?? "get", + path: routeId.original, + route: routeId.bucketRoute, + options, + data: requestData, + retries + }, + { ...res } + ); + } + return res; +} +__name(makeNetworkRequest, "makeNetworkRequest"); +async function handleErrors(manager, res, method, url, requestData, retries) { + const status = res.statusCode; + if (status >= 500 && status < 600) { + if (retries !== manager.options.retries) { + return null; + } + throw new HTTPError(status, method, url, requestData); + } else { + if (status >= 400 && status < 500) { + if (status === 401 && requestData.auth) { + manager.setToken(null); + } + const data = await parseResponse(res); + throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData); + } + return res; + } +} +__name(handleErrors, "handleErrors"); + +// src/lib/handlers/BurstHandler.ts +var BurstHandler = class { + /** + * @param manager - The request manager + * @param hash - The hash that this RequestHandler handles + * @param majorParameter - The major parameter for this handler + */ constructor(manager, hash, majorParameter) { this.manager = manager; this.hash = hash; this.majorParameter = majorParameter; this.id = `${hash}:${majorParameter}`; } + /** + * {@inheritdoc IHandler.id} + */ id; - reset = -1; - remaining = 1; - limit = Number.POSITIVE_INFINITY; - #asyncQueue = new AsyncQueue(); - #sublimitedQueue = null; - #sublimitPromise = null; - #shiftSublimit = false; - get inactive() { - return this.#asyncQueue.remaining === 0 && (this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) && !this.limited; - } - get globalLimited() { - return this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset; - } - get localLimited() { - return this.remaining <= 0 && Date.now() < this.reset; - } - get limited() { - return this.globalLimited || this.localLimited; - } - get timeToReset() { - return this.reset + this.manager.options.offset - Date.now(); - } + /** + * {@inheritDoc IHandler.inactive} + */ + inactive = false; + /** + * Emits a debug message + * + * @param message - The message to debug + */ debug(message) { this.manager.emit("restDebug" /* Debug */, `[REST ${this.id}] ${message}`); } - async globalDelayFor(time) { - await sleep(time); - this.manager.globalDelay = null; + /** + * {@inheritDoc IHandler.queueRequest} + */ + async queueRequest(routeId, url, options, requestData) { + return this.runRequest(routeId, url, options, requestData); } - async onRateLimit(rateLimitData) { - const { options } = this.manager; - if (!options.rejectOnRateLimit) - return; - const shouldThrow = typeof options.rejectOnRateLimit === "function" ? await options.rejectOnRateLimit(rateLimitData) : options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase())); - if (shouldThrow) { - throw new RateLimitError(rateLimitData); + /** + * The method that actually makes the request to the API, and updates info about the bucket accordingly + * + * @param routeId - The generalized API route with literal ids for major parameters + * @param url - The fully resolved URL to make the request to + * @param options - The fetch options needed to make the request + * @param requestData - Extra data from the user's request needed for errors and additional processing + * @param retries - The number of retries this request has already attempted (recursion) + */ + async runRequest(routeId, url, options, requestData, retries = 0) { + const method = options.method ?? "get"; + const res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries); + if (res === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); + } + const status = res.statusCode; + let retryAfter = 0; + const retry = parseHeader(res.headers["retry-after"]); + if (retry) + retryAfter = Number(retry) * 1e3 + this.manager.options.offset; + if (status === 401 || status === 403 || status === 429) { + incrementInvalidCount(this.manager); + } + if (status >= 200 && status < 300) { + return res; + } else if (status === 429) { + const isGlobal = res.headers["x-ratelimit-global"] !== void 0; + await onRateLimit(this.manager, { + timeToReset: retryAfter, + limit: Number.POSITIVE_INFINITY, + method, + hash: this.hash, + url, + route: routeId.bucketRoute, + majorParameter: this.majorParameter, + global: isGlobal + }); + this.debug( + [ + "Encountered unexpected 429 rate limit", + ` Global : ${isGlobal}`, + ` Method : ${method}`, + ` URL : ${url}`, + ` Bucket : ${routeId.bucketRoute}`, + ` Major parameter: ${routeId.majorParameter}`, + ` Hash : ${this.hash}`, + ` Limit : ${Number.POSITIVE_INFINITY}`, + ` Retry After : ${retryAfter}ms`, + ` Sublimit : None` + ].join("\n") + ); + await sleep(retryAfter); + return this.runRequest(routeId, url, options, requestData, retries); + } else { + const handled = await handleErrors(this.manager, res, method, url, requestData, retries); + if (handled === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); + } + return handled; } } +}; +__name(BurstHandler, "BurstHandler"); + +// src/lib/handlers/SequentialHandler.ts +import { setTimeout as sleep2 } from "node:timers/promises"; +import { AsyncQueue } from "@sapphire/async-queue"; +var SequentialHandler = class { + /** + * @param manager - The request manager + * @param hash - The hash that this RequestHandler handles + * @param majorParameter - The major parameter for this handler + */ + constructor(manager, hash, majorParameter) { + this.manager = manager; + this.hash = hash; + this.majorParameter = majorParameter; + this.id = `${hash}:${majorParameter}`; + } + /** + * {@inheritDoc IHandler.id} + */ + id; + /** + * The time this rate limit bucket will reset + */ + reset = -1; + /** + * The remaining requests that can be made before we are rate limited + */ + remaining = 1; + /** + * The total number of requests that can be made before we are rate limited + */ + limit = Number.POSITIVE_INFINITY; + /** + * The interface used to sequence async requests sequentially + */ + #asyncQueue = new AsyncQueue(); + /** + * The interface used to sequence sublimited async requests sequentially + */ + #sublimitedQueue = null; + /** + * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed + */ + #sublimitPromise = null; + /** + * Whether the sublimit queue needs to be shifted in the finally block + */ + #shiftSublimit = false; + /** + * {@inheritDoc IHandler.inactive} + */ + get inactive() { + return this.#asyncQueue.remaining === 0 && (this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) && !this.limited; + } + /** + * If the rate limit bucket is currently limited by the global limit + */ + get globalLimited() { + return this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset; + } + /** + * If the rate limit bucket is currently limited by its limit + */ + get localLimited() { + return this.remaining <= 0 && Date.now() < this.reset; + } + /** + * If the rate limit bucket is currently limited + */ + get limited() { + return this.globalLimited || this.localLimited; + } + /** + * The time until queued requests can continue + */ + get timeToReset() { + return this.reset + this.manager.options.offset - Date.now(); + } + /** + * Emits a debug message + * + * @param message - The message to debug + */ + debug(message) { + this.manager.emit("restDebug" /* Debug */, `[REST ${this.id}] ${message}`); + } + /** + * Delay all requests for the specified amount of time, handling global rate limits + * + * @param time - The amount of time to delay all requests for + */ + async globalDelayFor(time) { + await sleep2(time); + this.manager.globalDelay = null; + } + /** + * {@inheritDoc IHandler.queueRequest} + */ async queueRequest(routeId, url, options, requestData) { let queue = this.#asyncQueue; let queueType = 0 /* Standard */; @@ -429,26 +820,35 @@ var SequentialHandler = class { } } } + /** + * The method that actually makes the request to the api, and updates info about the bucket accordingly + * + * @param routeId - The generalized api route with literal ids for major parameters + * @param url - The fully resolved url to make the request to + * @param options - The fetch options needed to make the request + * @param requestData - Extra data from the user's request needed for errors and additional processing + * @param retries - The number of retries this request has already attempted (recursion) + */ async runRequest(routeId, url, options, requestData, retries = 0) { while (this.limited) { const isGlobal = this.globalLimited; let limit2; - let timeout2; + let timeout; let delay; if (isGlobal) { limit2 = this.manager.options.globalRequestsPerSecond; - timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + timeout = this.manager.globalReset + this.manager.options.offset - Date.now(); if (!this.manager.globalDelay) { - this.manager.globalDelay = this.globalDelayFor(timeout2); + this.manager.globalDelay = this.globalDelayFor(timeout); } delay = this.manager.globalDelay; } else { limit2 = this.limit; - timeout2 = this.timeToReset; - delay = sleep(timeout2); + timeout = this.timeToReset; + delay = sleep2(timeout); } const rateLimitData = { - timeToReset: timeout2, + timeToReset: timeout, limit: limit2, method: options.method ?? "get", hash: this.hash, @@ -458,11 +858,11 @@ var SequentialHandler = class { global: isGlobal }; this.manager.emit("rateLimited" /* RateLimited */, rateLimitData); - await this.onRateLimit(rateLimitData); + await onRateLimit(this.manager, rateLimitData); if (isGlobal) { - this.debug(`Global rate limit hit, blocking all requests for ${timeout2}ms`); + this.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`); } else { - this.debug(`Waiting ${timeout2}ms for rate limit to pass`); + this.debug(`Waiting ${timeout}ms for rate limit to pass`); } await delay; } @@ -472,41 +872,9 @@ var SequentialHandler = class { } this.manager.globalRemaining--; const method = options.method ?? "get"; - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), this.manager.options.timeout).unref(); - if (requestData.signal) { - const signal = requestData.signal; - if (signal.aborted) - controller.abort(); - else - signal.addEventListener("abort", () => controller.abort()); - } - let res; - try { - res = await request(url, { ...options, signal: controller.signal }); - } catch (error) { - if (!(error instanceof Error)) - throw error; - if (shouldRetry(error) && retries !== this.manager.options.retries) { - return await this.runRequest(routeId, url, options, requestData, ++retries); - } - throw error; - } finally { - clearTimeout(timeout); - } - if (this.manager.listenerCount("response" /* Response */)) { - this.manager.emit( - "response" /* Response */, - { - method, - path: routeId.original, - route: routeId.bucketRoute, - options, - data: requestData, - retries - }, - { ...res } - ); + const res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries); + if (res === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); } const status = res.statusCode; let retryAfter = 0; @@ -539,34 +907,23 @@ var SequentialHandler = class { } } if (status === 401 || status === 403 || status === 429) { - if (!invalidCountResetTime || invalidCountResetTime < Date.now()) { - invalidCountResetTime = Date.now() + 1e3 * 60 * 10; - invalidCount = 0; - } - invalidCount++; - const emitInvalid = this.manager.options.invalidRequestWarningInterval > 0 && invalidCount % this.manager.options.invalidRequestWarningInterval === 0; - if (emitInvalid) { - this.manager.emit("invalidRequestWarning" /* InvalidRequestWarning */, { - count: invalidCount, - remainingTime: invalidCountResetTime - Date.now() - }); - } + incrementInvalidCount(this.manager); } if (status >= 200 && status < 300) { return res; } else if (status === 429) { const isGlobal = this.globalLimited; let limit2; - let timeout2; + let timeout; if (isGlobal) { limit2 = this.manager.options.globalRequestsPerSecond; - timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + timeout = this.manager.globalReset + this.manager.options.offset - Date.now(); } else { limit2 = this.limit; - timeout2 = this.timeToReset; + timeout = this.timeToReset; } - await this.onRateLimit({ - timeToReset: timeout2, + await onRateLimit(this.manager, { + timeToReset: timeout, limit: limit2, method, hash: this.hash, @@ -598,7 +955,7 @@ var SequentialHandler = class { } this.#sublimitPromise?.resolve(); this.#sublimitPromise = null; - await sleep(sublimitTimeout); + await sleep2(sublimitTimeout); let resolve; const promise = new Promise((res2) => resolve = res2); this.#sublimitPromise = { promise, resolve }; @@ -608,20 +965,12 @@ var SequentialHandler = class { } } return this.runRequest(routeId, url, options, requestData, retries); - } else if (status >= 500 && status < 600) { - if (retries !== this.manager.options.retries) { + } else { + const handled = await handleErrors(this.manager, res, method, url, requestData, retries); + if (handled === null) { return this.runRequest(routeId, url, options, requestData, ++retries); } - throw new HTTPError(status, method, url, requestData); - } else { - if (status >= 400 && status < 500) { - if (status === 401 && requestData.auth) { - this.manager.setToken(null); - } - const data = await parseResponse(res); - throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData); - } - return res; + return handled; } } }; @@ -638,11 +987,30 @@ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => { return RequestMethod2; })(RequestMethod || {}); var RequestManager = class extends EventEmitter { + /** + * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests + * performed by this manager. + */ agent = null; + /** + * The number of requests remaining in the global bucket + */ globalRemaining; + /** + * The promise used to wait out the global rate limit + */ globalDelay = null; + /** + * The timestamp at which the global bucket resets + */ globalReset = -1; + /** + * API bucket hashes that are cached from provided routes + */ hashes = new Collection(); + /** + * Request handlers created from the bucket hash and the major parameters + */ handlers = new Collection(); #token = null; hashTimer; @@ -696,14 +1064,30 @@ var RequestManager = class extends EventEmitter { }, this.options.handlerSweepInterval).unref(); } } + /** + * Sets the default agent to use for requests performed by this manager + * + * @param agent - The agent to use + */ setAgent(agent) { this.agent = agent; return this; } + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ setToken(token) { this.#token = token; return this; } + /** + * Queues a request to be sent + * + * @param request - All the information needed to make a request + * @returns The response from the api request + */ async queueRequest(request2) { const routeId = RequestManager.generateRouteData(request2.fullRoute, request2.method); const hash = this.hashes.get(`${request2.method}:${routeId.bucketRoute}`) ?? { @@ -719,11 +1103,23 @@ var RequestManager = class extends EventEmitter { signal: request2.signal }); } + /** + * Creates a new rate limit handler from a hash, based on the hash and the major parameter + * + * @param hash - The hash for the route + * @param majorParameter - The major parameter for this handler + * @internal + */ createHandler(hash, majorParameter) { - const queue = new SequentialHandler(this, hash, majorParameter); + const queue = majorParameter === BurstHandlerMajorIdKey ? new BurstHandler(this, hash, majorParameter) : new SequentialHandler(this, hash, majorParameter); this.handlers.set(queue.id, queue); return queue; } + /** + * Formats the request data to a usable format for fetch + * + * @param request - The request data + */ async resolveRequest(request2) { const { options } = this; let query = ""; @@ -755,7 +1151,13 @@ var RequestManager = class extends EventEmitter { const fileKey = file.key ?? `files[${index}]`; if (Buffer3.isBuffer(file.data)) { const { fileTypeFromBuffer } = await getFileType(); - const contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime; + let contentType = file.contentType; + if (!contentType) { + const parsedType = (await fileTypeFromBuffer(file.data))?.mime; + if (parsedType) { + contentType = OverwrittenMimeTypes[parsedType] ?? parsedType; + } + } formData.append(fileKey, new Blob2([file.data], { type: contentType }), file.name); } else { formData.append(fileKey, new Blob2([`${file.data}`], { type: file.contentType }), file.name); @@ -790,19 +1192,39 @@ var RequestManager = class extends EventEmitter { fetchOptions.dispatcher = request2.dispatcher ?? this.agent ?? void 0; return { url, fetchOptions }; } + /** + * Stops the hash sweeping interval + */ clearHashSweeper() { clearInterval(this.hashTimer); } + /** + * Stops the request handler sweeping interval + */ clearHandlerSweeper() { clearInterval(this.handlerTimer); } + /** + * Generates route data for an endpoint:method + * + * @param endpoint - The raw endpoint to generalize + * @param method - The HTTP method this endpoint is called without + * @internal + */ static generateRouteData(endpoint, method) { - const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{16,19})/.exec(endpoint); + if (endpoint.startsWith("/interactions/") && endpoint.endsWith("/callback")) { + return { + majorParameter: BurstHandlerMajorIdKey, + bucketRoute: "/interactions/:id/:token/callback", + original: endpoint + }; + } + const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{17,19})/.exec(endpoint); const majorId = majorIdMatch?.[1] ?? "global"; - const baseRoute = endpoint.replaceAll(/\d{16,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); + const baseRoute = endpoint.replaceAll(/\d{17,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); let exceptions = ""; if (method === "DELETE" /* Delete */ && baseRoute === "/channels/:id/messages/:id") { - const id = /\d{16,19}$/.exec(endpoint)[0]; + const id = /\d{17,19}$/.exec(endpoint)[0]; const timestamp = DiscordSnowflake.timestampFrom(id); if (Date.now() - timestamp > 1e3 * 60 * 60 * 24 * 14) { exceptions += "/Delete Old Message"; @@ -835,36 +1257,89 @@ var REST = class extends EventEmitter2 { this.requestManager.off(name, listener); }); } + /** + * Gets the agent set for this instance + */ getAgent() { return this.requestManager.agent; } + /** + * Sets the default agent to use for requests performed by this instance + * + * @param agent - Sets the agent to use + */ setAgent(agent) { this.requestManager.setAgent(agent); return this; } + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ setToken(token) { this.requestManager.setToken(token); return this; } + /** + * Runs a get request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async get(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "GET" /* Get */ }); } + /** + * Runs a delete request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async delete(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "DELETE" /* Delete */ }); } + /** + * Runs a post request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async post(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "POST" /* Post */ }); } + /** + * Runs a put request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async put(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "PUT" /* Put */ }); } + /** + * Runs a patch request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async patch(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "PATCH" /* Patch */ }); } + /** + * Runs a request from the api + * + * @param options - Request options + */ async request(options) { const response = await this.raw(options); return parseResponse(response); } + /** + * Runs a request from the API, yielding the raw Response object + * + * @param options - Request options + */ async raw(options) { return this.requestManager.queueRequest(options); } @@ -872,16 +1347,19 @@ var REST = class extends EventEmitter2 { __name(REST, "REST"); // src/index.ts -var version = "1.5.0"; +var version = "1.7.1"; export { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, + BurstHandlerMajorIdKey, CDN, DefaultRestOptions, DefaultUserAgent, + DefaultUserAgentAppendix, DiscordAPIError, HTTPError, + OverwrittenMimeTypes, REST, RESTEvents, RateLimitError, diff --git a/node_modules/@discordjs/rest/dist/index.mjs.map b/node_modules/@discordjs/rest/dist/index.mjs.map index 0ccc6de..85bb8eb 100644 --- a/node_modules/@discordjs/rest/dist/index.mjs.map +++ b/node_modules/@discordjs/rest/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/lib/CDN.ts","../src/lib/utils/constants.ts","../src/lib/errors/DiscordAPIError.ts","../src/lib/errors/HTTPError.ts","../src/lib/errors/RateLimitError.ts","../src/lib/RequestManager.ts","../src/lib/handlers/SequentialHandler.ts","../src/lib/utils/utils.ts","../src/lib/REST.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\nimport { URL } from 'node:url';\nimport {\n\tALLOWED_EXTENSIONS,\n\tALLOWED_SIZES,\n\tALLOWED_STICKER_EXTENSIONS,\n\tDefaultRestOptions,\n\ttype ImageExtension,\n\ttype ImageSize,\n\ttype StickerExtension,\n} from './utils/constants.js';\n\n/**\n * The options used for image URLs\n */\nexport interface BaseImageURLOptions {\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: ImageExtension;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The options used for image URLs with animated content\n */\nexport interface ImageURLOptions extends BaseImageURLOptions {\n\t/**\n\t * Whether or not to prefer the static version of an image asset.\n\t */\n\tforceStatic?: boolean;\n}\n\n/**\n * The options to use when making a CDN URL\n */\nexport interface MakeURLOptions {\n\t/**\n\t * The allowed extensions that can be used\n\t */\n\tallowedExtensions?: readonly string[];\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: string | undefined;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The CDN link builder\n */\nexport class CDN {\n\tpublic constructor(private readonly base: string = DefaultRestOptions.cdn) {}\n\n\t/**\n\t * Generates an app asset URL for a client's asset.\n\t *\n\t * @param clientId - The client id that has the asset\n\t * @param assetHash - The hash provided by Discord for this asset\n\t * @param options - Optional options for the asset\n\t */\n\tpublic appAsset(clientId: string, assetHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/${clientId}/${assetHash}`, options);\n\t}\n\n\t/**\n\t * Generates an app icon URL for a client's icon.\n\t *\n\t * @param clientId - The client id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic appIcon(clientId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-icons/${clientId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates an avatar URL, e.g. for a user or a webhook.\n\t *\n\t * @param id - The id that has the icon\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic avatar(id: string, avatarHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a banner URL, e.g. for a user or a guild.\n\t *\n\t * @param id - The id that has the banner splash\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic banner(id: string, bannerHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL for a channel, e.g. a group DM.\n\t *\n\t * @param channelId - The channel id that has the icon\n\t * @param iconHash - The hash provided by Discord for this channel\n\t * @param options - Optional options for the icon\n\t */\n\tpublic channelIcon(channelId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates the default avatar URL for a discriminator.\n\t *\n\t * @param discriminator - The discriminator modulo 5\n\t */\n\tpublic defaultAvatar(discriminator: number): string {\n\t\treturn this.makeURL(`/embed/avatars/${discriminator}`, { extension: 'png' });\n\t}\n\n\t/**\n\t * Generates a discovery splash URL for a guild's discovery splash.\n\t *\n\t * @param guildId - The guild id that has the discovery splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic discoverySplash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates an emoji's URL for an emoji.\n\t *\n\t * @param emojiId - The emoji id\n\t * @param extension - The extension of the emoji\n\t */\n\tpublic emoji(emojiId: string, extension?: ImageExtension): string {\n\t\treturn this.makeURL(`/emojis/${emojiId}`, { extension });\n\t}\n\n\t/**\n\t * Generates a guild member avatar URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic guildMemberAvatar(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tavatarHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a guild member banner URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic guildMemberBanner(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tbannerHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL, e.g. for a guild.\n\t *\n\t * @param id - The id that has the icon splash\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic icon(id: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options);\n\t}\n\n\t/**\n\t * Generates a URL for the icon of a role\n\t *\n\t * @param roleId - The id of the role that has the icon\n\t * @param roleIconHash - The hash provided by Discord for this role icon\n\t * @param options - Optional options for the role icon\n\t */\n\tpublic roleIcon(roleId: string, roleIconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a guild invite splash URL for a guild's invite splash.\n\t *\n\t * @param guildId - The guild id that has the invite splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic splash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates a sticker URL.\n\t *\n\t * @param stickerId - The sticker id\n\t * @param extension - The extension of the sticker\n\t */\n\tpublic sticker(stickerId: string, extension?: StickerExtension): string {\n\t\treturn this.makeURL(`/stickers/${stickerId}`, {\n\t\t\tallowedExtensions: ALLOWED_STICKER_EXTENSIONS,\n\t\t\textension: extension ?? 'png', // Stickers cannot have a `.webp` extension, so we default to a `.png`\n\t\t});\n\t}\n\n\t/**\n\t * Generates a sticker pack banner URL.\n\t *\n\t * @param bannerId - The banner id\n\t * @param options - Optional options for the banner\n\t */\n\tpublic stickerPackBanner(bannerId: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options);\n\t}\n\n\t/**\n\t * Generates a team icon URL for a team's icon.\n\t *\n\t * @param teamId - The team id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic teamIcon(teamId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/team-icons/${teamId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a cover image for a guild scheduled event.\n\t *\n\t * @param scheduledEventId - The scheduled event id\n\t * @param coverHash - The hash provided by discord for this cover image\n\t * @param options - Optional options for the cover image\n\t */\n\tpublic guildScheduledEventCover(\n\t\tscheduledEventId: string,\n\t\tcoverHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`.\n\t *\n\t * @param route - The base cdn route\n\t * @param hash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the link\n\t */\n\tprivate dynamicMakeURL(\n\t\troute: string,\n\t\thash: string,\n\t\t{ forceStatic = false, ...options }: Readonly = {},\n\t): string {\n\t\treturn this.makeURL(route, !forceStatic && hash.startsWith('a_') ? { ...options, extension: 'gif' } : options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource\n\t *\n\t * @param route - The base cdn route\n\t * @param options - The extension/size options for the link\n\t */\n\tprivate makeURL(\n\t\troute: string,\n\t\t{ allowedExtensions = ALLOWED_EXTENSIONS, extension = 'webp', size }: Readonly = {},\n\t): string {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\textension = String(extension).toLowerCase();\n\n\t\tif (!allowedExtensions.includes(extension)) {\n\t\t\tthrow new RangeError(`Invalid extension provided: ${extension}\\nMust be one of: ${allowedExtensions.join(', ')}`);\n\t\t}\n\n\t\tif (size && !ALLOWED_SIZES.includes(size)) {\n\t\t\tthrow new RangeError(`Invalid size provided: ${size}\\nMust be one of: ${ALLOWED_SIZES.join(', ')}`);\n\t\t}\n\n\t\tconst url = new URL(`${this.base}${route}.${extension}`);\n\n\t\tif (size) {\n\t\t\turl.searchParams.set('size', String(size));\n\t\t}\n\n\t\treturn url.toString();\n\t}\n}\n","import process from 'node:process';\nimport { APIVersion } from 'discord-api-types/v10';\nimport { Agent } from 'undici';\nimport type { RESTOptions } from '../REST.js';\n\nexport const DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.5.0)`;\n\nexport const DefaultRestOptions = {\n\tget agent() {\n\t\treturn new Agent({\n\t\t\tconnect: {\n\t\t\t\ttimeout: 30_000,\n\t\t\t},\n\t\t});\n\t},\n\tapi: 'https://discord.com/api',\n\tauthPrefix: 'Bot',\n\tcdn: 'https://cdn.discordapp.com',\n\theaders: {},\n\tinvalidRequestWarningInterval: 0,\n\tglobalRequestsPerSecond: 50,\n\toffset: 50,\n\trejectOnRateLimit: null,\n\tretries: 3,\n\ttimeout: 15_000,\n\tuserAgentAppendix: `Node.js ${process.version}`,\n\tversion: APIVersion,\n\thashSweepInterval: 14_400_000, // 4 Hours\n\thashLifetime: 86_400_000, // 24 Hours\n\thandlerSweepInterval: 3_600_000, // 1 Hour\n} as const satisfies Required;\n\n/**\n * The events that the REST manager emits\n */\nexport const enum RESTEvents {\n\tDebug = 'restDebug',\n\tHandlerSweep = 'handlerSweep',\n\tHashSweep = 'hashSweep',\n\tInvalidRequestWarning = 'invalidRequestWarning',\n\tRateLimited = 'rateLimited',\n\tResponse = 'response',\n}\n\nexport const ALLOWED_EXTENSIONS = ['webp', 'png', 'jpg', 'jpeg', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_STICKER_EXTENSIONS = ['png', 'json'] as const satisfies readonly string[];\nexport const ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1_024, 2_048, 4_096] as const satisfies readonly number[];\n\nexport type ImageExtension = typeof ALLOWED_EXTENSIONS[number];\nexport type StickerExtension = typeof ALLOWED_STICKER_EXTENSIONS[number];\nexport type ImageSize = typeof ALLOWED_SIZES[number];\n","import type { InternalRequest, RawFile } from '../RequestManager.js';\n\ninterface DiscordErrorFieldInformation {\n\tcode: string;\n\tmessage: string;\n}\n\ninterface DiscordErrorGroupWrapper {\n\t_errors: DiscordError[];\n}\n\ntype DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | { [k: string]: DiscordError };\n\nexport interface DiscordErrorData {\n\tcode: number;\n\terrors?: DiscordError;\n\tmessage: string;\n}\n\nexport interface OAuthErrorData {\n\terror: string;\n\terror_description?: string;\n}\n\nexport interface RequestBody {\n\tfiles: RawFile[] | undefined;\n\tjson: unknown | undefined;\n}\n\nfunction isErrorGroupWrapper(error: DiscordError): error is DiscordErrorGroupWrapper {\n\treturn Reflect.has(error as Record, '_errors');\n}\n\nfunction isErrorResponse(error: DiscordError): error is DiscordErrorFieldInformation {\n\treturn typeof Reflect.get(error as Record, 'message') === 'string';\n}\n\n/**\n * Represents an API error returned by Discord\n */\nexport class DiscordAPIError extends Error {\n\tpublic requestBody: RequestBody;\n\n\t/**\n\t * @param rawError - The error reported by Discord\n\t * @param code - The error code reported by Discord\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic rawError: DiscordErrorData | OAuthErrorData,\n\t\tpublic code: number | string,\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(DiscordAPIError.getMessage(rawError));\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${DiscordAPIError.name}[${this.code}]`;\n\t}\n\n\tprivate static getMessage(error: DiscordErrorData | OAuthErrorData) {\n\t\tlet flattened = '';\n\t\tif ('code' in error) {\n\t\t\tif (error.errors) {\n\t\t\t\tflattened = [...this.flattenDiscordError(error.errors)].join('\\n');\n\t\t\t}\n\n\t\t\treturn error.message && flattened\n\t\t\t\t? `${error.message}\\n${flattened}`\n\t\t\t\t: error.message || flattened || 'Unknown Error';\n\t\t}\n\n\t\treturn error.error_description ?? 'No Description';\n\t}\n\n\tprivate static *flattenDiscordError(obj: DiscordError, key = ''): IterableIterator {\n\t\tif (isErrorResponse(obj)) {\n\t\t\treturn yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();\n\t\t}\n\n\t\tfor (const [otherKey, val] of Object.entries(obj)) {\n\t\t\tconst nextKey = otherKey.startsWith('_')\n\t\t\t\t? key\n\t\t\t\t: key\n\t\t\t\t? Number.isNaN(Number(otherKey))\n\t\t\t\t\t? `${key}.${otherKey}`\n\t\t\t\t\t: `${key}[${otherKey}]`\n\t\t\t\t: otherKey;\n\n\t\t\tif (typeof val === 'string') {\n\t\t\t\tyield val;\n\t\t\t} else if (isErrorGroupWrapper(val)) {\n\t\t\t\tfor (const error of val._errors) {\n\t\t\t\t\tyield* this.flattenDiscordError(error, nextKey);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield* this.flattenDiscordError(val, nextKey);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { STATUS_CODES } from 'node:http';\nimport type { InternalRequest } from '../RequestManager.js';\nimport type { RequestBody } from './DiscordAPIError.js';\n\n/**\n * Represents a HTTP error\n */\nexport class HTTPError extends Error {\n\tpublic requestBody: RequestBody;\n\n\tpublic override name = HTTPError.name;\n\n\t/**\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(STATUS_CODES[status]);\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n}\n","import type { RateLimitData } from '../REST';\n\nexport class RateLimitError extends Error implements RateLimitData {\n\tpublic timeToReset: number;\n\n\tpublic limit: number;\n\n\tpublic method: string;\n\n\tpublic hash: string;\n\n\tpublic url: string;\n\n\tpublic route: string;\n\n\tpublic majorParameter: string;\n\n\tpublic global: boolean;\n\n\tpublic constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData) {\n\t\tsuper();\n\t\tthis.timeToReset = timeToReset;\n\t\tthis.limit = limit;\n\t\tthis.method = method;\n\t\tthis.hash = hash;\n\t\tthis.url = url;\n\t\tthis.route = route;\n\t\tthis.majorParameter = majorParameter;\n\t\tthis.global = global;\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${RateLimitError.name}[${this.route}]`;\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { setInterval, clearInterval } from 'node:timers';\nimport type { URLSearchParams } from 'node:url';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { DiscordSnowflake } from '@sapphire/snowflake';\nimport { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';\nimport type { RESTOptions, RestEvents, RequestOptions } from './REST.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { SequentialHandler } from './handlers/SequentialHandler.js';\nimport { DefaultRestOptions, DefaultUserAgent, RESTEvents } from './utils/constants.js';\nimport { resolveBody } from './utils/utils.js';\n\n// Make this a lazy dynamic import as file-type is a pure ESM package\nconst getFileType = lazy(async () => import('file-type'));\n\n/**\n * Represents a file to be added to the request\n */\nexport interface RawFile {\n\t/**\n\t * Content-Type of the file\n\t */\n\tcontentType?: string;\n\t/**\n\t * The actual data for the file\n\t */\n\tdata: Buffer | boolean | number | string;\n\t/**\n\t * An explicit key to use for key of the formdata field for this file.\n\t * When not provided, the index of the file in the files array is used in the form `files[${index}]`.\n\t * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)\n\t */\n\tkey?: string;\n\t/**\n\t * The name of the file\n\t */\n\tname: string;\n}\n\n/**\n * Represents possible data to be given to an endpoint\n */\nexport interface RequestData {\n\t/**\n\t * Whether to append JSON data to form data instead of `payload_json` when sending files\n\t */\n\tappendToFormData?: boolean;\n\t/**\n\t * If this request needs the `Authorization` header\n\t *\n\t * @defaultValue `true`\n\t */\n\tauth?: boolean;\n\t/**\n\t * The authorization prefix to use for this request, useful if you use this with bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix?: 'Bearer' | 'Bot';\n\t/**\n\t * The body to send to this request.\n\t * If providing as BodyInit, set `passThroughBody: true`\n\t */\n\tbody?: BodyInit | unknown;\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.\n\t */\n\tdispatcher?: Agent;\n\t/**\n\t * Files to be attached to this request\n\t */\n\tfiles?: RawFile[] | undefined;\n\t/**\n\t * Additional headers to add to this request\n\t */\n\theaders?: Record;\n\t/**\n\t * Whether to pass-through the body property directly to `fetch()`.\n\t * This only applies when files is NOT present\n\t */\n\tpassThroughBody?: boolean;\n\t/**\n\t * Query string parameters to append to the called endpoint\n\t */\n\tquery?: URLSearchParams;\n\t/**\n\t * Reason to show in the audit logs\n\t */\n\treason?: string | undefined;\n\t/**\n\t * The signal to abort the queue entry or the REST call, where applicable\n\t */\n\tsignal?: AbortSignal | undefined;\n\t/**\n\t * If this request should be versioned\n\t *\n\t * @defaultValue `true`\n\t */\n\tversioned?: boolean;\n}\n\n/**\n * Possible headers for an API call\n */\nexport interface RequestHeaders {\n\tAuthorization?: string;\n\t'User-Agent': string;\n\t'X-Audit-Log-Reason'?: string;\n}\n\n/**\n * Possible API methods to be used when doing requests\n */\nexport const enum RequestMethod {\n\tDelete = 'DELETE',\n\tGet = 'GET',\n\tPatch = 'PATCH',\n\tPost = 'POST',\n\tPut = 'PUT',\n}\n\nexport type RouteLike = `/${string}`;\n\n/**\n * Internal request options\n *\n * @internal\n */\nexport interface InternalRequest extends RequestData {\n\tfullRoute: RouteLike;\n\tmethod: RequestMethod;\n}\n\nexport type HandlerRequestData = Pick;\n\n/**\n * Parsed route data for an endpoint\n *\n * @internal\n */\nexport interface RouteData {\n\tbucketRoute: string;\n\tmajorParameter: string;\n\toriginal: RouteLike;\n}\n\n/**\n * Represents a hash and its associated fields\n *\n * @internal\n */\nexport interface HashData {\n\tlastAccess: number;\n\tvalue: string;\n}\n\nexport interface RequestManager {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\n/**\n * Represents the class that manages handlers for endpoints\n */\nexport class RequestManager extends EventEmitter {\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests\n\t * performed by this manager.\n\t */\n\tpublic agent: Dispatcher | null = null;\n\n\t/**\n\t * The number of requests remaining in the global bucket\n\t */\n\tpublic globalRemaining: number;\n\n\t/**\n\t * The promise used to wait out the global rate limit\n\t */\n\tpublic globalDelay: Promise | null = null;\n\n\t/**\n\t * The timestamp at which the global bucket resets\n\t */\n\tpublic globalReset = -1;\n\n\t/**\n\t * API bucket hashes that are cached from provided routes\n\t */\n\tpublic readonly hashes = new Collection();\n\n\t/**\n\t * Request handlers created from the bucket hash and the major parameters\n\t */\n\tpublic readonly handlers = new Collection();\n\n\t#token: string | null = null;\n\n\tprivate hashTimer!: NodeJS.Timer;\n\n\tprivate handlerTimer!: NodeJS.Timer;\n\n\tpublic readonly options: RESTOptions;\n\n\tpublic constructor(options: Partial) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultRestOptions, ...options };\n\t\tthis.options.offset = Math.max(0, this.options.offset);\n\t\tthis.globalRemaining = this.options.globalRequestsPerSecond;\n\t\tthis.agent = options.agent ?? null;\n\n\t\t// Start sweepers\n\t\tthis.setupSweepers();\n\t}\n\n\tprivate setupSweepers() {\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\tconst validateMaxInterval = (interval: number) => {\n\t\t\tif (interval > 14_400_000) {\n\t\t\t\tthrow new Error('Cannot set an interval greater than 4 hours');\n\t\t\t}\n\t\t};\n\n\t\tif (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.hashSweepInterval);\n\t\t\tthis.hashTimer = setInterval(() => {\n\t\t\t\tconst sweptHashes = new Collection();\n\t\t\t\tconst currentDate = Date.now();\n\n\t\t\t\t// Begin sweeping hash based on lifetimes\n\t\t\t\tthis.hashes.sweep((val, key) => {\n\t\t\t\t\t// `-1` indicates a global hash\n\t\t\t\t\tif (val.lastAccess === -1) return false;\n\n\t\t\t\t\t// Check if lifetime has been exceeded\n\t\t\t\t\tconst shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime;\n\n\t\t\t\t\t// Add hash to collection of swept hashes\n\t\t\t\t\tif (shouldSweep) {\n\t\t\t\t\t\t// Add to swept hashes\n\t\t\t\t\t\tsweptHashes.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit debug information\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`);\n\n\t\t\t\t\treturn shouldSweep;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HashSweep, sweptHashes);\n\t\t\t}, this.options.hashSweepInterval).unref();\n\t\t}\n\n\t\tif (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.handlerSweepInterval);\n\t\t\tthis.handlerTimer = setInterval(() => {\n\t\t\t\tconst sweptHandlers = new Collection();\n\n\t\t\t\t// Begin sweeping handlers based on activity\n\t\t\t\tthis.handlers.sweep((val, key) => {\n\t\t\t\t\tconst { inactive } = val;\n\n\t\t\t\t\t// Collect inactive handlers\n\t\t\t\t\tif (inactive) {\n\t\t\t\t\t\tsweptHandlers.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`);\n\t\t\t\t\treturn inactive;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HandlerSweep, sweptHandlers);\n\t\t\t}, this.options.handlerSweepInterval).unref();\n\t\t}\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this manager\n\t *\n\t * @param agent - The agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.agent = agent;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.#token = token;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Queues a request to be sent\n\t *\n\t * @param request - All the information needed to make a request\n\t * @returns The response from the api request\n\t */\n\tpublic async queueRequest(request: InternalRequest): Promise {\n\t\t// Generalize the endpoint to its route data\n\t\tconst routeId = RequestManager.generateRouteData(request.fullRoute, request.method);\n\t\t// Get the bucket hash for the generic route, or point to a global route otherwise\n\t\tconst hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {\n\t\t\tvalue: `Global(${request.method}:${routeId.bucketRoute})`,\n\t\t\tlastAccess: -1,\n\t\t};\n\n\t\t// Get the request handler for the obtained hash, with its major parameter\n\t\tconst handler =\n\t\t\tthis.handlers.get(`${hash.value}:${routeId.majorParameter}`) ??\n\t\t\tthis.createHandler(hash.value, routeId.majorParameter);\n\n\t\t// Resolve the request into usable fetch options\n\t\tconst { url, fetchOptions } = await this.resolveRequest(request);\n\n\t\t// Queue the request\n\t\treturn handler.queueRequest(routeId, url, fetchOptions, {\n\t\t\tbody: request.body,\n\t\t\tfiles: request.files,\n\t\t\tauth: request.auth !== false,\n\t\t\tsignal: request.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new rate limit handler from a hash, based on the hash and the major parameter\n\t *\n\t * @param hash - The hash for the route\n\t * @param majorParameter - The major parameter for this handler\n\t * @internal\n\t */\n\tprivate createHandler(hash: string, majorParameter: string) {\n\t\t// Create the async request queue to handle requests\n\t\tconst queue = new SequentialHandler(this, hash, majorParameter);\n\t\t// Save the queue based on its id\n\t\tthis.handlers.set(queue.id, queue);\n\n\t\treturn queue;\n\t}\n\n\t/**\n\t * Formats the request data to a usable format for fetch\n\t *\n\t * @param request - The request data\n\t */\n\tprivate async resolveRequest(request: InternalRequest): Promise<{ fetchOptions: RequestOptions; url: string }> {\n\t\tconst { options } = this;\n\n\t\tlet query = '';\n\n\t\t// If a query option is passed, use it\n\t\tif (request.query) {\n\t\t\tconst resolvedQuery = request.query.toString();\n\t\t\tif (resolvedQuery !== '') {\n\t\t\t\tquery = `?${resolvedQuery}`;\n\t\t\t}\n\t\t}\n\n\t\t// Create the required headers\n\t\tconst headers: RequestHeaders = {\n\t\t\t...this.options.headers,\n\t\t\t'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),\n\t\t};\n\n\t\t// If this request requires authorization (allowing non-\"authorized\" requests for webhooks)\n\t\tif (request.auth !== false) {\n\t\t\t// If we haven't received a token, throw an error\n\t\t\tif (!this.#token) {\n\t\t\t\tthrow new Error('Expected token to be set for this request, but none was present');\n\t\t\t}\n\n\t\t\theaders.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${this.#token}`;\n\t\t}\n\n\t\t// If a reason was set, set it's appropriate header\n\t\tif (request.reason?.length) {\n\t\t\theaders['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);\n\t\t}\n\n\t\t// Format the full request URL (api base, optional version, endpoint, optional querystring)\n\t\tconst url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${\n\t\t\trequest.fullRoute\n\t\t}${query}`;\n\n\t\tlet finalBody: RequestInit['body'];\n\t\tlet additionalHeaders: Record = {};\n\n\t\tif (request.files?.length) {\n\t\t\tconst formData = new FormData();\n\n\t\t\t// Attach all files to the request\n\t\t\tfor (const [index, file] of request.files.entries()) {\n\t\t\t\tconst fileKey = file.key ?? `files[${index}]`;\n\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#parameters\n\t\t\t\t// FormData.append only accepts a string or Blob.\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters\n\t\t\t\t// The Blob constructor accepts TypedArray/ArrayBuffer, strings, and Blobs.\n\t\t\t\tif (Buffer.isBuffer(file.data)) {\n\t\t\t\t\t// Try to infer the content type from the buffer if one isn't passed\n\t\t\t\t\tconst { fileTypeFromBuffer } = await getFileType();\n\t\t\t\t\tconst contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime;\n\t\t\t\t\tformData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);\n\t\t\t\t} else {\n\t\t\t\t\tformData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (request.body != null) {\n\t\t\t\tif (request.appendToFormData) {\n\t\t\t\t\tfor (const [key, value] of Object.entries(request.body as Record)) {\n\t\t\t\t\t\tformData.append(key, value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.append('payload_json', JSON.stringify(request.body));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set the final body to the form data\n\t\t\tfinalBody = formData;\n\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t} else if (request.body != null) {\n\t\t\tif (request.passThroughBody) {\n\t\t\t\tfinalBody = request.body as BodyInit;\n\t\t\t} else {\n\t\t\t\t// Stringify the JSON data\n\t\t\t\tfinalBody = JSON.stringify(request.body);\n\t\t\t\t// Set the additional headers to specify the content-type\n\t\t\t\tadditionalHeaders = { 'Content-Type': 'application/json' };\n\t\t\t}\n\t\t}\n\n\t\tfinalBody = await resolveBody(finalBody);\n\n\t\tconst fetchOptions: RequestOptions = {\n\t\t\theaders: { ...request.headers, ...additionalHeaders, ...headers } as Record,\n\t\t\tmethod: request.method.toUpperCase() as Dispatcher.HttpMethod,\n\t\t};\n\n\t\tif (finalBody !== undefined) {\n\t\t\tfetchOptions.body = finalBody as Exclude;\n\t\t}\n\n\t\t// Prioritize setting an agent per request, use the agent for this instance otherwise.\n\t\tfetchOptions.dispatcher = request.dispatcher ?? this.agent ?? undefined!;\n\n\t\treturn { url, fetchOptions };\n\t}\n\n\t/**\n\t * Stops the hash sweeping interval\n\t */\n\tpublic clearHashSweeper() {\n\t\tclearInterval(this.hashTimer);\n\t}\n\n\t/**\n\t * Stops the request handler sweeping interval\n\t */\n\tpublic clearHandlerSweeper() {\n\t\tclearInterval(this.handlerTimer);\n\t}\n\n\t/**\n\t * Generates route data for an endpoint:method\n\t *\n\t * @param endpoint - The raw endpoint to generalize\n\t * @param method - The HTTP method this endpoint is called without\n\t * @internal\n\t */\n\tprivate static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {\n\t\tconst majorIdMatch = /^\\/(?:channels|guilds|webhooks)\\/(\\d{16,19})/.exec(endpoint);\n\n\t\t// Get the major id for this route - global otherwise\n\t\tconst majorId = majorIdMatch?.[1] ?? 'global';\n\n\t\tconst baseRoute = endpoint\n\t\t\t// Strip out all ids\n\t\t\t.replaceAll(/\\d{16,19}/g, ':id')\n\t\t\t// Strip out reaction as they fall under the same bucket\n\t\t\t.replace(/\\/reactions\\/(.*)/, '/reactions/:reaction');\n\n\t\tlet exceptions = '';\n\n\t\t// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)\n\t\t// https://github.com/discord/discord-api-docs/issues/1295\n\t\tif (method === RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {\n\t\t\tconst id = /\\d{16,19}$/.exec(endpoint)![0]!;\n\t\t\tconst timestamp = DiscordSnowflake.timestampFrom(id);\n\t\t\tif (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {\n\t\t\t\texceptions += '/Delete Old Message';\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmajorParameter: majorId,\n\t\t\tbucketRoute: baseRoute + exceptions,\n\t\t\toriginal: endpoint,\n\t\t};\n\t}\n}\n","import { setTimeout, clearTimeout } from 'node:timers';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport { request, type Dispatcher } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager';\nimport { DiscordAPIError, type DiscordErrorData, type OAuthErrorData } from '../errors/DiscordAPIError.js';\nimport { HTTPError } from '../errors/HTTPError.js';\nimport { RateLimitError } from '../errors/RateLimitError.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { hasSublimit, parseHeader, parseResponse, shouldRetry } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\n\n/**\n * Invalid request limiting is done on a per-IP basis, not a per-token basis.\n * The best we can do is track invalid counts process-wide (on the theory that\n * users could have multiple bots run from one process) rather than per-bot.\n * Therefore, store these at file scope here rather than in the client's\n * RESTManager object.\n */\nlet invalidCount = 0;\nlet invalidCountResetTime: number | null = null;\n\nconst enum QueueType {\n\tStandard,\n\tSublimit,\n}\n\n/**\n * The structure used to handle requests for a given bucket\n */\nexport class SequentialHandler implements IHandler {\n\t/**\n\t * {@inheritDoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * The time this rate limit bucket will reset\n\t */\n\tprivate reset = -1;\n\n\t/**\n\t * The remaining requests that can be made before we are rate limited\n\t */\n\tprivate remaining = 1;\n\n\t/**\n\t * The total number of requests that can be made before we are rate limited\n\t */\n\tprivate limit = Number.POSITIVE_INFINITY;\n\n\t/**\n\t * The interface used to sequence async requests sequentially\n\t */\n\t#asyncQueue = new AsyncQueue();\n\n\t/**\n\t * The interface used to sequence sublimited async requests sequentially\n\t */\n\t#sublimitedQueue: AsyncQueue | null = null;\n\n\t/**\n\t * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed\n\t */\n\t#sublimitPromise: { promise: Promise; resolve(): void } | null = null;\n\n\t/**\n\t * Whether the sublimit queue needs to be shifted in the finally block\n\t */\n\t#shiftSublimit = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic get inactive(): boolean {\n\t\treturn (\n\t\t\tthis.#asyncQueue.remaining === 0 &&\n\t\t\t(this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) &&\n\t\t\t!this.limited\n\t\t);\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by the global limit\n\t */\n\tprivate get globalLimited(): boolean {\n\t\treturn this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by its limit\n\t */\n\tprivate get localLimited(): boolean {\n\t\treturn this.remaining <= 0 && Date.now() < this.reset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited\n\t */\n\tprivate get limited(): boolean {\n\t\treturn this.globalLimited || this.localLimited;\n\t}\n\n\t/**\n\t * The time until queued requests can continue\n\t */\n\tprivate get timeToReset(): number {\n\t\treturn this.reset + this.manager.options.offset - Date.now();\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * Delay all requests for the specified amount of time, handling global rate limits\n\t *\n\t * @param time - The amount of time to delay all requests for\n\t */\n\tprivate async globalDelayFor(time: number): Promise {\n\t\tawait sleep(time);\n\t\tthis.manager.globalDelay = null;\n\t}\n\n\t/*\n\t * Determines whether the request should be queued or whether a RateLimitError should be thrown\n\t */\n\tprivate async onRateLimit(rateLimitData: RateLimitData) {\n\t\tconst { options } = this.manager;\n\t\tif (!options.rejectOnRateLimit) return;\n\n\t\tconst shouldThrow =\n\t\t\ttypeof options.rejectOnRateLimit === 'function'\n\t\t\t\t? await options.rejectOnRateLimit(rateLimitData)\n\t\t\t\t: options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase()));\n\t\tif (shouldThrow) {\n\t\t\tthrow new RateLimitError(rateLimitData);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\tlet queue = this.#asyncQueue;\n\t\tlet queueType = QueueType.Standard;\n\t\t// Separate sublimited requests when already sublimited\n\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\tqueueType = QueueType.Sublimit;\n\t\t}\n\n\t\t// Wait for any previous requests to be completed before this one is run\n\t\tawait queue.wait({ signal: requestData.signal });\n\t\t// This set handles retroactively sublimiting requests\n\t\tif (queueType === QueueType.Standard) {\n\t\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\t\t/**\n\t\t\t\t * Remove the request from the standard queue, it should never be possible to get here while processing the\n\t\t\t\t * sublimit queue so there is no need to worry about shifting the wrong request\n\t\t\t\t */\n\t\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\t\tconst wait = queue.wait();\n\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\tawait wait;\n\t\t\t} else if (this.#sublimitPromise) {\n\t\t\t\t// Stall requests while the sublimit queue gets processed\n\t\t\t\tawait this.#sublimitPromise.promise;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request, and return the results\n\t\t\treturn await this.runRequest(routeId, url, options, requestData);\n\t\t} finally {\n\t\t\t// Allow the next request to fire\n\t\t\tqueue.shift();\n\t\t\tif (this.#shiftSublimit) {\n\t\t\t\tthis.#shiftSublimit = false;\n\t\t\t\tthis.#sublimitedQueue?.shift();\n\t\t\t}\n\n\t\t\t// If this request is the last request in a sublimit\n\t\t\tif (this.#sublimitedQueue?.remaining === 0) {\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitedQueue = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The method that actually makes the request to the api, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized api route with literal ids for major parameters\n\t * @param url - The fully resolved url to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\t/*\n\t\t * After calculations have been done, pre-emptively stop further requests\n\t\t * Potentially loop until this task can run if e.g. the global rate limit is hit twice\n\t\t */\n\t\twhile (this.limited) {\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\t\t\tlet delay: Promise;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t\t// If this is the first task to reach the global timeout, set the global delay\n\t\t\t\tif (!this.manager.globalDelay) {\n\t\t\t\t\t// The global delay function clears the global delay state when it is resolved\n\t\t\t\t\tthis.manager.globalDelay = this.globalDelayFor(timeout);\n\t\t\t\t}\n\n\t\t\t\tdelay = this.manager.globalDelay;\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t\tdelay = sleep(timeout);\n\t\t\t}\n\n\t\t\tconst rateLimitData: RateLimitData = {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t};\n\t\t\t// Let library users know they have hit a rate limit\n\t\t\tthis.manager.emit(RESTEvents.RateLimited, rateLimitData);\n\t\t\t// Determine whether a RateLimitError should be thrown\n\t\t\tawait this.onRateLimit(rateLimitData);\n\t\t\t// When not erroring, emit debug for what is happening\n\t\t\tif (isGlobal) {\n\t\t\t\tthis.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`);\n\t\t\t} else {\n\t\t\t\tthis.debug(`Waiting ${timeout}ms for rate limit to pass`);\n\t\t\t}\n\n\t\t\t// Wait the remaining time left before the rate limit resets\n\t\t\tawait delay;\n\t\t}\n\n\t\t// As the request goes out, update the global usage information\n\t\tif (!this.manager.globalReset || this.manager.globalReset < Date.now()) {\n\t\t\tthis.manager.globalReset = Date.now() + 1_000;\n\t\t\tthis.manager.globalRemaining = this.manager.options.globalRequestsPerSecond;\n\t\t}\n\n\t\tthis.manager.globalRemaining--;\n\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst controller = new AbortController();\n\t\tconst timeout = setTimeout(() => controller.abort(), this.manager.options.timeout).unref();\n\t\tif (requestData.signal) {\n\t\t\t// The type polyfill is required because Node.js's types are incomplete.\n\t\t\tconst signal = requestData.signal as PolyFillAbortSignal;\n\t\t\t// If the user signal was aborted, abort the controller, else abort the local signal.\n\t\t\t// The reason why we don't re-use the user's signal, is because users may use the same signal for multiple\n\t\t\t// requests, and we do not want to cause unexpected side-effects.\n\t\t\tif (signal.aborted) controller.abort();\n\t\t\telse signal.addEventListener('abort', () => controller.abort());\n\t\t}\n\n\t\tlet res: Dispatcher.ResponseData;\n\t\ttry {\n\t\t\tres = await request(url, { ...options, signal: controller.signal });\n\t\t} catch (error: unknown) {\n\t\t\tif (!(error instanceof Error)) throw error;\n\t\t\t// Retry the specified number of times if needed\n\t\t\tif (shouldRetry(error) && retries !== this.manager.options.retries) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn await this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t}\n\n\t\tif (this.manager.listenerCount(RESTEvents.Response)) {\n\t\t\tthis.manager.emit(\n\t\t\t\tRESTEvents.Response,\n\t\t\t\t{\n\t\t\t\t\tmethod,\n\t\t\t\t\tpath: routeId.original,\n\t\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\t\toptions,\n\t\t\t\t\tdata: requestData,\n\t\t\t\t\tretries,\n\t\t\t\t},\n\t\t\t\t{ ...res },\n\t\t\t);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\n\t\tconst limit = parseHeader(res.headers['x-ratelimit-limit']);\n\t\tconst remaining = parseHeader(res.headers['x-ratelimit-remaining']);\n\t\tconst reset = parseHeader(res.headers['x-ratelimit-reset-after']);\n\t\tconst hash = parseHeader(res.headers['x-ratelimit-bucket']);\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Update the total number of requests that can be made before the rate limit resets\n\t\tthis.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY;\n\t\t// Update the number of remaining requests that can be made before the rate limit resets\n\t\tthis.remaining = remaining ? Number(remaining) : 1;\n\t\t// Update the time when this rate limit resets (reset-after is in seconds)\n\t\tthis.reset = reset ? Number(reset) * 1_000 + Date.now() + this.manager.options.offset : Date.now();\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Handle buckets via the hash header retroactively\n\t\tif (hash && hash !== this.hash) {\n\t\t\t// Let library users know when rate limit buckets have been updated\n\t\t\tthis.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\\n'));\n\t\t\t// This queue will eventually be eliminated via attrition\n\t\t\tthis.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { value: hash, lastAccess: Date.now() });\n\t\t} else if (hash) {\n\t\t\t// Handle the case where hash value doesn't change\n\t\t\t// Fetch the hash data from the manager\n\t\t\tconst hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`);\n\n\t\t\t// When fetched, update the last access of the hash\n\t\t\tif (hashData) {\n\t\t\t\thashData.lastAccess = Date.now();\n\t\t\t}\n\t\t}\n\n\t\t// Handle retryAfter, which means we have actually hit a rate limit\n\t\tlet sublimitTimeout: number | null = null;\n\t\tif (retryAfter > 0) {\n\t\t\tif (res.headers['x-ratelimit-global'] !== undefined) {\n\t\t\t\tthis.manager.globalRemaining = 0;\n\t\t\t\tthis.manager.globalReset = Date.now() + retryAfter;\n\t\t\t} else if (!this.localLimited) {\n\t\t\t\t/*\n\t\t\t\t * This is a sublimit (e.g. 2 channel name changes/10 minutes) since the headers don't indicate a\n\t\t\t\t * route-wide rate limit. Don't update remaining or reset to avoid rate limiting the whole\n\t\t\t\t * endpoint, just set a reset time on the request itself to avoid retrying too soon.\n\t\t\t\t */\n\t\t\t\tsublimitTimeout = retryAfter;\n\t\t\t}\n\t\t}\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tif (!invalidCountResetTime || invalidCountResetTime < Date.now()) {\n\t\t\t\tinvalidCountResetTime = Date.now() + 1_000 * 60 * 10;\n\t\t\t\tinvalidCount = 0;\n\t\t\t}\n\n\t\t\tinvalidCount++;\n\n\t\t\tconst emitInvalid =\n\t\t\t\tthis.manager.options.invalidRequestWarningInterval > 0 &&\n\t\t\t\tinvalidCount % this.manager.options.invalidRequestWarningInterval === 0;\n\t\t\tif (emitInvalid) {\n\t\t\t\t// Let library users know periodically about invalid requests\n\t\t\t\tthis.manager.emit(RESTEvents.InvalidRequestWarning, {\n\t\t\t\t\tcount: invalidCount,\n\t\t\t\t\tremainingTime: invalidCountResetTime - Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t}\n\n\t\t\tawait this.onRateLimit({\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal.toString()}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${limit}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\t\t\t// If caused by a sublimit, wait it out here so other requests on the route can be handled\n\t\t\tif (sublimitTimeout) {\n\t\t\t\t// Normally the sublimit queue will not exist, however, if a sublimit is hit while in the sublimit queue, it will\n\t\t\t\tconst firstSublimit = !this.#sublimitedQueue;\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\tthis.#sublimitedQueue = new AsyncQueue();\n\t\t\t\t\tvoid this.#sublimitedQueue.wait();\n\t\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\t}\n\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitPromise = null;\n\t\t\t\tawait sleep(sublimitTimeout);\n\t\t\t\tlet resolve: () => void;\n\t\t\t\t// eslint-disable-next-line promise/param-names, no-promise-executor-return\n\t\t\t\tconst promise = new Promise((res) => (resolve = res));\n\t\t\t\tthis.#sublimitPromise = { promise, resolve: resolve! };\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\t// Re-queue this request so it can be shifted by the finally\n\t\t\t\t\tawait this.#asyncQueue.wait();\n\t\t\t\t\tthis.#shiftSublimit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else if (status >= 500 && status < 600) {\n\t\t\t// Retry the specified number of times for possible server side issues\n\t\t\tif (retries !== this.manager.options.retries) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\t// We are out of retries, throw an error\n\t\t\tthrow new HTTPError(status, method, url, requestData);\n\t\t} else {\n\t\t\t// Handle possible malformed requests\n\t\t\tif (status >= 400 && status < 500) {\n\t\t\t\t// If we receive this status code, it means the token we had is no longer valid.\n\t\t\t\tif (status === 401 && requestData.auth) {\n\t\t\t\t\tthis.manager.setToken(null!);\n\t\t\t\t}\n\n\t\t\t\t// The request will not succeed for some reason, parse the error returned from the api\n\t\t\t\tconst data = (await parseResponse(res)) as DiscordErrorData | OAuthErrorData;\n\t\t\t\t// throw the API error\n\t\t\t\tthrow new DiscordAPIError(data, 'code' in data ? data.code : data.error, status, method, url, requestData);\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\t}\n}\n\ninterface PolyFillAbortSignal {\n\treadonly aborted: boolean;\n\taddEventListener(type: 'abort', listener: () => void): void;\n\tremoveEventListener(type: 'abort', listener: () => void): void;\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { URLSearchParams } from 'node:url';\nimport { types } from 'node:util';\nimport type { RESTPatchAPIChannelJSONBody } from 'discord-api-types/v10';\nimport { FormData, type Dispatcher, type RequestInit } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport { RequestMethod } from '../RequestManager.js';\n\nexport function parseHeader(header: string[] | string | undefined): string | undefined {\n\tif (header === undefined || typeof header === 'string') {\n\t\treturn header;\n\t}\n\n\treturn header.join(';');\n}\n\nfunction serializeSearchParam(value: unknown): string | null {\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn value;\n\t\tcase 'number':\n\t\tcase 'bigint':\n\t\tcase 'boolean':\n\t\t\treturn value.toString();\n\t\tcase 'object':\n\t\t\tif (value === null) return null;\n\t\t\tif (value instanceof Date) {\n\t\t\t\treturn Number.isNaN(value.getTime()) ? null : value.toISOString();\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-base-to-string\n\t\t\tif (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) return value.toString();\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Creates and populates an URLSearchParams instance from an object, stripping\n * out null and undefined values, while also coercing non-strings to strings.\n *\n * @param options - The options to use\n * @returns A populated URLSearchParams instance\n */\nexport function makeURLSearchParams(options?: Readonly) {\n\tconst params = new URLSearchParams();\n\tif (!options) return params;\n\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tconst serialized = serializeSearchParam(value);\n\t\tif (serialized !== null) params.append(key, serialized);\n\t}\n\n\treturn params;\n}\n\n/**\n * Converts the response to usable data\n *\n * @param res - The fetch response\n */\nexport async function parseResponse(res: Dispatcher.ResponseData): Promise {\n\tconst header = parseHeader(res.headers['content-type']);\n\tif (header?.startsWith('application/json')) {\n\t\treturn res.body.json();\n\t}\n\n\treturn res.body.arrayBuffer();\n}\n\n/**\n * Check whether a request falls under a sublimit\n *\n * @param bucketRoute - The buckets route identifier\n * @param body - The options provided as JSON data\n * @param method - The HTTP method that will be used to make the request\n * @returns Whether the request falls under a sublimit\n */\nexport function hasSublimit(bucketRoute: string, body?: unknown, method?: string): boolean {\n\t// TODO: Update for new sublimits\n\t// Currently known sublimits:\n\t// Editing channel `name` or `topic`\n\tif (bucketRoute === '/channels/:id') {\n\t\tif (typeof body !== 'object' || body === null) return false;\n\t\t// This should never be a POST body, but just in case\n\t\tif (method !== RequestMethod.Patch) return false;\n\t\tconst castedBody = body as RESTPatchAPIChannelJSONBody;\n\t\treturn ['name', 'topic'].some((key) => Reflect.has(castedBody, key));\n\t}\n\n\t// If we are checking if a request has a sublimit on a route not checked above, sublimit all requests to avoid a flood of 429s\n\treturn true;\n}\n\nexport async function resolveBody(body: RequestInit['body']): Promise {\n\t// eslint-disable-next-line no-eq-null, eqeqeq\n\tif (body == null) {\n\t\treturn null;\n\t} else if (typeof body === 'string') {\n\t\treturn body;\n\t} else if (types.isUint8Array(body)) {\n\t\treturn body;\n\t} else if (types.isArrayBuffer(body)) {\n\t\treturn new Uint8Array(body);\n\t} else if (body instanceof URLSearchParams) {\n\t\treturn body.toString();\n\t} else if (body instanceof DataView) {\n\t\treturn new Uint8Array(body.buffer);\n\t} else if (body instanceof Blob) {\n\t\treturn new Uint8Array(await body.arrayBuffer());\n\t} else if (body instanceof FormData) {\n\t\treturn body;\n\t} else if ((body as Iterable)[Symbol.iterator]) {\n\t\tconst chunks = [...(body as Iterable)];\n\t\tconst length = chunks.reduce((a, b) => a + b.length, 0);\n\n\t\tconst uint8 = new Uint8Array(length);\n\t\tlet lengthUsed = 0;\n\n\t\treturn chunks.reduce((a, b) => {\n\t\t\ta.set(b, lengthUsed);\n\t\t\tlengthUsed += b.length;\n\t\t\treturn a;\n\t\t}, uint8);\n\t} else if ((body as AsyncIterable)[Symbol.asyncIterator]) {\n\t\tconst chunks: Uint8Array[] = [];\n\n\t\tfor await (const chunk of body as AsyncIterable) {\n\t\t\tchunks.push(chunk);\n\t\t}\n\n\t\treturn Buffer.concat(chunks);\n\t}\n\n\tthrow new TypeError(`Unable to resolve body.`);\n}\n\n/**\n * Check whether an error indicates that a retry can be attempted\n *\n * @param error - The error thrown by the network request\n * @returns Whether the error indicates a retry should be attempted\n */\nexport function shouldRetry(error: Error | NodeJS.ErrnoException) {\n\t// Retry for possible timed out requests\n\tif (error.name === 'AbortError') return true;\n\t// Downlevel ECONNRESET to retry as it may be recoverable\n\treturn ('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET');\n}\n","import { EventEmitter } from 'node:events';\nimport type { Collection } from '@discordjs/collection';\nimport type { request, Dispatcher } from 'undici';\nimport { CDN } from './CDN.js';\nimport {\n\tRequestManager,\n\tRequestMethod,\n\ttype HashData,\n\ttype HandlerRequestData,\n\ttype InternalRequest,\n\ttype RequestData,\n\ttype RouteLike,\n} from './RequestManager.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { DefaultRestOptions, RESTEvents } from './utils/constants.js';\nimport { parseResponse } from './utils/utils.js';\n\n/**\n * Options to be passed when creating the REST instance\n */\nexport interface RESTOptions {\n\t/**\n\t * The agent to set globally\n\t */\n\tagent: Dispatcher;\n\t/**\n\t * The base api path, without version\n\t *\n\t * @defaultValue `'https://discord.com/api'`\n\t */\n\tapi: string;\n\t/**\n\t * The authorization prefix to use for requests, useful if you want to use\n\t * bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix: 'Bearer' | 'Bot';\n\t/**\n\t * The cdn path\n\t *\n\t * @defaultValue 'https://cdn.discordapp.com'\n\t */\n\tcdn: string;\n\t/**\n\t * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)\n\t *\n\t * @defaultValue `50`\n\t */\n\tglobalRequestsPerSecond: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)\n\t *\n\t * @defaultValue `3_600_000`\n\t */\n\thandlerSweepInterval: number;\n\t/**\n\t * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)\n\t *\n\t * @defaultValue `86_400_000`\n\t */\n\thashLifetime: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)\n\t *\n\t * @defaultValue `14_400_000`\n\t */\n\thashSweepInterval: number;\n\t/**\n\t * Additional headers to send for all API requests\n\t *\n\t * @defaultValue `{}`\n\t */\n\theaders: Record;\n\t/**\n\t * The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).\n\t * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.\n\t *\n\t * @defaultValue `0`\n\t */\n\tinvalidRequestWarningInterval: number;\n\t/**\n\t * The extra offset to add to rate limits in milliseconds\n\t *\n\t * @defaultValue `50`\n\t */\n\toffset: number;\n\t/**\n\t * Determines how rate limiting and pre-emptive throttling should be handled.\n\t * When an array of strings, each element is treated as a prefix for the request route\n\t * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)\n\t * for which to throw {@link RateLimitError}s. All other request routes will be queued normally\n\t *\n\t * @defaultValue `null`\n\t */\n\trejectOnRateLimit: RateLimitQueueFilter | string[] | null;\n\t/**\n\t * The number of retries for errors with the 500 code, or errors\n\t * that timeout\n\t *\n\t * @defaultValue `3`\n\t */\n\tretries: number;\n\t/**\n\t * The time to wait in milliseconds before a request is aborted\n\t *\n\t * @defaultValue `15_000`\n\t */\n\ttimeout: number;\n\t/**\n\t * Extra information to add to the user agent\n\t *\n\t * @defaultValue `Node.js ${process.version}`\n\t */\n\tuserAgentAppendix: string;\n\t/**\n\t * The version of the API to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\n/**\n * Data emitted on `RESTEvents.RateLimited`\n */\nexport interface RateLimitData {\n\t/**\n\t * Whether the rate limit that was reached was the global limit\n\t */\n\tglobal: boolean;\n\t/**\n\t * The bucket hash for this request\n\t */\n\thash: string;\n\t/**\n\t * The amount of requests we can perform before locking requests\n\t */\n\tlimit: number;\n\t/**\n\t * The major parameter of the route\n\t *\n\t * For example, in `/channels/x`, this will be `x`.\n\t * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.\n\t */\n\tmajorParameter: string;\n\t/**\n\t * The HTTP method being performed\n\t */\n\tmethod: string;\n\t/**\n\t * The route being hit in this request\n\t */\n\troute: string;\n\t/**\n\t * The time, in milliseconds, until the request-lock is reset\n\t */\n\ttimeToReset: number;\n\t/**\n\t * The full URL for this request\n\t */\n\turl: string;\n}\n\n/**\n * A function that determines whether the rate limit hit should throw an Error\n */\nexport type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise | boolean;\n\nexport interface APIRequest {\n\t/**\n\t * The data that was used to form the body of this request\n\t */\n\tdata: HandlerRequestData;\n\t/**\n\t * The HTTP method used in this request\n\t */\n\tmethod: string;\n\t/**\n\t * Additional HTTP options for this request\n\t */\n\toptions: RequestOptions;\n\t/**\n\t * The full path used to make the request\n\t */\n\tpath: RouteLike;\n\t/**\n\t * The number of times this request has been attempted\n\t */\n\tretries: number;\n\t/**\n\t * The API route identifying the ratelimit for this request\n\t */\n\troute: string;\n}\n\nexport interface InvalidRequestWarningData {\n\t/**\n\t * Number of invalid requests that have been made in the window\n\t */\n\tcount: number;\n\t/**\n\t * Time in milliseconds remaining before the count resets\n\t */\n\tremainingTime: number;\n}\n\nexport interface RestEvents {\n\thandlerSweep: [sweptHandlers: Collection];\n\thashSweep: [sweptHashes: Collection];\n\tinvalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];\n\tnewListener: [name: string, listener: (...args: any) => void];\n\trateLimited: [rateLimitInfo: RateLimitData];\n\tremoveListener: [name: string, listener: (...args: any) => void];\n\tresponse: [request: APIRequest, response: Dispatcher.ResponseData];\n\trestDebug: [info: string];\n}\n\nexport interface REST {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\nexport type RequestOptions = Exclude[1], undefined>;\n\nexport class REST extends EventEmitter {\n\tpublic readonly cdn: CDN;\n\n\tpublic readonly requestManager: RequestManager;\n\n\tpublic constructor(options: Partial = {}) {\n\t\tsuper();\n\t\tthis.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn);\n\t\tthis.requestManager = new RequestManager(options)\n\t\t\t.on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug))\n\t\t\t.on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited))\n\t\t\t.on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning))\n\t\t\t.on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep));\n\n\t\tthis.on('newListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.on(name, listener);\n\t\t});\n\t\tthis.on('removeListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.off(name, listener);\n\t\t});\n\t}\n\n\t/**\n\t * Gets the agent set for this instance\n\t */\n\tpublic getAgent() {\n\t\treturn this.requestManager.agent;\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this instance\n\t *\n\t * @param agent - Sets the agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.requestManager.setAgent(agent);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.requestManager.setToken(token);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a get request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async get(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Get });\n\t}\n\n\t/**\n\t * Runs a delete request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async delete(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Delete });\n\t}\n\n\t/**\n\t * Runs a post request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async post(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Post });\n\t}\n\n\t/**\n\t * Runs a put request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async put(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Put });\n\t}\n\n\t/**\n\t * Runs a patch request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async patch(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Patch });\n\t}\n\n\t/**\n\t * Runs a request from the api\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async request(options: InternalRequest) {\n\t\tconst response = await this.raw(options);\n\t\treturn parseResponse(response);\n\t}\n\n\t/**\n\t * Runs a request from the API, yielding the raw Response object\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async raw(options: InternalRequest) {\n\t\treturn this.requestManager.queueRequest(options);\n\t}\n}\n","export * from './lib/CDN.js';\nexport * from './lib/errors/DiscordAPIError.js';\nexport * from './lib/errors/HTTPError.js';\nexport * from './lib/errors/RateLimitError.js';\nexport * from './lib/RequestManager.js';\nexport * from './lib/REST.js';\nexport * from './lib/utils/constants.js';\nexport { makeURLSearchParams, parseResponse } from './lib/utils/utils.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.5.0';\n"],"mappings":";;;;AACA,SAAS,WAAW;;;ACDpB,OAAO,aAAa;AACpB,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AAGf,IAAM,mBAAmB;AAEzB,IAAM,qBAAqB;AAAA,EACjC,IAAI,QAAQ;AACX,WAAO,IAAI,MAAM;AAAA,MAChB,SAAS;AAAA,QACR,SAAS;AAAA,MACV;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EACA,KAAK;AAAA,EACL,YAAY;AAAA,EACZ,KAAK;AAAA,EACL,SAAS,CAAC;AAAA,EACV,+BAA+B;AAAA,EAC/B,yBAAyB;AAAA,EACzB,QAAQ;AAAA,EACR,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,mBAAmB,WAAW,QAAQ;AAAA,EACtC,SAAS;AAAA,EACT,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,sBAAsB;AACvB;AAKO,IAAW,aAAX,kBAAWA,gBAAX;AACN,EAAAA,YAAA,WAAQ;AACR,EAAAA,YAAA,kBAAe;AACf,EAAAA,YAAA,eAAY;AACZ,EAAAA,YAAA,2BAAwB;AACxB,EAAAA,YAAA,iBAAc;AACd,EAAAA,YAAA,cAAW;AANM,SAAAA;AAAA,GAAA;AASX,IAAM,qBAAqB,CAAC,QAAQ,OAAO,OAAO,QAAQ,KAAK;AAC/D,IAAM,6BAA6B,CAAC,OAAO,MAAM;AACjD,IAAM,gBAAgB,CAAC,IAAI,IAAI,IAAI,KAAK,KAAK,KAAK,MAAO,MAAO,IAAK;;;ADerE,IAAM,MAAN,MAAU;AAAA,EACT,Y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SAAS,WAAW,8BAA6B,CAAC;AAAA,EAC5E;AAAA,EAQA,MAAa,KAAK,WAAsB,UAAuB,CAAC,GAAG;AAClE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,0BAA2B,CAAC;AAAA,EAC1E;AAAA,EAQA,MAAa,IAAI,WAAsB,UAAuB,CAAC,GAAG;AACjE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,wBAA0B,CAAC;AAAA,EACzE;AAAA,EAQA,MAAa,MAAM,WAAsB,UAAuB,CAAC,GAAG;AACnE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,4BAA4B,CAAC;AAAA,EAC3E;AAAA,EAOA,MAAa,QAAQ,SAA0B;AAC9C,UAAM,WAAW,MAAM,KAAK,IAAI,OAAO;AACvC,WAAO,cAAc,QAAQ;AAAA,EAC9B;AAAA,EAOA,MAAa,IAAI,SAA0B;AAC1C,WAAO,KAAK,eAAe,aAAa,OAAO;AAAA,EAChD;AACD;AArHa;;;AC9NN,IAAM,UAAkB;","names":["RESTEvents","Blob","Buffer","FormData","Buffer","Buffer","limit","timeout","res","RequestMethod","request","FormData","Buffer","Blob","EventEmitter","EventEmitter"]} \ No newline at end of file +{"version":3,"sources":["../src/lib/CDN.ts","../src/lib/utils/constants.ts","../src/lib/errors/DiscordAPIError.ts","../src/lib/errors/HTTPError.ts","../src/lib/errors/RateLimitError.ts","../src/lib/RequestManager.ts","../src/lib/handlers/BurstHandler.ts","../src/lib/utils/utils.ts","../src/lib/handlers/Shared.ts","../src/lib/handlers/SequentialHandler.ts","../src/lib/REST.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\nimport { URL } from 'node:url';\nimport {\n\tALLOWED_EXTENSIONS,\n\tALLOWED_SIZES,\n\tALLOWED_STICKER_EXTENSIONS,\n\tDefaultRestOptions,\n\ttype ImageExtension,\n\ttype ImageSize,\n\ttype StickerExtension,\n} from './utils/constants.js';\n\n/**\n * The options used for image URLs\n */\nexport interface BaseImageURLOptions {\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: ImageExtension;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The options used for image URLs with animated content\n */\nexport interface ImageURLOptions extends BaseImageURLOptions {\n\t/**\n\t * Whether or not to prefer the static version of an image asset.\n\t */\n\tforceStatic?: boolean;\n}\n\n/**\n * The options to use when making a CDN URL\n */\nexport interface MakeURLOptions {\n\t/**\n\t * The allowed extensions that can be used\n\t */\n\tallowedExtensions?: readonly string[];\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: string | undefined;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The CDN link builder\n */\nexport class CDN {\n\tpublic constructor(private readonly base: string = DefaultRestOptions.cdn) {}\n\n\t/**\n\t * Generates an app asset URL for a client's asset.\n\t *\n\t * @param clientId - The client id that has the asset\n\t * @param assetHash - The hash provided by Discord for this asset\n\t * @param options - Optional options for the asset\n\t */\n\tpublic appAsset(clientId: string, assetHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/${clientId}/${assetHash}`, options);\n\t}\n\n\t/**\n\t * Generates an app icon URL for a client's icon.\n\t *\n\t * @param clientId - The client id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic appIcon(clientId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-icons/${clientId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates an avatar URL, e.g. for a user or a webhook.\n\t *\n\t * @param id - The id that has the icon\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic avatar(id: string, avatarHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a banner URL, e.g. for a user or a guild.\n\t *\n\t * @param id - The id that has the banner splash\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic banner(id: string, bannerHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL for a channel, e.g. a group DM.\n\t *\n\t * @param channelId - The channel id that has the icon\n\t * @param iconHash - The hash provided by Discord for this channel\n\t * @param options - Optional options for the icon\n\t */\n\tpublic channelIcon(channelId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates the default avatar URL for a discriminator.\n\t *\n\t * @param discriminator - The discriminator modulo 5\n\t */\n\tpublic defaultAvatar(discriminator: number): string {\n\t\treturn this.makeURL(`/embed/avatars/${discriminator}`, { extension: 'png' });\n\t}\n\n\t/**\n\t * Generates a discovery splash URL for a guild's discovery splash.\n\t *\n\t * @param guildId - The guild id that has the discovery splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic discoverySplash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates an emoji's URL for an emoji.\n\t *\n\t * @param emojiId - The emoji id\n\t * @param extension - The extension of the emoji\n\t */\n\tpublic emoji(emojiId: string, extension?: ImageExtension): string {\n\t\treturn this.makeURL(`/emojis/${emojiId}`, { extension });\n\t}\n\n\t/**\n\t * Generates a guild member avatar URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic guildMemberAvatar(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tavatarHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a guild member banner URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic guildMemberBanner(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tbannerHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL, e.g. for a guild.\n\t *\n\t * @param id - The id that has the icon splash\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic icon(id: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options);\n\t}\n\n\t/**\n\t * Generates a URL for the icon of a role\n\t *\n\t * @param roleId - The id of the role that has the icon\n\t * @param roleIconHash - The hash provided by Discord for this role icon\n\t * @param options - Optional options for the role icon\n\t */\n\tpublic roleIcon(roleId: string, roleIconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a guild invite splash URL for a guild's invite splash.\n\t *\n\t * @param guildId - The guild id that has the invite splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic splash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates a sticker URL.\n\t *\n\t * @param stickerId - The sticker id\n\t * @param extension - The extension of the sticker\n\t * @privateRemarks\n\t * Stickers cannot have a `.webp` extension, so we default to a `.png`\n\t */\n\tpublic sticker(stickerId: string, extension: StickerExtension = 'png'): string {\n\t\treturn this.makeURL(`/stickers/${stickerId}`, { allowedExtensions: ALLOWED_STICKER_EXTENSIONS, extension });\n\t}\n\n\t/**\n\t * Generates a sticker pack banner URL.\n\t *\n\t * @param bannerId - The banner id\n\t * @param options - Optional options for the banner\n\t */\n\tpublic stickerPackBanner(bannerId: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options);\n\t}\n\n\t/**\n\t * Generates a team icon URL for a team's icon.\n\t *\n\t * @param teamId - The team id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic teamIcon(teamId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/team-icons/${teamId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a cover image for a guild scheduled event.\n\t *\n\t * @param scheduledEventId - The scheduled event id\n\t * @param coverHash - The hash provided by discord for this cover image\n\t * @param options - Optional options for the cover image\n\t */\n\tpublic guildScheduledEventCover(\n\t\tscheduledEventId: string,\n\t\tcoverHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`.\n\t *\n\t * @param route - The base cdn route\n\t * @param hash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the link\n\t */\n\tprivate dynamicMakeURL(\n\t\troute: string,\n\t\thash: string,\n\t\t{ forceStatic = false, ...options }: Readonly = {},\n\t): string {\n\t\treturn this.makeURL(route, !forceStatic && hash.startsWith('a_') ? { ...options, extension: 'gif' } : options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource\n\t *\n\t * @param route - The base cdn route\n\t * @param options - The extension/size options for the link\n\t */\n\tprivate makeURL(\n\t\troute: string,\n\t\t{ allowedExtensions = ALLOWED_EXTENSIONS, extension = 'webp', size }: Readonly = {},\n\t): string {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\textension = String(extension).toLowerCase();\n\n\t\tif (!allowedExtensions.includes(extension)) {\n\t\t\tthrow new RangeError(`Invalid extension provided: ${extension}\\nMust be one of: ${allowedExtensions.join(', ')}`);\n\t\t}\n\n\t\tif (size && !ALLOWED_SIZES.includes(size)) {\n\t\t\tthrow new RangeError(`Invalid size provided: ${size}\\nMust be one of: ${ALLOWED_SIZES.join(', ')}`);\n\t\t}\n\n\t\tconst url = new URL(`${this.base}${route}.${extension}`);\n\n\t\tif (size) {\n\t\t\turl.searchParams.set('size', String(size));\n\t\t}\n\n\t\treturn url.toString();\n\t}\n}\n","import process from 'node:process';\nimport { APIVersion } from 'discord-api-types/v10';\nimport { Agent } from 'undici';\nimport type { RESTOptions } from '../REST.js';\n\nexport const DefaultUserAgent =\n\t`DiscordBot (https://discord.js.org, 1.7.1)` as `DiscordBot (https://discord.js.org, ${string})`;\n\n/**\n * The default string to append onto the user agent.\n */\nexport const DefaultUserAgentAppendix = process.release?.name === 'node' ? `Node.js/${process.version}` : '';\n\nexport const DefaultRestOptions = {\n\tget agent() {\n\t\treturn new Agent({\n\t\t\tconnect: {\n\t\t\t\ttimeout: 30_000,\n\t\t\t},\n\t\t});\n\t},\n\tapi: 'https://discord.com/api',\n\tauthPrefix: 'Bot',\n\tcdn: 'https://cdn.discordapp.com',\n\theaders: {},\n\tinvalidRequestWarningInterval: 0,\n\tglobalRequestsPerSecond: 50,\n\toffset: 50,\n\trejectOnRateLimit: null,\n\tretries: 3,\n\ttimeout: 15_000,\n\tuserAgentAppendix: DefaultUserAgentAppendix,\n\tversion: APIVersion,\n\thashSweepInterval: 14_400_000, // 4 Hours\n\thashLifetime: 86_400_000, // 24 Hours\n\thandlerSweepInterval: 3_600_000, // 1 Hour\n} as const satisfies Required;\n\n/**\n * The events that the REST manager emits\n */\nexport enum RESTEvents {\n\tDebug = 'restDebug',\n\tHandlerSweep = 'handlerSweep',\n\tHashSweep = 'hashSweep',\n\tInvalidRequestWarning = 'invalidRequestWarning',\n\tRateLimited = 'rateLimited',\n\tResponse = 'response',\n}\n\nexport const ALLOWED_EXTENSIONS = ['webp', 'png', 'jpg', 'jpeg', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_STICKER_EXTENSIONS = ['png', 'json', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1_024, 2_048, 4_096] as const satisfies readonly number[];\n\nexport type ImageExtension = (typeof ALLOWED_EXTENSIONS)[number];\nexport type StickerExtension = (typeof ALLOWED_STICKER_EXTENSIONS)[number];\nexport type ImageSize = (typeof ALLOWED_SIZES)[number];\n\nexport const OverwrittenMimeTypes = {\n\t// https://github.com/discordjs/discord.js/issues/8557\n\t'image/apng': 'image/png',\n} as const satisfies Readonly>;\n\nexport const BurstHandlerMajorIdKey = 'burst';\n","import type { InternalRequest, RawFile } from '../RequestManager.js';\n\ninterface DiscordErrorFieldInformation {\n\tcode: string;\n\tmessage: string;\n}\n\ninterface DiscordErrorGroupWrapper {\n\t_errors: DiscordError[];\n}\n\ntype DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | { [k: string]: DiscordError };\n\nexport interface DiscordErrorData {\n\tcode: number;\n\terrors?: DiscordError;\n\tmessage: string;\n}\n\nexport interface OAuthErrorData {\n\terror: string;\n\terror_description?: string;\n}\n\nexport interface RequestBody {\n\tfiles: RawFile[] | undefined;\n\tjson: unknown | undefined;\n}\n\nfunction isErrorGroupWrapper(error: DiscordError): error is DiscordErrorGroupWrapper {\n\treturn Reflect.has(error as Record, '_errors');\n}\n\nfunction isErrorResponse(error: DiscordError): error is DiscordErrorFieldInformation {\n\treturn typeof Reflect.get(error as Record, 'message') === 'string';\n}\n\n/**\n * Represents an API error returned by Discord\n */\nexport class DiscordAPIError extends Error {\n\tpublic requestBody: RequestBody;\n\n\t/**\n\t * @param rawError - The error reported by Discord\n\t * @param code - The error code reported by Discord\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic rawError: DiscordErrorData | OAuthErrorData,\n\t\tpublic code: number | string,\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(DiscordAPIError.getMessage(rawError));\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${DiscordAPIError.name}[${this.code}]`;\n\t}\n\n\tprivate static getMessage(error: DiscordErrorData | OAuthErrorData) {\n\t\tlet flattened = '';\n\t\tif ('code' in error) {\n\t\t\tif (error.errors) {\n\t\t\t\tflattened = [...this.flattenDiscordError(error.errors)].join('\\n');\n\t\t\t}\n\n\t\t\treturn error.message && flattened\n\t\t\t\t? `${error.message}\\n${flattened}`\n\t\t\t\t: error.message || flattened || 'Unknown Error';\n\t\t}\n\n\t\treturn error.error_description ?? 'No Description';\n\t}\n\n\tprivate static *flattenDiscordError(obj: DiscordError, key = ''): IterableIterator {\n\t\tif (isErrorResponse(obj)) {\n\t\t\treturn yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();\n\t\t}\n\n\t\tfor (const [otherKey, val] of Object.entries(obj)) {\n\t\t\tconst nextKey = otherKey.startsWith('_')\n\t\t\t\t? key\n\t\t\t\t: key\n\t\t\t\t? Number.isNaN(Number(otherKey))\n\t\t\t\t\t? `${key}.${otherKey}`\n\t\t\t\t\t: `${key}[${otherKey}]`\n\t\t\t\t: otherKey;\n\n\t\t\tif (typeof val === 'string') {\n\t\t\t\tyield val;\n\t\t\t} else if (isErrorGroupWrapper(val)) {\n\t\t\t\tfor (const error of val._errors) {\n\t\t\t\t\tyield* this.flattenDiscordError(error, nextKey);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield* this.flattenDiscordError(val, nextKey);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { STATUS_CODES } from 'node:http';\nimport type { InternalRequest } from '../RequestManager.js';\nimport type { RequestBody } from './DiscordAPIError.js';\n\n/**\n * Represents a HTTP error\n */\nexport class HTTPError extends Error {\n\tpublic requestBody: RequestBody;\n\n\tpublic override name = HTTPError.name;\n\n\t/**\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(STATUS_CODES[status]);\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n}\n","import type { RateLimitData } from '../REST.js';\n\nexport class RateLimitError extends Error implements RateLimitData {\n\tpublic timeToReset: number;\n\n\tpublic limit: number;\n\n\tpublic method: string;\n\n\tpublic hash: string;\n\n\tpublic url: string;\n\n\tpublic route: string;\n\n\tpublic majorParameter: string;\n\n\tpublic global: boolean;\n\n\tpublic constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData) {\n\t\tsuper();\n\t\tthis.timeToReset = timeToReset;\n\t\tthis.limit = limit;\n\t\tthis.method = method;\n\t\tthis.hash = hash;\n\t\tthis.url = url;\n\t\tthis.route = route;\n\t\tthis.majorParameter = majorParameter;\n\t\tthis.global = global;\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${RateLimitError.name}[${this.route}]`;\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { setInterval, clearInterval } from 'node:timers';\nimport type { URLSearchParams } from 'node:url';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { DiscordSnowflake } from '@sapphire/snowflake';\nimport { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';\nimport type { RESTOptions, RestEvents, RequestOptions } from './REST.js';\nimport { BurstHandler } from './handlers/BurstHandler.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { SequentialHandler } from './handlers/SequentialHandler.js';\nimport {\n\tBurstHandlerMajorIdKey,\n\tDefaultRestOptions,\n\tDefaultUserAgent,\n\tOverwrittenMimeTypes,\n\tRESTEvents,\n} from './utils/constants.js';\nimport { resolveBody } from './utils/utils.js';\n\n// Make this a lazy dynamic import as file-type is a pure ESM package\nconst getFileType = lazy(async () => import('file-type'));\n\n/**\n * Represents a file to be added to the request\n */\nexport interface RawFile {\n\t/**\n\t * Content-Type of the file\n\t */\n\tcontentType?: string;\n\t/**\n\t * The actual data for the file\n\t */\n\tdata: Buffer | boolean | number | string;\n\t/**\n\t * An explicit key to use for key of the formdata field for this file.\n\t * When not provided, the index of the file in the files array is used in the form `files[${index}]`.\n\t * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)\n\t */\n\tkey?: string;\n\t/**\n\t * The name of the file\n\t */\n\tname: string;\n}\n\n/**\n * Represents possible data to be given to an endpoint\n */\nexport interface RequestData {\n\t/**\n\t * Whether to append JSON data to form data instead of `payload_json` when sending files\n\t */\n\tappendToFormData?: boolean;\n\t/**\n\t * If this request needs the `Authorization` header\n\t *\n\t * @defaultValue `true`\n\t */\n\tauth?: boolean;\n\t/**\n\t * The authorization prefix to use for this request, useful if you use this with bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix?: 'Bearer' | 'Bot';\n\t/**\n\t * The body to send to this request.\n\t * If providing as BodyInit, set `passThroughBody: true`\n\t */\n\tbody?: BodyInit | unknown;\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.\n\t */\n\tdispatcher?: Agent;\n\t/**\n\t * Files to be attached to this request\n\t */\n\tfiles?: RawFile[] | undefined;\n\t/**\n\t * Additional headers to add to this request\n\t */\n\theaders?: Record;\n\t/**\n\t * Whether to pass-through the body property directly to `fetch()`.\n\t * This only applies when files is NOT present\n\t */\n\tpassThroughBody?: boolean;\n\t/**\n\t * Query string parameters to append to the called endpoint\n\t */\n\tquery?: URLSearchParams;\n\t/**\n\t * Reason to show in the audit logs\n\t */\n\treason?: string | undefined;\n\t/**\n\t * The signal to abort the queue entry or the REST call, where applicable\n\t */\n\tsignal?: AbortSignal | undefined;\n\t/**\n\t * If this request should be versioned\n\t *\n\t * @defaultValue `true`\n\t */\n\tversioned?: boolean;\n}\n\n/**\n * Possible headers for an API call\n */\nexport interface RequestHeaders {\n\tAuthorization?: string;\n\t'User-Agent': string;\n\t'X-Audit-Log-Reason'?: string;\n}\n\n/**\n * Possible API methods to be used when doing requests\n */\nexport enum RequestMethod {\n\tDelete = 'DELETE',\n\tGet = 'GET',\n\tPatch = 'PATCH',\n\tPost = 'POST',\n\tPut = 'PUT',\n}\n\nexport type RouteLike = `/${string}`;\n\n/**\n * Internal request options\n *\n * @internal\n */\nexport interface InternalRequest extends RequestData {\n\tfullRoute: RouteLike;\n\tmethod: RequestMethod;\n}\n\nexport type HandlerRequestData = Pick;\n\n/**\n * Parsed route data for an endpoint\n *\n * @internal\n */\nexport interface RouteData {\n\tbucketRoute: string;\n\tmajorParameter: string;\n\toriginal: RouteLike;\n}\n\n/**\n * Represents a hash and its associated fields\n *\n * @internal\n */\nexport interface HashData {\n\tlastAccess: number;\n\tvalue: string;\n}\n\nexport interface RequestManager {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\n/**\n * Represents the class that manages handlers for endpoints\n */\nexport class RequestManager extends EventEmitter {\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests\n\t * performed by this manager.\n\t */\n\tpublic agent: Dispatcher | null = null;\n\n\t/**\n\t * The number of requests remaining in the global bucket\n\t */\n\tpublic globalRemaining: number;\n\n\t/**\n\t * The promise used to wait out the global rate limit\n\t */\n\tpublic globalDelay: Promise | null = null;\n\n\t/**\n\t * The timestamp at which the global bucket resets\n\t */\n\tpublic globalReset = -1;\n\n\t/**\n\t * API bucket hashes that are cached from provided routes\n\t */\n\tpublic readonly hashes = new Collection();\n\n\t/**\n\t * Request handlers created from the bucket hash and the major parameters\n\t */\n\tpublic readonly handlers = new Collection();\n\n\t#token: string | null = null;\n\n\tprivate hashTimer!: NodeJS.Timer;\n\n\tprivate handlerTimer!: NodeJS.Timer;\n\n\tpublic readonly options: RESTOptions;\n\n\tpublic constructor(options: Partial) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultRestOptions, ...options };\n\t\tthis.options.offset = Math.max(0, this.options.offset);\n\t\tthis.globalRemaining = this.options.globalRequestsPerSecond;\n\t\tthis.agent = options.agent ?? null;\n\n\t\t// Start sweepers\n\t\tthis.setupSweepers();\n\t}\n\n\tprivate setupSweepers() {\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\tconst validateMaxInterval = (interval: number) => {\n\t\t\tif (interval > 14_400_000) {\n\t\t\t\tthrow new Error('Cannot set an interval greater than 4 hours');\n\t\t\t}\n\t\t};\n\n\t\tif (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.hashSweepInterval);\n\t\t\tthis.hashTimer = setInterval(() => {\n\t\t\t\tconst sweptHashes = new Collection();\n\t\t\t\tconst currentDate = Date.now();\n\n\t\t\t\t// Begin sweeping hash based on lifetimes\n\t\t\t\tthis.hashes.sweep((val, key) => {\n\t\t\t\t\t// `-1` indicates a global hash\n\t\t\t\t\tif (val.lastAccess === -1) return false;\n\n\t\t\t\t\t// Check if lifetime has been exceeded\n\t\t\t\t\tconst shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime;\n\n\t\t\t\t\t// Add hash to collection of swept hashes\n\t\t\t\t\tif (shouldSweep) {\n\t\t\t\t\t\t// Add to swept hashes\n\t\t\t\t\t\tsweptHashes.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit debug information\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`);\n\n\t\t\t\t\treturn shouldSweep;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HashSweep, sweptHashes);\n\t\t\t}, this.options.hashSweepInterval).unref();\n\t\t}\n\n\t\tif (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.handlerSweepInterval);\n\t\t\tthis.handlerTimer = setInterval(() => {\n\t\t\t\tconst sweptHandlers = new Collection();\n\n\t\t\t\t// Begin sweeping handlers based on activity\n\t\t\t\tthis.handlers.sweep((val, key) => {\n\t\t\t\t\tconst { inactive } = val;\n\n\t\t\t\t\t// Collect inactive handlers\n\t\t\t\t\tif (inactive) {\n\t\t\t\t\t\tsweptHandlers.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`);\n\t\t\t\t\treturn inactive;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HandlerSweep, sweptHandlers);\n\t\t\t}, this.options.handlerSweepInterval).unref();\n\t\t}\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this manager\n\t *\n\t * @param agent - The agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.agent = agent;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.#token = token;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Queues a request to be sent\n\t *\n\t * @param request - All the information needed to make a request\n\t * @returns The response from the api request\n\t */\n\tpublic async queueRequest(request: InternalRequest): Promise {\n\t\t// Generalize the endpoint to its route data\n\t\tconst routeId = RequestManager.generateRouteData(request.fullRoute, request.method);\n\t\t// Get the bucket hash for the generic route, or point to a global route otherwise\n\t\tconst hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {\n\t\t\tvalue: `Global(${request.method}:${routeId.bucketRoute})`,\n\t\t\tlastAccess: -1,\n\t\t};\n\n\t\t// Get the request handler for the obtained hash, with its major parameter\n\t\tconst handler =\n\t\t\tthis.handlers.get(`${hash.value}:${routeId.majorParameter}`) ??\n\t\t\tthis.createHandler(hash.value, routeId.majorParameter);\n\n\t\t// Resolve the request into usable fetch options\n\t\tconst { url, fetchOptions } = await this.resolveRequest(request);\n\n\t\t// Queue the request\n\t\treturn handler.queueRequest(routeId, url, fetchOptions, {\n\t\t\tbody: request.body,\n\t\t\tfiles: request.files,\n\t\t\tauth: request.auth !== false,\n\t\t\tsignal: request.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new rate limit handler from a hash, based on the hash and the major parameter\n\t *\n\t * @param hash - The hash for the route\n\t * @param majorParameter - The major parameter for this handler\n\t * @internal\n\t */\n\tprivate createHandler(hash: string, majorParameter: string) {\n\t\t// Create the async request queue to handle requests\n\t\tconst queue =\n\t\t\tmajorParameter === BurstHandlerMajorIdKey\n\t\t\t\t? new BurstHandler(this, hash, majorParameter)\n\t\t\t\t: new SequentialHandler(this, hash, majorParameter);\n\t\t// Save the queue based on its id\n\t\tthis.handlers.set(queue.id, queue);\n\n\t\treturn queue;\n\t}\n\n\t/**\n\t * Formats the request data to a usable format for fetch\n\t *\n\t * @param request - The request data\n\t */\n\tprivate async resolveRequest(request: InternalRequest): Promise<{ fetchOptions: RequestOptions; url: string }> {\n\t\tconst { options } = this;\n\n\t\tlet query = '';\n\n\t\t// If a query option is passed, use it\n\t\tif (request.query) {\n\t\t\tconst resolvedQuery = request.query.toString();\n\t\t\tif (resolvedQuery !== '') {\n\t\t\t\tquery = `?${resolvedQuery}`;\n\t\t\t}\n\t\t}\n\n\t\t// Create the required headers\n\t\tconst headers: RequestHeaders = {\n\t\t\t...this.options.headers,\n\t\t\t'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),\n\t\t};\n\n\t\t// If this request requires authorization (allowing non-\"authorized\" requests for webhooks)\n\t\tif (request.auth !== false) {\n\t\t\t// If we haven't received a token, throw an error\n\t\t\tif (!this.#token) {\n\t\t\t\tthrow new Error('Expected token to be set for this request, but none was present');\n\t\t\t}\n\n\t\t\theaders.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${this.#token}`;\n\t\t}\n\n\t\t// If a reason was set, set it's appropriate header\n\t\tif (request.reason?.length) {\n\t\t\theaders['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);\n\t\t}\n\n\t\t// Format the full request URL (api base, optional version, endpoint, optional querystring)\n\t\tconst url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${\n\t\t\trequest.fullRoute\n\t\t}${query}`;\n\n\t\tlet finalBody: RequestInit['body'];\n\t\tlet additionalHeaders: Record = {};\n\n\t\tif (request.files?.length) {\n\t\t\tconst formData = new FormData();\n\n\t\t\t// Attach all files to the request\n\t\t\tfor (const [index, file] of request.files.entries()) {\n\t\t\t\tconst fileKey = file.key ?? `files[${index}]`;\n\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#parameters\n\t\t\t\t// FormData.append only accepts a string or Blob.\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters\n\t\t\t\t// The Blob constructor accepts TypedArray/ArrayBuffer, strings, and Blobs.\n\t\t\t\tif (Buffer.isBuffer(file.data)) {\n\t\t\t\t\t// Try to infer the content type from the buffer if one isn't passed\n\t\t\t\t\tconst { fileTypeFromBuffer } = await getFileType();\n\t\t\t\t\tlet contentType = file.contentType;\n\t\t\t\t\tif (!contentType) {\n\t\t\t\t\t\tconst parsedType = (await fileTypeFromBuffer(file.data))?.mime;\n\t\t\t\t\t\tif (parsedType) {\n\t\t\t\t\t\t\tcontentType = OverwrittenMimeTypes[parsedType as keyof typeof OverwrittenMimeTypes] ?? parsedType;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tformData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);\n\t\t\t\t} else {\n\t\t\t\t\tformData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (request.body != null) {\n\t\t\t\tif (request.appendToFormData) {\n\t\t\t\t\tfor (const [key, value] of Object.entries(request.body as Record)) {\n\t\t\t\t\t\tformData.append(key, value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.append('payload_json', JSON.stringify(request.body));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set the final body to the form data\n\t\t\tfinalBody = formData;\n\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t} else if (request.body != null) {\n\t\t\tif (request.passThroughBody) {\n\t\t\t\tfinalBody = request.body as BodyInit;\n\t\t\t} else {\n\t\t\t\t// Stringify the JSON data\n\t\t\t\tfinalBody = JSON.stringify(request.body);\n\t\t\t\t// Set the additional headers to specify the content-type\n\t\t\t\tadditionalHeaders = { 'Content-Type': 'application/json' };\n\t\t\t}\n\t\t}\n\n\t\tfinalBody = await resolveBody(finalBody);\n\n\t\tconst fetchOptions: RequestOptions = {\n\t\t\theaders: { ...request.headers, ...additionalHeaders, ...headers } as Record,\n\t\t\tmethod: request.method.toUpperCase() as Dispatcher.HttpMethod,\n\t\t};\n\n\t\tif (finalBody !== undefined) {\n\t\t\tfetchOptions.body = finalBody as Exclude;\n\t\t}\n\n\t\t// Prioritize setting an agent per request, use the agent for this instance otherwise.\n\t\tfetchOptions.dispatcher = request.dispatcher ?? this.agent ?? undefined!;\n\n\t\treturn { url, fetchOptions };\n\t}\n\n\t/**\n\t * Stops the hash sweeping interval\n\t */\n\tpublic clearHashSweeper() {\n\t\tclearInterval(this.hashTimer);\n\t}\n\n\t/**\n\t * Stops the request handler sweeping interval\n\t */\n\tpublic clearHandlerSweeper() {\n\t\tclearInterval(this.handlerTimer);\n\t}\n\n\t/**\n\t * Generates route data for an endpoint:method\n\t *\n\t * @param endpoint - The raw endpoint to generalize\n\t * @param method - The HTTP method this endpoint is called without\n\t * @internal\n\t */\n\tprivate static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {\n\t\tif (endpoint.startsWith('/interactions/') && endpoint.endsWith('/callback')) {\n\t\t\treturn {\n\t\t\t\tmajorParameter: BurstHandlerMajorIdKey,\n\t\t\t\tbucketRoute: '/interactions/:id/:token/callback',\n\t\t\t\toriginal: endpoint,\n\t\t\t};\n\t\t}\n\n\t\tconst majorIdMatch = /^\\/(?:channels|guilds|webhooks)\\/(\\d{17,19})/.exec(endpoint);\n\n\t\t// Get the major id for this route - global otherwise\n\t\tconst majorId = majorIdMatch?.[1] ?? 'global';\n\n\t\tconst baseRoute = endpoint\n\t\t\t// Strip out all ids\n\t\t\t.replaceAll(/\\d{17,19}/g, ':id')\n\t\t\t// Strip out reaction as they fall under the same bucket\n\t\t\t.replace(/\\/reactions\\/(.*)/, '/reactions/:reaction');\n\n\t\tlet exceptions = '';\n\n\t\t// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)\n\t\t// https://github.com/discord/discord-api-docs/issues/1295\n\t\tif (method === RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {\n\t\t\tconst id = /\\d{17,19}$/.exec(endpoint)![0]!;\n\t\t\tconst timestamp = DiscordSnowflake.timestampFrom(id);\n\t\t\tif (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {\n\t\t\t\texceptions += '/Delete Old Message';\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmajorParameter: majorId,\n\t\t\tbucketRoute: baseRoute + exceptions,\n\t\t\toriginal: endpoint,\n\t\t};\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport type { Dispatcher } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { onRateLimit, parseHeader } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\nimport { handleErrors, incrementInvalidCount, makeNetworkRequest } from './Shared.js';\n\n/**\n * The structure used to handle burst requests for a given bucket.\n * Burst requests have no ratelimit handling but allow for pre- and post-processing\n * of data in the same manner as sequentially queued requests.\n *\n * @remarks\n * This queue may still emit a rate limit error if an unexpected 429 is hit\n */\nexport class BurstHandler implements IHandler {\n\t/**\n\t * {@inheritdoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic inactive = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\treturn this.runRequest(routeId, url, options, requestData);\n\t}\n\n\t/**\n\t * The method that actually makes the request to the API, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized API route with literal ids for major parameters\n\t * @param url - The fully resolved URL to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries);\n\n\t\t// Retry requested\n\t\tif (res === null) {\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tincrementInvalidCount(this.manager);\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// Unexpected ratelimit\n\t\t\tconst isGlobal = res.headers['x-ratelimit-global'] !== undefined;\n\t\t\tawait onRateLimit(this.manager, {\n\t\t\t\ttimeToReset: retryAfter,\n\t\t\t\tlimit: Number.POSITIVE_INFINITY,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${Number.POSITIVE_INFINITY}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : None`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\n\t\t\t// We are bypassing all other limits, but an encountered limit should be respected (it's probably a non-punished rate limit anyways)\n\t\t\tawait sleep(retryAfter);\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else {\n\t\t\tconst handled = await handleErrors(this.manager, res, method, url, requestData, retries);\n\t\t\tif (handled === null) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\treturn handled;\n\t\t}\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { URLSearchParams } from 'node:url';\nimport { types } from 'node:util';\nimport type { RESTPatchAPIChannelJSONBody } from 'discord-api-types/v10';\nimport { FormData, type Dispatcher, type RequestInit } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST.js';\nimport { type RequestManager, RequestMethod } from '../RequestManager.js';\nimport { RateLimitError } from '../errors/RateLimitError.js';\n\nexport function parseHeader(header: string[] | string | undefined): string | undefined {\n\tif (header === undefined || typeof header === 'string') {\n\t\treturn header;\n\t}\n\n\treturn header.join(';');\n}\n\nfunction serializeSearchParam(value: unknown): string | null {\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn value;\n\t\tcase 'number':\n\t\tcase 'bigint':\n\t\tcase 'boolean':\n\t\t\treturn value.toString();\n\t\tcase 'object':\n\t\t\tif (value === null) return null;\n\t\t\tif (value instanceof Date) {\n\t\t\t\treturn Number.isNaN(value.getTime()) ? null : value.toISOString();\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-base-to-string\n\t\t\tif (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) return value.toString();\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Creates and populates an URLSearchParams instance from an object, stripping\n * out null and undefined values, while also coercing non-strings to strings.\n *\n * @param options - The options to use\n * @returns A populated URLSearchParams instance\n */\nexport function makeURLSearchParams(options?: Readonly) {\n\tconst params = new URLSearchParams();\n\tif (!options) return params;\n\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tconst serialized = serializeSearchParam(value);\n\t\tif (serialized !== null) params.append(key, serialized);\n\t}\n\n\treturn params;\n}\n\n/**\n * Converts the response to usable data\n *\n * @param res - The fetch response\n */\nexport async function parseResponse(res: Dispatcher.ResponseData): Promise {\n\tconst header = parseHeader(res.headers['content-type']);\n\tif (header?.startsWith('application/json')) {\n\t\treturn res.body.json();\n\t}\n\n\treturn res.body.arrayBuffer();\n}\n\n/**\n * Check whether a request falls under a sublimit\n *\n * @param bucketRoute - The buckets route identifier\n * @param body - The options provided as JSON data\n * @param method - The HTTP method that will be used to make the request\n * @returns Whether the request falls under a sublimit\n */\nexport function hasSublimit(bucketRoute: string, body?: unknown, method?: string): boolean {\n\t// TODO: Update for new sublimits\n\t// Currently known sublimits:\n\t// Editing channel `name` or `topic`\n\tif (bucketRoute === '/channels/:id') {\n\t\tif (typeof body !== 'object' || body === null) return false;\n\t\t// This should never be a POST body, but just in case\n\t\tif (method !== RequestMethod.Patch) return false;\n\t\tconst castedBody = body as RESTPatchAPIChannelJSONBody;\n\t\treturn ['name', 'topic'].some((key) => Reflect.has(castedBody, key));\n\t}\n\n\t// If we are checking if a request has a sublimit on a route not checked above, sublimit all requests to avoid a flood of 429s\n\treturn true;\n}\n\nexport async function resolveBody(body: RequestInit['body']): Promise {\n\t// eslint-disable-next-line no-eq-null, eqeqeq\n\tif (body == null) {\n\t\treturn null;\n\t} else if (typeof body === 'string') {\n\t\treturn body;\n\t} else if (types.isUint8Array(body)) {\n\t\treturn body;\n\t} else if (types.isArrayBuffer(body)) {\n\t\treturn new Uint8Array(body);\n\t} else if (body instanceof URLSearchParams) {\n\t\treturn body.toString();\n\t} else if (body instanceof DataView) {\n\t\treturn new Uint8Array(body.buffer);\n\t} else if (body instanceof Blob) {\n\t\treturn new Uint8Array(await body.arrayBuffer());\n\t} else if (body instanceof FormData) {\n\t\treturn body;\n\t} else if ((body as Iterable)[Symbol.iterator]) {\n\t\tconst chunks = [...(body as Iterable)];\n\t\tconst length = chunks.reduce((a, b) => a + b.length, 0);\n\n\t\tconst uint8 = new Uint8Array(length);\n\t\tlet lengthUsed = 0;\n\n\t\treturn chunks.reduce((a, b) => {\n\t\t\ta.set(b, lengthUsed);\n\t\t\tlengthUsed += b.length;\n\t\t\treturn a;\n\t\t}, uint8);\n\t} else if ((body as AsyncIterable)[Symbol.asyncIterator]) {\n\t\tconst chunks: Uint8Array[] = [];\n\n\t\tfor await (const chunk of body as AsyncIterable) {\n\t\t\tchunks.push(chunk);\n\t\t}\n\n\t\treturn Buffer.concat(chunks);\n\t}\n\n\tthrow new TypeError(`Unable to resolve body.`);\n}\n\n/**\n * Check whether an error indicates that a retry can be attempted\n *\n * @param error - The error thrown by the network request\n * @returns Whether the error indicates a retry should be attempted\n */\nexport function shouldRetry(error: Error | NodeJS.ErrnoException) {\n\t// Retry for possible timed out requests\n\tif (error.name === 'AbortError') return true;\n\t// Downlevel ECONNRESET to retry as it may be recoverable\n\treturn ('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET');\n}\n\n/**\n * Determines whether the request should be queued or whether a RateLimitError should be thrown\n *\n * @internal\n */\nexport async function onRateLimit(manager: RequestManager, rateLimitData: RateLimitData) {\n\tconst { options } = manager;\n\tif (!options.rejectOnRateLimit) return;\n\n\tconst shouldThrow =\n\t\ttypeof options.rejectOnRateLimit === 'function'\n\t\t\t? await options.rejectOnRateLimit(rateLimitData)\n\t\t\t: options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase()));\n\tif (shouldThrow) {\n\t\tthrow new RateLimitError(rateLimitData);\n\t}\n}\n","import { setTimeout, clearTimeout } from 'node:timers';\nimport { request, type Dispatcher } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport type { DiscordErrorData, OAuthErrorData } from '../errors/DiscordAPIError.js';\nimport { DiscordAPIError } from '../errors/DiscordAPIError.js';\nimport { HTTPError } from '../errors/HTTPError.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { parseResponse, shouldRetry } from '../utils/utils.js';\nimport type { PolyFillAbortSignal } from './IHandler.js';\n\n/**\n * Invalid request limiting is done on a per-IP basis, not a per-token basis.\n * The best we can do is track invalid counts process-wide (on the theory that\n * users could have multiple bots run from one process) rather than per-bot.\n * Therefore, store these at file scope here rather than in the client's\n * RESTManager object.\n */\nlet invalidCount = 0;\nlet invalidCountResetTime: number | null = null;\n\n/**\n * Increment the invalid request count and emit warning if necessary\n *\n * @internal\n */\nexport function incrementInvalidCount(manager: RequestManager) {\n\tif (!invalidCountResetTime || invalidCountResetTime < Date.now()) {\n\t\tinvalidCountResetTime = Date.now() + 1_000 * 60 * 10;\n\t\tinvalidCount = 0;\n\t}\n\n\tinvalidCount++;\n\n\tconst emitInvalid =\n\t\tmanager.options.invalidRequestWarningInterval > 0 &&\n\t\tinvalidCount % manager.options.invalidRequestWarningInterval === 0;\n\tif (emitInvalid) {\n\t\t// Let library users know periodically about invalid requests\n\t\tmanager.emit(RESTEvents.InvalidRequestWarning, {\n\t\t\tcount: invalidCount,\n\t\t\tremainingTime: invalidCountResetTime - Date.now(),\n\t\t});\n\t}\n}\n\n/**\n * Performs the actual network request for a request handler\n *\n * @param manager - The manager that holds options and emits informational events\n * @param routeId - The generalized api route with literal ids for major parameters\n * @param url - The fully resolved url to make the request to\n * @param options - The fetch options needed to make the request\n * @param requestData - Extra data from the user's request needed for errors and additional processing\n * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)\n * @returns The respond from the network or `null` when the request should be retried\n * @internal\n */\nexport async function makeNetworkRequest(\n\tmanager: RequestManager,\n\trouteId: RouteData,\n\turl: string,\n\toptions: RequestOptions,\n\trequestData: HandlerRequestData,\n\tretries: number,\n) {\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(() => controller.abort(), manager.options.timeout).unref();\n\tif (requestData.signal) {\n\t\t// The type polyfill is required because Node.js's types are incomplete.\n\t\tconst signal = requestData.signal as unknown as PolyFillAbortSignal;\n\t\t// If the user signal was aborted, abort the controller, else abort the local signal.\n\t\t// The reason why we don't re-use the user's signal, is because users may use the same signal for multiple\n\t\t// requests, and we do not want to cause unexpected side-effects.\n\t\tif (signal.aborted) controller.abort();\n\t\telse signal.addEventListener('abort', () => controller.abort());\n\t}\n\n\tlet res: Dispatcher.ResponseData;\n\ttry {\n\t\tres = await request(url, { ...options, signal: controller.signal });\n\t} catch (error: unknown) {\n\t\tif (!(error instanceof Error)) throw error;\n\t\t// Retry the specified number of times if needed\n\t\tif (shouldRetry(error) && retries !== manager.options.retries) {\n\t\t\t// Retry is handled by the handler upon receiving null\n\t\t\treturn null;\n\t\t}\n\n\t\tthrow error;\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n\n\tif (manager.listenerCount(RESTEvents.Response)) {\n\t\tmanager.emit(\n\t\t\tRESTEvents.Response,\n\t\t\t{\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\tpath: routeId.original,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\toptions,\n\t\t\t\tdata: requestData,\n\t\t\t\tretries,\n\t\t\t},\n\t\t\t{ ...res },\n\t\t);\n\t}\n\n\treturn res;\n}\n\n/**\n * Handles 5xx and 4xx errors (not 429's) conventionally. 429's should be handled before calling this function\n *\n * @param manager - The manager that holds options and emits informational events\n * @param res - The response received from {@link makeNetworkRequest}\n * @param method - The method used to make the request\n * @param url - The fully resolved url to make the request to\n * @param requestData - Extra data from the user's request needed for errors and additional processing\n * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)\n * @returns - The response if the status code is not handled or null to request a retry\n */\nexport async function handleErrors(\n\tmanager: RequestManager,\n\tres: Dispatcher.ResponseData,\n\tmethod: string,\n\turl: string,\n\trequestData: HandlerRequestData,\n\tretries: number,\n) {\n\tconst status = res.statusCode;\n\tif (status >= 500 && status < 600) {\n\t\t// Retry the specified number of times for possible server side issues\n\t\tif (retries !== manager.options.retries) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// We are out of retries, throw an error\n\t\tthrow new HTTPError(status, method, url, requestData);\n\t} else {\n\t\t// Handle possible malformed requests\n\t\tif (status >= 400 && status < 500) {\n\t\t\t// If we receive this status code, it means the token we had is no longer valid.\n\t\t\tif (status === 401 && requestData.auth) {\n\t\t\t\tmanager.setToken(null!);\n\t\t\t}\n\n\t\t\t// The request will not succeed for some reason, parse the error returned from the api\n\t\t\tconst data = (await parseResponse(res)) as DiscordErrorData | OAuthErrorData;\n\t\t\t// throw the API error\n\t\t\tthrow new DiscordAPIError(data, 'code' in data ? data.code : data.error, status, method, url, requestData);\n\t\t}\n\n\t\treturn res;\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport type { Dispatcher } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { hasSublimit, onRateLimit, parseHeader } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\nimport { handleErrors, incrementInvalidCount, makeNetworkRequest } from './Shared.js';\n\nconst enum QueueType {\n\tStandard,\n\tSublimit,\n}\n\n/**\n * The structure used to handle sequential requests for a given bucket\n */\nexport class SequentialHandler implements IHandler {\n\t/**\n\t * {@inheritDoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * The time this rate limit bucket will reset\n\t */\n\tprivate reset = -1;\n\n\t/**\n\t * The remaining requests that can be made before we are rate limited\n\t */\n\tprivate remaining = 1;\n\n\t/**\n\t * The total number of requests that can be made before we are rate limited\n\t */\n\tprivate limit = Number.POSITIVE_INFINITY;\n\n\t/**\n\t * The interface used to sequence async requests sequentially\n\t */\n\t#asyncQueue = new AsyncQueue();\n\n\t/**\n\t * The interface used to sequence sublimited async requests sequentially\n\t */\n\t#sublimitedQueue: AsyncQueue | null = null;\n\n\t/**\n\t * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed\n\t */\n\t#sublimitPromise: { promise: Promise; resolve(): void } | null = null;\n\n\t/**\n\t * Whether the sublimit queue needs to be shifted in the finally block\n\t */\n\t#shiftSublimit = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic get inactive(): boolean {\n\t\treturn (\n\t\t\tthis.#asyncQueue.remaining === 0 &&\n\t\t\t(this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) &&\n\t\t\t!this.limited\n\t\t);\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by the global limit\n\t */\n\tprivate get globalLimited(): boolean {\n\t\treturn this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by its limit\n\t */\n\tprivate get localLimited(): boolean {\n\t\treturn this.remaining <= 0 && Date.now() < this.reset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited\n\t */\n\tprivate get limited(): boolean {\n\t\treturn this.globalLimited || this.localLimited;\n\t}\n\n\t/**\n\t * The time until queued requests can continue\n\t */\n\tprivate get timeToReset(): number {\n\t\treturn this.reset + this.manager.options.offset - Date.now();\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * Delay all requests for the specified amount of time, handling global rate limits\n\t *\n\t * @param time - The amount of time to delay all requests for\n\t */\n\tprivate async globalDelayFor(time: number): Promise {\n\t\tawait sleep(time);\n\t\tthis.manager.globalDelay = null;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\tlet queue = this.#asyncQueue;\n\t\tlet queueType = QueueType.Standard;\n\t\t// Separate sublimited requests when already sublimited\n\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\tqueueType = QueueType.Sublimit;\n\t\t}\n\n\t\t// Wait for any previous requests to be completed before this one is run\n\t\tawait queue.wait({ signal: requestData.signal });\n\t\t// This set handles retroactively sublimiting requests\n\t\tif (queueType === QueueType.Standard) {\n\t\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\t\t/**\n\t\t\t\t * Remove the request from the standard queue, it should never be possible to get here while processing the\n\t\t\t\t * sublimit queue so there is no need to worry about shifting the wrong request\n\t\t\t\t */\n\t\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\t\tconst wait = queue.wait();\n\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\tawait wait;\n\t\t\t} else if (this.#sublimitPromise) {\n\t\t\t\t// Stall requests while the sublimit queue gets processed\n\t\t\t\tawait this.#sublimitPromise.promise;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request, and return the results\n\t\t\treturn await this.runRequest(routeId, url, options, requestData);\n\t\t} finally {\n\t\t\t// Allow the next request to fire\n\t\t\tqueue.shift();\n\t\t\tif (this.#shiftSublimit) {\n\t\t\t\tthis.#shiftSublimit = false;\n\t\t\t\tthis.#sublimitedQueue?.shift();\n\t\t\t}\n\n\t\t\t// If this request is the last request in a sublimit\n\t\t\tif (this.#sublimitedQueue?.remaining === 0) {\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitedQueue = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The method that actually makes the request to the api, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized api route with literal ids for major parameters\n\t * @param url - The fully resolved url to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\t/*\n\t\t * After calculations have been done, pre-emptively stop further requests\n\t\t * Potentially loop until this task can run if e.g. the global rate limit is hit twice\n\t\t */\n\t\twhile (this.limited) {\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\t\t\tlet delay: Promise;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t\t// If this is the first task to reach the global timeout, set the global delay\n\t\t\t\tif (!this.manager.globalDelay) {\n\t\t\t\t\t// The global delay function clears the global delay state when it is resolved\n\t\t\t\t\tthis.manager.globalDelay = this.globalDelayFor(timeout);\n\t\t\t\t}\n\n\t\t\t\tdelay = this.manager.globalDelay;\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t\tdelay = sleep(timeout);\n\t\t\t}\n\n\t\t\tconst rateLimitData: RateLimitData = {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t};\n\t\t\t// Let library users know they have hit a rate limit\n\t\t\tthis.manager.emit(RESTEvents.RateLimited, rateLimitData);\n\t\t\t// Determine whether a RateLimitError should be thrown\n\t\t\tawait onRateLimit(this.manager, rateLimitData);\n\t\t\t// When not erroring, emit debug for what is happening\n\t\t\tif (isGlobal) {\n\t\t\t\tthis.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`);\n\t\t\t} else {\n\t\t\t\tthis.debug(`Waiting ${timeout}ms for rate limit to pass`);\n\t\t\t}\n\n\t\t\t// Wait the remaining time left before the rate limit resets\n\t\t\tawait delay;\n\t\t}\n\n\t\t// As the request goes out, update the global usage information\n\t\tif (!this.manager.globalReset || this.manager.globalReset < Date.now()) {\n\t\t\tthis.manager.globalReset = Date.now() + 1_000;\n\t\t\tthis.manager.globalRemaining = this.manager.options.globalRequestsPerSecond;\n\t\t}\n\n\t\tthis.manager.globalRemaining--;\n\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries);\n\n\t\t// Retry requested\n\t\tif (res === null) {\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\n\t\tconst limit = parseHeader(res.headers['x-ratelimit-limit']);\n\t\tconst remaining = parseHeader(res.headers['x-ratelimit-remaining']);\n\t\tconst reset = parseHeader(res.headers['x-ratelimit-reset-after']);\n\t\tconst hash = parseHeader(res.headers['x-ratelimit-bucket']);\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Update the total number of requests that can be made before the rate limit resets\n\t\tthis.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY;\n\t\t// Update the number of remaining requests that can be made before the rate limit resets\n\t\tthis.remaining = remaining ? Number(remaining) : 1;\n\t\t// Update the time when this rate limit resets (reset-after is in seconds)\n\t\tthis.reset = reset ? Number(reset) * 1_000 + Date.now() + this.manager.options.offset : Date.now();\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Handle buckets via the hash header retroactively\n\t\tif (hash && hash !== this.hash) {\n\t\t\t// Let library users know when rate limit buckets have been updated\n\t\t\tthis.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\\n'));\n\t\t\t// This queue will eventually be eliminated via attrition\n\t\t\tthis.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { value: hash, lastAccess: Date.now() });\n\t\t} else if (hash) {\n\t\t\t// Handle the case where hash value doesn't change\n\t\t\t// Fetch the hash data from the manager\n\t\t\tconst hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`);\n\n\t\t\t// When fetched, update the last access of the hash\n\t\t\tif (hashData) {\n\t\t\t\thashData.lastAccess = Date.now();\n\t\t\t}\n\t\t}\n\n\t\t// Handle retryAfter, which means we have actually hit a rate limit\n\t\tlet sublimitTimeout: number | null = null;\n\t\tif (retryAfter > 0) {\n\t\t\tif (res.headers['x-ratelimit-global'] !== undefined) {\n\t\t\t\tthis.manager.globalRemaining = 0;\n\t\t\t\tthis.manager.globalReset = Date.now() + retryAfter;\n\t\t\t} else if (!this.localLimited) {\n\t\t\t\t/*\n\t\t\t\t * This is a sublimit (e.g. 2 channel name changes/10 minutes) since the headers don't indicate a\n\t\t\t\t * route-wide rate limit. Don't update remaining or reset to avoid rate limiting the whole\n\t\t\t\t * endpoint, just set a reset time on the request itself to avoid retrying too soon.\n\t\t\t\t */\n\t\t\t\tsublimitTimeout = retryAfter;\n\t\t\t}\n\t\t}\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tincrementInvalidCount(this.manager);\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t}\n\n\t\t\tawait onRateLimit(this.manager, {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal.toString()}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${limit}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\t\t\t// If caused by a sublimit, wait it out here so other requests on the route can be handled\n\t\t\tif (sublimitTimeout) {\n\t\t\t\t// Normally the sublimit queue will not exist, however, if a sublimit is hit while in the sublimit queue, it will\n\t\t\t\tconst firstSublimit = !this.#sublimitedQueue;\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\tthis.#sublimitedQueue = new AsyncQueue();\n\t\t\t\t\tvoid this.#sublimitedQueue.wait();\n\t\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\t}\n\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitPromise = null;\n\t\t\t\tawait sleep(sublimitTimeout);\n\t\t\t\tlet resolve: () => void;\n\t\t\t\t// eslint-disable-next-line promise/param-names, no-promise-executor-return\n\t\t\t\tconst promise = new Promise((res) => (resolve = res));\n\t\t\t\tthis.#sublimitPromise = { promise, resolve: resolve! };\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\t// Re-queue this request so it can be shifted by the finally\n\t\t\t\t\tawait this.#asyncQueue.wait();\n\t\t\t\t\tthis.#shiftSublimit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else {\n\t\t\tconst handled = await handleErrors(this.manager, res, method, url, requestData, retries);\n\t\t\tif (handled === null) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\treturn handled;\n\t\t}\n\t}\n}\n","import { EventEmitter } from 'node:events';\nimport type { Collection } from '@discordjs/collection';\nimport type { request, Dispatcher } from 'undici';\nimport { CDN } from './CDN.js';\nimport {\n\tRequestManager,\n\tRequestMethod,\n\ttype HashData,\n\ttype HandlerRequestData,\n\ttype InternalRequest,\n\ttype RequestData,\n\ttype RouteLike,\n} from './RequestManager.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { DefaultRestOptions, RESTEvents } from './utils/constants.js';\nimport { parseResponse } from './utils/utils.js';\n\n/**\n * Options to be passed when creating the REST instance\n */\nexport interface RESTOptions {\n\t/**\n\t * The agent to set globally\n\t */\n\tagent: Dispatcher;\n\t/**\n\t * The base api path, without version\n\t *\n\t * @defaultValue `'https://discord.com/api'`\n\t */\n\tapi: string;\n\t/**\n\t * The authorization prefix to use for requests, useful if you want to use\n\t * bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix: 'Bearer' | 'Bot';\n\t/**\n\t * The cdn path\n\t *\n\t * @defaultValue 'https://cdn.discordapp.com'\n\t */\n\tcdn: string;\n\t/**\n\t * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)\n\t *\n\t * @defaultValue `50`\n\t */\n\tglobalRequestsPerSecond: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)\n\t *\n\t * @defaultValue `3_600_000`\n\t */\n\thandlerSweepInterval: number;\n\t/**\n\t * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)\n\t *\n\t * @defaultValue `86_400_000`\n\t */\n\thashLifetime: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)\n\t *\n\t * @defaultValue `14_400_000`\n\t */\n\thashSweepInterval: number;\n\t/**\n\t * Additional headers to send for all API requests\n\t *\n\t * @defaultValue `{}`\n\t */\n\theaders: Record;\n\t/**\n\t * The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).\n\t * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.\n\t *\n\t * @defaultValue `0`\n\t */\n\tinvalidRequestWarningInterval: number;\n\t/**\n\t * The extra offset to add to rate limits in milliseconds\n\t *\n\t * @defaultValue `50`\n\t */\n\toffset: number;\n\t/**\n\t * Determines how rate limiting and pre-emptive throttling should be handled.\n\t * When an array of strings, each element is treated as a prefix for the request route\n\t * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)\n\t * for which to throw {@link RateLimitError}s. All other request routes will be queued normally\n\t *\n\t * @defaultValue `null`\n\t */\n\trejectOnRateLimit: RateLimitQueueFilter | string[] | null;\n\t/**\n\t * The number of retries for errors with the 500 code, or errors\n\t * that timeout\n\t *\n\t * @defaultValue `3`\n\t */\n\tretries: number;\n\t/**\n\t * The time to wait in milliseconds before a request is aborted\n\t *\n\t * @defaultValue `15_000`\n\t */\n\ttimeout: number;\n\t/**\n\t * Extra information to add to the user agent\n\t *\n\t * @defaultValue DefaultUserAgentAppendix\n\t */\n\tuserAgentAppendix: string;\n\t/**\n\t * The version of the API to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\n/**\n * Data emitted on `RESTEvents.RateLimited`\n */\nexport interface RateLimitData {\n\t/**\n\t * Whether the rate limit that was reached was the global limit\n\t */\n\tglobal: boolean;\n\t/**\n\t * The bucket hash for this request\n\t */\n\thash: string;\n\t/**\n\t * The amount of requests we can perform before locking requests\n\t */\n\tlimit: number;\n\t/**\n\t * The major parameter of the route\n\t *\n\t * For example, in `/channels/x`, this will be `x`.\n\t * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.\n\t */\n\tmajorParameter: string;\n\t/**\n\t * The HTTP method being performed\n\t */\n\tmethod: string;\n\t/**\n\t * The route being hit in this request\n\t */\n\troute: string;\n\t/**\n\t * The time, in milliseconds, until the request-lock is reset\n\t */\n\ttimeToReset: number;\n\t/**\n\t * The full URL for this request\n\t */\n\turl: string;\n}\n\n/**\n * A function that determines whether the rate limit hit should throw an Error\n */\nexport type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise | boolean;\n\nexport interface APIRequest {\n\t/**\n\t * The data that was used to form the body of this request\n\t */\n\tdata: HandlerRequestData;\n\t/**\n\t * The HTTP method used in this request\n\t */\n\tmethod: string;\n\t/**\n\t * Additional HTTP options for this request\n\t */\n\toptions: RequestOptions;\n\t/**\n\t * The full path used to make the request\n\t */\n\tpath: RouteLike;\n\t/**\n\t * The number of times this request has been attempted\n\t */\n\tretries: number;\n\t/**\n\t * The API route identifying the ratelimit for this request\n\t */\n\troute: string;\n}\n\nexport interface InvalidRequestWarningData {\n\t/**\n\t * Number of invalid requests that have been made in the window\n\t */\n\tcount: number;\n\t/**\n\t * Time in milliseconds remaining before the count resets\n\t */\n\tremainingTime: number;\n}\n\nexport interface RestEvents {\n\thandlerSweep: [sweptHandlers: Collection];\n\thashSweep: [sweptHashes: Collection];\n\tinvalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];\n\tnewListener: [name: string, listener: (...args: any) => void];\n\trateLimited: [rateLimitInfo: RateLimitData];\n\tremoveListener: [name: string, listener: (...args: any) => void];\n\tresponse: [request: APIRequest, response: Dispatcher.ResponseData];\n\trestDebug: [info: string];\n}\n\nexport interface REST {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\nexport type RequestOptions = Exclude[1], undefined>;\n\nexport class REST extends EventEmitter {\n\tpublic readonly cdn: CDN;\n\n\tpublic readonly requestManager: RequestManager;\n\n\tpublic constructor(options: Partial = {}) {\n\t\tsuper();\n\t\tthis.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn);\n\t\tthis.requestManager = new RequestManager(options)\n\t\t\t.on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug))\n\t\t\t.on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited))\n\t\t\t.on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning))\n\t\t\t.on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep));\n\n\t\tthis.on('newListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.on(name, listener);\n\t\t});\n\t\tthis.on('removeListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.off(name, listener);\n\t\t});\n\t}\n\n\t/**\n\t * Gets the agent set for this instance\n\t */\n\tpublic getAgent() {\n\t\treturn this.requestManager.agent;\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this instance\n\t *\n\t * @param agent - Sets the agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.requestManager.setAgent(agent);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.requestManager.setToken(token);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a get request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async get(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Get });\n\t}\n\n\t/**\n\t * Runs a delete request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async delete(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Delete });\n\t}\n\n\t/**\n\t * Runs a post request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async post(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Post });\n\t}\n\n\t/**\n\t * Runs a put request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async put(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Put });\n\t}\n\n\t/**\n\t * Runs a patch request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async patch(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Patch });\n\t}\n\n\t/**\n\t * Runs a request from the api\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async request(options: InternalRequest) {\n\t\tconst response = await this.raw(options);\n\t\treturn parseResponse(response);\n\t}\n\n\t/**\n\t * Runs a request from the API, yielding the raw Response object\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async raw(options: InternalRequest) {\n\t\treturn this.requestManager.queueRequest(options);\n\t}\n}\n","export * from './lib/CDN.js';\nexport * from './lib/errors/DiscordAPIError.js';\nexport * from './lib/errors/HTTPError.js';\nexport * from './lib/errors/RateLimitError.js';\nexport * from './lib/RequestManager.js';\nexport * from './lib/REST.js';\nexport * from './lib/utils/constants.js';\nexport { makeURLSearchParams, parseResponse } from './lib/utils/utils.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.7.1' as string;\n"],"mappings":";;;;AACA,SAAS,WAAW;;;ACDpB,OAAO,aAAa;AACpB,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AAGf,IAAM,mBACZ;AAKM,IAAM,2BAA2B,QAAQ,SAAS,SAAS,SAAS,WAAW,QAAQ,YAA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AA,EAOA,MAAa,QAAQ,SAA0B;AAC9C,UAAM,WAAW,MAAM,KAAK,IAAI,OAAO;AACvC,WAAO,cAAc,QAAQ;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAa,IAAI,SAA0B;AAC1C,WAAO,KAAK,eAAe,aAAa,OAAO;AAAA,EAChD;AACD;AArHa;;;AC/NN,IAAM,UAAU;","names":["RESTEvents","Blob","Buffer","FormData","Buffer","Buffer","sleep","sleep","limit","res","RequestMethod","request","FormData","Buffer","Blob","EventEmitter","EventEmitter"]} \ No newline at end of file diff --git a/node_modules/@discordjs/rest/package.json b/node_modules/@discordjs/rest/package.json index fa7dd68..6f668ae 100644 --- a/node_modules/@discordjs/rest/package.json +++ b/node_modules/@discordjs/rest/package.json @@ -1,14 +1,15 @@ { "name": "@discordjs/rest", - "version": "1.5.0", + "version": "1.7.1", "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": "api-extractor run --local", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", "prepack": "yarn lint && yarn test && yarn build", "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/rest/*'", "release": "cliff-jumper" @@ -17,9 +18,9 @@ "module": "./dist/index.mjs", "typings": "./dist/index.d.ts", "exports": { + "types": "./dist/index.d.ts", "import": "./dist/index.mjs", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" + "require": "./dist/index.js" }, "directories": { "lib": "src", @@ -45,36 +46,37 @@ ], "repository": { "type": "git", - "url": "git+https://github.com/discordjs/discord.js.git" + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/rest" }, "bugs": { "url": "https://github.com/discordjs/discord.js/issues" }, "homepage": "https://discord.js.org", "dependencies": { - "@discordjs/collection": "^1.3.0", - "@discordjs/util": "^0.1.0", + "@discordjs/collection": "^1.5.1", + "@discordjs/util": "^0.3.0", "@sapphire/async-queue": "^1.5.0", - "@sapphire/snowflake": "^3.2.2", - "discord-api-types": "^0.37.23", - "file-type": "^18.0.0", - "tslib": "^2.4.1", - "undici": "^5.13.0" + "@sapphire/snowflake": "^3.4.2", + "discord-api-types": "^0.37.41", + "file-type": "^18.3.0", + "tslib": "^2.5.0", + "undici": "^5.22.0" }, "devDependencies": { - "@favware/cliff-jumper": "^1.9.0", - "@microsoft/api-extractor": "^7.33.6", - "@types/node": "16.18.4", - "@vitest/coverage-c8": "^0.25.3", + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.6", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.30.1", "cross-env": "^7.0.3", - "esbuild-plugin-version-injector": "^1.0.2", - "eslint": "^8.28.0", - "eslint-config-neon": "^0.1.40", - "eslint-formatter-pretty": "^4.1.0", - "prettier": "^2.8.0", - "tsup": "^6.5.0", - "typescript": "^4.9.3", - "vitest": "^0.25.3" + "esbuild-plugin-version-injector": "^1.1.0", + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.42", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsup": "^6.7.0", + "typescript": "^5.0.4", + "vitest": "^0.29.8" }, "engines": { "node": ">=16.9.0" diff --git a/node_modules/@discordjs/util/CHANGELOG.md b/node_modules/@discordjs/util/CHANGELOG.md index ff1b8f5..1f7cb97 100644 --- a/node_modules/@discordjs/util/CHANGELOG.md +++ b/node_modules/@discordjs/util/CHANGELOG.md @@ -2,6 +2,54 @@ All notable changes to this project will be documented in this file. +# [@discordjs/util@0.3.1](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.3.0...@discordjs/util@0.3.1) - (2023-05-01) + +## Refactor + +- **ShardClientUtil:** Logic de-duplication (#9491) ([a9f2bff](https://github.com/discordjs/discord.js/commit/a9f2bff82a18c6a3afdee99e5830e1d7b4da65dc)) + +# [@discordjs/util@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.2.0...@discordjs/util@0.3.0) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/util@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.2.0...@discordjs/util@0.3.0) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/util@0.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.1.0...@discordjs/util@0.2.0) - (2023-03-12) + +## Bug Fixes + +- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4)) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) +- **core:** Implement some ws send events (#8941) ([816aed4](https://github.com/discordjs/discord.js/commit/816aed478e3035060697092d52ad2b58106be0ee)) +- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2)) + # [@discordjs/util@0.1.0](https://github.com/discordjs/discord.js/tree/@discordjs/util@0.1.0) - (2022-10-03) ## Features diff --git a/node_modules/@discordjs/util/README.md b/node_modules/@discordjs/util/README.md index 543c22a..edd628d 100644 --- a/node_modules/@discordjs/util/README.md +++ b/node_modules/@discordjs/util/README.md @@ -13,22 +13,51 @@

+## About + +`@discordjs/util` is a collection of utility functions for use with discord.js. + +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh +npm install @discordjs/util +yarn add @discordjs/util +pnpm add @discordjs/util +``` + ## Links -- [Website](https://discord.js.org/) ([source](https://github.com/discordjs/discord.js/tree/main/packages/website)) -- [Documentation](https://discord.js.org/#/docs) -- [Guide](https://discordjs.guide/) ([source](https://github.com/discordjs/guide)) - See also the [Update Guide](https://discordjs.guide/additional-info/changes-in-v14.html), including updated and removed items in the library. -- [discord.js Discord server](https://discord.gg/djs) -- [Discord API Discord server](https://discord.gg/discord-api) -- [GitHub](https://github.com/discordjs/discord.js/tree/main/packages/scripts) -- [Related libraries](https://discord.com/developers/docs/topics/community-resources#libraries) +- [Website][website] ([source][website-source]) +- [Documentation][documentation] +- [Guide][guide] ([source][guide-source]) + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. +- [discord.js Discord server][discord] +- [Discord API Discord server][discord-api] +- [GitHub][source] +- [npm][npm] +- [Related libraries][related-libs] ## Contributing -See [the contribution guide](https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md) if you'd like to submit a PR. +Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the +[documentation][documentation]. +See [the contribution guide][contributing] if you'd like to submit a PR. ## Help -If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle -nudge in the right direction, please don't hesitate to join our official [discord.js Server](https://discord.gg/djs). +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. + +[website]: https://discord.js.org +[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website +[documentation]: https://discord.js.org/docs/packages/util/stable +[guide]: https://discordjs.guide/ +[guide-source]: https://github.com/discordjs/guide +[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html +[discord]: https://discord.gg/djs +[discord-api]: https://discord.gg/discord-api +[source]: https://github.com/discordjs/discord.js/tree/main/packages/util +[npm]: https://www.npmjs.com/package/@discordjs/util +[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries +[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md diff --git a/node_modules/@discordjs/util/dist/index.d.ts b/node_modules/@discordjs/util/dist/index.d.ts index e12a3ec..13459b5 100644 --- a/node_modules/@discordjs/util/dist/index.d.ts +++ b/node_modules/@discordjs/util/dist/index.d.ts @@ -1,7 +1,7 @@ /** * Represents a type that may or may not be a promise */ -declare type Awaitable = PromiseLike | T; +type Awaitable = PromiseLike | T; /** * Lazy is a wrapper around a value that is computed lazily. It is useful for @@ -18,23 +18,57 @@ declare type Awaitable = PromiseLike | T; declare function lazy(cb: () => T): () => T; /** - * Yields the numbers in the given range as an array + * Options for creating a range + */ +interface RangeOptions { + /** + * The end of the range (exclusive) + */ + end: number; + /** + * The start of the range (inclusive) + */ + start: number; + /** + * The amount to increment by + * + * @defaultValue `1` + */ + step?: number; +} +/** + * A generator to yield numbers in a given range * - * @param start - The start of the range - * @param end - The end of the range (inclusive) - * @param step - The amount to increment between each number + * @remarks + * This method is end-exclusive, for example the last number yielded by `range(5)` is 4. If you + * prefer for the end to be included add 1 to the range or `end` option. + * @param range - A number representing the the range to yield (exclusive) or an object with start, end and step * @example * Basic range * ```ts - * range(3, 5); // [3, 4, 5] + * for (const number of range(5)) { + * console.log(number); + * } + * // Prints 0, 1, 2, 3, 4 * ``` * @example * Range with a step * ```ts - * range(3, 10, 2); // [3, 5, 7, 9] + * for (const number of range({ start: 3, end: 10, step: 2 })) { + * console.log(number); + * } + * // Prints 3, 5, 7, 9 * ``` */ -declare function range(start: number, end: number, step?: number): number[]; +declare function range(range: RangeOptions | number): Generator; + +/** + * Calculates the shard id for a given guild id. + * + * @param guildId - The guild id to calculate the shard id for + * @param shardCount - The total number of shards + */ +declare function calculateShardId(guildId: string, shardCount: number): number; /** * Represents an object capable of representing itself as a JSON object @@ -73,4 +107,4 @@ interface Equatable { */ declare function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable; -export { Awaitable, Equatable, JSONEncodable, isEquatable, isJSONEncodable, lazy, range }; +export { Awaitable, Equatable, JSONEncodable, RangeOptions, calculateShardId, isEquatable, isJSONEncodable, lazy, range }; diff --git a/node_modules/@discordjs/util/dist/index.js b/node_modules/@discordjs/util/dist/index.js index 9078bfd..d4859a1 100644 --- a/node_modules/@discordjs/util/dist/index.js +++ b/node_modules/@discordjs/util/dist/index.js @@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { + calculateShardId: () => calculateShardId, isEquatable: () => isEquatable, isJSONEncodable: () => isJSONEncodable, lazy: () => lazy, @@ -36,11 +37,29 @@ function lazy(cb) { __name(lazy, "lazy"); // src/functions/range.ts -function range(start, end, step = 1) { - return Array.from({ length: (end - start) / step + 1 }, (_, index) => start + index * step); +function* range(range2) { + let rangeEnd; + let start = 0; + let step = 1; + if (typeof range2 === "number") { + rangeEnd = range2; + } else { + start = range2.start; + rangeEnd = range2.end; + step = range2.step ?? 1; + } + for (let index = start; index < rangeEnd; index += step) { + yield index; + } } __name(range, "range"); +// src/functions/calculateShardId.ts +function calculateShardId(guildId, shardCount) { + return Number(BigInt(guildId) >> 22n) % shardCount; +} +__name(calculateShardId, "calculateShardId"); + // src/JSONEncodable.ts function isJSONEncodable(maybeEncodable) { return maybeEncodable !== null && typeof maybeEncodable === "object" && "toJSON" in maybeEncodable; @@ -54,6 +73,7 @@ function isEquatable(maybeEquatable) { __name(isEquatable, "isEquatable"); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { + calculateShardId, isEquatable, isJSONEncodable, lazy, diff --git a/node_modules/@discordjs/util/dist/index.js.map b/node_modules/@discordjs/util/dist/index.js.map index f059cfe..60cab93 100644 --- a/node_modules/@discordjs/util/dist/index.js.map +++ b/node_modules/@discordjs/util/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/functions/lazy.ts","../src/functions/range.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["export * from './types.js';\nexport * from './functions/index.js';\nexport * from './JSONEncodable.js';\nexport * from './Equatable.js';\n","/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Yields the numbers in the given range as an array\n *\n * @param start - The start of the range\n * @param end - The end of the range (inclusive)\n * @param step - The amount to increment between each number\n * @example\n * Basic range\n * ```ts\n * range(3, 5); // [3, 4, 5]\n * ```\n * @example\n * Range with a step\n * ```ts\n * range(3, 10, 2); // [3, 5, 7, 9]\n * ```\n */\nexport function range(start: number, end: number, step = 1): number[] {\n\treturn Array.from({ length: (end - start) / step + 1 }, (_, index) => start + index * step);\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;ACIT,SAAS,MAAM,OAAe,KAAa,OAAO,GAAa;AACrE,SAAO,MAAM,KAAK,EAAE,SAAS,MAAM,SAAS,OAAO,EAAE,GAAG,CAAC,GAAG,UAAU,QAAQ,QAAQ,IAAI;AAC3F;AAFgB;;;ACAT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/functions/lazy.ts","../src/functions/range.ts","../src/functions/calculateShardId.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["export * from './types.js';\nexport * from './functions/index.js';\nexport * from './JSONEncodable.js';\nexport * from './Equatable.js';\n","/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Options for creating a range\n */\nexport interface RangeOptions {\n\t/**\n\t * The end of the range (exclusive)\n\t */\n\tend: number;\n\t/**\n\t * The start of the range (inclusive)\n\t */\n\tstart: number;\n\t/**\n\t * The amount to increment by\n\t *\n\t * @defaultValue `1`\n\t */\n\tstep?: number;\n}\n\n/**\n * A generator to yield numbers in a given range\n *\n * @remarks\n * This method is end-exclusive, for example the last number yielded by `range(5)` is 4. If you\n * prefer for the end to be included add 1 to the range or `end` option.\n * @param range - A number representing the the range to yield (exclusive) or an object with start, end and step\n * @example\n * Basic range\n * ```ts\n * for (const number of range(5)) {\n * console.log(number);\n * }\n * // Prints 0, 1, 2, 3, 4\n * ```\n * @example\n * Range with a step\n * ```ts\n * for (const number of range({ start: 3, end: 10, step: 2 })) {\n * \tconsole.log(number);\n * }\n * // Prints 3, 5, 7, 9\n * ```\n */\nexport function* range(range: RangeOptions | number) {\n\tlet rangeEnd: number;\n\tlet start = 0;\n\tlet step = 1;\n\n\tif (typeof range === 'number') {\n\t\trangeEnd = range;\n\t} else {\n\t\tstart = range.start;\n\t\trangeEnd = range.end;\n\t\tstep = range.step ?? 1;\n\t}\n\n\tfor (let index = start; index < rangeEnd; index += step) {\n\t\tyield index;\n\t}\n}\n","/**\n * Calculates the shard id for a given guild id.\n *\n * @param guildId - The guild id to calculate the shard id for\n * @param shardCount - The total number of shards\n */\nexport function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number(BigInt(guildId) >> 22n) % shardCount;\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;AC+BT,UAAU,MAAMA,QAA8B;AACpD,MAAI;AACJ,MAAI,QAAQ;AACZ,MAAI,OAAO;AAEX,MAAI,OAAOA,WAAU,UAAU;AAC9B,eAAWA;AAAA,EACZ,OAAO;AACN,YAAQA,OAAM;AACd,eAAWA,OAAM;AACjB,WAAOA,OAAM,QAAQ;AAAA,EACtB;AAEA,WAAS,QAAQ,OAAO,QAAQ,UAAU,SAAS,MAAM;AACxD,UAAM;AAAA,EACP;AACD;AAhBiB;;;ACtCV,SAAS,iBAAiB,SAAiB,YAAoB;AACrE,SAAO,OAAO,OAAO,OAAO,KAAK,GAAG,IAAI;AACzC;AAFgB;;;ACWT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":["range"]} \ No newline at end of file diff --git a/node_modules/@discordjs/util/dist/index.mjs b/node_modules/@discordjs/util/dist/index.mjs index 4b56502..2b50e8f 100644 --- a/node_modules/@discordjs/util/dist/index.mjs +++ b/node_modules/@discordjs/util/dist/index.mjs @@ -9,11 +9,29 @@ function lazy(cb) { __name(lazy, "lazy"); // src/functions/range.ts -function range(start, end, step = 1) { - return Array.from({ length: (end - start) / step + 1 }, (_, index) => start + index * step); +function* range(range2) { + let rangeEnd; + let start = 0; + let step = 1; + if (typeof range2 === "number") { + rangeEnd = range2; + } else { + start = range2.start; + rangeEnd = range2.end; + step = range2.step ?? 1; + } + for (let index = start; index < rangeEnd; index += step) { + yield index; + } } __name(range, "range"); +// src/functions/calculateShardId.ts +function calculateShardId(guildId, shardCount) { + return Number(BigInt(guildId) >> 22n) % shardCount; +} +__name(calculateShardId, "calculateShardId"); + // src/JSONEncodable.ts function isJSONEncodable(maybeEncodable) { return maybeEncodable !== null && typeof maybeEncodable === "object" && "toJSON" in maybeEncodable; @@ -26,6 +44,7 @@ function isEquatable(maybeEquatable) { } __name(isEquatable, "isEquatable"); export { + calculateShardId, isEquatable, isJSONEncodable, lazy, diff --git a/node_modules/@discordjs/util/dist/index.mjs.map b/node_modules/@discordjs/util/dist/index.mjs.map index b9081f6..6d73425 100644 --- a/node_modules/@discordjs/util/dist/index.mjs.map +++ b/node_modules/@discordjs/util/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/functions/lazy.ts","../src/functions/range.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Yields the numbers in the given range as an array\n *\n * @param start - The start of the range\n * @param end - The end of the range (inclusive)\n * @param step - The amount to increment between each number\n * @example\n * Basic range\n * ```ts\n * range(3, 5); // [3, 4, 5]\n * ```\n * @example\n * Range with a step\n * ```ts\n * range(3, 10, 2); // [3, 5, 7, 9]\n * ```\n */\nexport function range(start: number, end: number, step = 1): number[] {\n\treturn Array.from({ length: (end - start) / step + 1 }, (_, index) => start + index * step);\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;AAaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;ACIT,SAAS,MAAM,OAAe,KAAa,OAAO,GAAa;AACrE,SAAO,MAAM,KAAK,EAAE,SAAS,MAAM,SAAS,OAAO,EAAE,GAAG,CAAC,GAAG,UAAU,QAAQ,QAAQ,IAAI;AAC3F;AAFgB;;;ACAT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/functions/lazy.ts","../src/functions/range.ts","../src/functions/calculateShardId.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Options for creating a range\n */\nexport interface RangeOptions {\n\t/**\n\t * The end of the range (exclusive)\n\t */\n\tend: number;\n\t/**\n\t * The start of the range (inclusive)\n\t */\n\tstart: number;\n\t/**\n\t * The amount to increment by\n\t *\n\t * @defaultValue `1`\n\t */\n\tstep?: number;\n}\n\n/**\n * A generator to yield numbers in a given range\n *\n * @remarks\n * This method is end-exclusive, for example the last number yielded by `range(5)` is 4. If you\n * prefer for the end to be included add 1 to the range or `end` option.\n * @param range - A number representing the the range to yield (exclusive) or an object with start, end and step\n * @example\n * Basic range\n * ```ts\n * for (const number of range(5)) {\n * console.log(number);\n * }\n * // Prints 0, 1, 2, 3, 4\n * ```\n * @example\n * Range with a step\n * ```ts\n * for (const number of range({ start: 3, end: 10, step: 2 })) {\n * \tconsole.log(number);\n * }\n * // Prints 3, 5, 7, 9\n * ```\n */\nexport function* range(range: RangeOptions | number) {\n\tlet rangeEnd: number;\n\tlet start = 0;\n\tlet step = 1;\n\n\tif (typeof range === 'number') {\n\t\trangeEnd = range;\n\t} else {\n\t\tstart = range.start;\n\t\trangeEnd = range.end;\n\t\tstep = range.step ?? 1;\n\t}\n\n\tfor (let index = start; index < rangeEnd; index += step) {\n\t\tyield index;\n\t}\n}\n","/**\n * Calculates the shard id for a given guild id.\n *\n * @param guildId - The guild id to calculate the shard id for\n * @param shardCount - The total number of shards\n */\nexport function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number(BigInt(guildId) >> 22n) % shardCount;\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;AAaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;AC+BT,UAAU,MAAMA,QAA8B;AACpD,MAAI;AACJ,MAAI,QAAQ;AACZ,MAAI,OAAO;AAEX,MAAI,OAAOA,WAAU,UAAU;AAC9B,eAAWA;AAAA,EACZ,OAAO;AACN,YAAQA,OAAM;AACd,eAAWA,OAAM;AACjB,WAAOA,OAAM,QAAQ;AAAA,EACtB;AAEA,WAAS,QAAQ,OAAO,QAAQ,UAAU,SAAS,MAAM;AACxD,UAAM;AAAA,EACP;AACD;AAhBiB;;;ACtCV,SAAS,iBAAiB,SAAiB,YAAoB;AACrE,SAAO,OAAO,OAAO,OAAO,KAAK,GAAG,IAAI;AACzC;AAFgB;;;ACWT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":["range"]} \ No newline at end of file diff --git a/node_modules/@discordjs/util/package.json b/node_modules/@discordjs/util/package.json index b37ddab..aae4201 100644 --- a/node_modules/@discordjs/util/package.json +++ b/node_modules/@discordjs/util/package.json @@ -1,14 +1,15 @@ { "name": "@discordjs/util", - "version": "0.1.0", + "version": "0.3.1", "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": "prettier --write . && TIMING=1 eslint src --ext mjs,js,ts --fix", + "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": "downlevel-dts dist docs/dist --to=3.7 && api-extractor run --local", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", "prepack": "yarn lint && yarn test && yarn build", "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/util/*'", "release": "cliff-jumper" @@ -17,9 +18,9 @@ "module": "./dist/index.mjs", "types": "./dist/index.d.ts", "exports": { + "types": "./dist/index.d.ts", "import": "./dist/index.mjs", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" + "require": "./dist/index.js" }, "directories": { "lib": "src" @@ -44,26 +45,27 @@ ], "repository": { "type": "git", - "url": "https://github.com/discordjs/discord.js.git" + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/util" }, "bugs": { "url": "https://github.com/discordjs/discord.js/issues" }, "homepage": "https://discord.js.org", "devDependencies": { - "@favware/cliff-jumper": "^1.8.8", - "@microsoft/api-extractor": "^7.32.0", - "@types/node": "^16.11.56", - "@vitest/coverage-c8": "^0.22.1", + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.6", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.30.1", "cross-env": "^7.0.3", - "downlevel-dts": "^0.10.1", - "eslint": "^8.23.0", - "eslint-config-neon": "^0.1.31", - "prettier": "^2.7.1", - "tsd": "^0.23.0", - "tsup": "^6.2.3", - "typescript": "^4.8.2", - "vitest": "^0.22.1" + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.42", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsd": "^0.28.1", + "tsup": "^6.7.0", + "typescript": "^5.0.4", + "vitest": "^0.29.8" }, "engines": { "node": ">=16.9.0" diff --git a/node_modules/@discordjs/ws/CHANGELOG.md b/node_modules/@discordjs/ws/CHANGELOG.md new file mode 100644 index 0000000..4432009 --- /dev/null +++ b/node_modules/@discordjs/ws/CHANGELOG.md @@ -0,0 +1,193 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@discordjs/ws@0.8.3](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.2...@discordjs/ws@0.8.3) - (2023-05-06) + +## Bug Fixes + +- **WebSocketShard:** Wait a little before reconnecting (#9517) ([00da44a](https://github.com/discordjs/discord.js/commit/00da44a120fb0eeb2bdc3a03670836a544dc5418)) + +## Testing + +- **ws:** Fix tests (#9520) ([3e80f0b](https://github.com/discordjs/discord.js/commit/3e80f0b384ea2dc14c1b60b5897e90040cab9a24)) + +# [@discordjs/ws@0.8.2](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.1...@discordjs/ws@0.8.2) - (2023-05-01) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +# [@discordjs/ws@0.8.1](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.0...@discordjs/ws@0.8.1) - (2023-04-16) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Refactor + +- Abstract identify throttling and correct max_concurrency handling (#9375) ([02dfaf1](https://github.com/discordjs/discord.js/commit/02dfaf1aa2c798315d0dd7f809cc469771b36ffc)) +- **WebSocketShard:** WaitForEvent and its error handling (#9282) ([dcf58d8](https://github.com/discordjs/discord.js/commit/dcf58d81401387a5e157b20829aa56638e106e9d)) + +# [@discordjs/ws@0.8.2](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.1...@discordjs/ws@0.8.2) - (2023-05-01) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +# [@discordjs/ws@0.8.1](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.0...@discordjs/ws@0.8.1) - (2023-04-16) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Refactor + +- Abstract identify throttling and correct max_concurrency handling (#9375) ([02dfaf1](https://github.com/discordjs/discord.js/commit/02dfaf1aa2c798315d0dd7f809cc469771b36ffc)) +- **WebSocketShard:** WaitForEvent and its error handling (#9282) ([dcf58d8](https://github.com/discordjs/discord.js/commit/dcf58d81401387a5e157b20829aa56638e106e9d)) + +# [@discordjs/ws@0.8.1](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.0...@discordjs/ws@0.8.1) - (2023-04-16) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Refactor + +- Abstract identify throttling and correct max_concurrency handling (#9375) ([02dfaf1](https://github.com/discordjs/discord.js/commit/02dfaf1aa2c798315d0dd7f809cc469771b36ffc)) +- **WebSocketShard:** WaitForEvent and its error handling (#9282) ([dcf58d8](https://github.com/discordjs/discord.js/commit/dcf58d81401387a5e157b20829aa56638e106e9d)) + +# [@discordjs/ws@0.8.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.7.0...@discordjs/ws@0.8.0) - (2023-04-01) + +## Bug Fixes + +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) +- **WebSocketShard:** Don't await #destroy in error bubbling logic (#9276) ([519825a](https://github.com/discordjs/discord.js/commit/519825a651fe22042a73046824d12f03f56ca9e2)) +- **WebSocketShard:** Don't close in #destroy when status is connecting (#9254) ([c76b17d](https://github.com/discordjs/discord.js/commit/c76b17d3b327fb55ef76770d4825e02ab8f26ad1)) +- **WebSocketShard:** Cancel initial heartbeat in destroy (#9244) ([9842082](https://github.com/discordjs/discord.js/commit/98420826bc2296fc392f17e8254cf4ad743ff5af)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/ws@0.7.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.6.0...@discordjs/ws@0.7.0) - (2023-03-12) + +## Bug Fixes + +- **WebSocketShard:** #send race condition due to ready state (#9226) ([a99fc64](https://github.com/discordjs/discord.js/commit/a99fc64e3f73c3976617a7ed825fa7d6e9fb3b53)) +- **WebSocketShard:** Wait for hello rather than ready in connect (#9178) ([27e0b32](https://github.com/discordjs/discord.js/commit/27e0b32c5f0fe605f152e6ba67ce3f596137ff01)) +- **WebSocketShard:** Proper error bubbling (#9119) ([9681f34](https://github.com/discordjs/discord.js/commit/9681f348770b0e2ff9b7c96b1c30575dd950e2ed)) +- Ws typo (#9056) ([05a1cbf](https://github.com/discordjs/discord.js/commit/05a1cbfe5479195b0bc9b6f0971fe39f6af6fd77)) + +## 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)) +- Updated @discordjs/ws README.md to include optional packages (#8973) ([4ee00b6](https://github.com/discordjs/discord.js/commit/4ee00b6534fad39da1fe54fb2c1766b264a020ca)) + +## Features + +- **WebSocketShard:** Heartbeat jitter (#9223) ([6ecff26](https://github.com/discordjs/discord.js/commit/6ecff26ec65ce1d559a3406b396b3190868b1961)) +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) +- **ws:** Custom workers (#9004) ([828a13b](https://github.com/discordjs/discord.js/commit/828a13b526dde1334e8879e76e664584bdb5db73)) +- **ws:** Metrics (#9005) ([0ff67d8](https://github.com/discordjs/discord.js/commit/0ff67d8e7adee43ff82bbf072dac9a4c7c9fe8c2)) + +## Refactor + +- **WebSocketManager:** Passing in strategy (#9122) ([5c5a583](https://github.com/discordjs/discord.js/commit/5c5a5832b94cd4d371cc99c4f9c3384523dabeeb)) + +## Styling + +- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b)) + +# [@discordjs/ws@0.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.5.0...@discordjs/ws@0.6.0) - (2022-12-16) + +## Bug Fixes + +- **WebSocketShard:** Send ratelimit handling (#8887) ([40b504a](https://github.com/discordjs/discord.js/commit/40b504a2088effc6a467f40ac3cf2a6d736ab209)) + +## Features + +- **core:** Add support for role connections (#8930) ([3d6fa24](https://github.com/discordjs/discord.js/commit/3d6fa248c07b2278504bbe8bafa17a3294971fd9)) + +## Refactor + +- **WebSocketShard:** Identify throttling (#8888) ([8f552a0](https://github.com/discordjs/discord.js/commit/8f552a0e17c0eca71063e7a4353b9b351bcdf9fd)) + +# [@discordjs/ws@0.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.4.1...@discordjs/ws@0.5.0) - (2022-11-28) + +## Bug Fixes + +- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4)) + +## Documentation + +- Remove unused imports (#8744) ([179392d](https://github.com/discordjs/discord.js/commit/179392d6d7d634c6d10f6abb20c072516c1c1d43)) + +## Features + +- New select menus (#8793) ([5152abf](https://github.com/discordjs/discord.js/commit/5152abf7285581abf7689e9050fdc56c4abb1e2b)) + +# [@discordjs/ws@0.4.1](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.4.0...@discordjs/ws@0.4.1) - (2022-10-10) + +## Bug Fixes + +- **WebSocketShard:** Dispatch race condition (#8731) ([c2b6777](https://github.com/discordjs/discord.js/commit/c2b677759b905d6eb3ebcefcec2cb04eb38436bb)) + +# [@discordjs/ws@0.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.3.0...@discordjs/ws@0.4.0) - (2022-10-08) + +## Bug Fixes + +- Ws package.json path (#8720) ([7af3c3b](https://github.com/discordjs/discord.js/commit/7af3c3b6f1517a5d14372b5aa0ef3a2ed8633f6f)) +- **WebSocketShard:** Add ready data parameter to ready event (#8705) ([a7eab50](https://github.com/discordjs/discord.js/commit/a7eab50ee3e286ca10e37107d695385251bd044d)) +- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9)) + +## Documentation + +- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0)) + +## Features + +- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2)) +- Add `@discordjs/util` (#8591) ([b2ec865](https://github.com/discordjs/discord.js/commit/b2ec865765bf94181473864a627fb63ea8173fd3)) + +## 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/ws@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.2.0...@discordjs/ws@0.3.0) - (2022-08-22) + +## Bug Fixes + +- **WebSocketShard#destroy:** Wait for close and cleanup listeners (#8479) ([acdafe6](https://github.com/discordjs/discord.js/commit/acdafe60c7aa1ac5a3d358934c055c297080a944)) +- **WebSocketManager#connect:** Check if we have enough sessions (#8481) ([4fd4252](https://github.com/discordjs/discord.js/commit/4fd42528fea6127e6468a651f9544913c19ade4d)) +- **WebSocketShard:** Always reconnect on disconnected with 1000 (#8405) ([359f688](https://github.com/discordjs/discord.js/commit/359f6885558fcfb3151971ab589077a89ee71a01)) +- **WebSocketShard:** Emit errors directly instead of objects (#8406) ([3161e1a](https://github.com/discordjs/discord.js/commit/3161e1a1acfbf929ecf33958fa1657553dd9bc1e)) + +## Documentation + +- Fence examples in codeblocks ([193b252](https://github.com/discordjs/discord.js/commit/193b252672440a860318d3c2968aedd9cb88e0ce)) + +## 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)) +- **website:** Render tsdoc examples (#8494) ([7116647](https://github.com/discordjs/discord.js/commit/7116647947e413da59fbf493ed5251ddcd710ce7)) +- **WebSocketShard:** Support new resume url (#8480) ([bc06cc6](https://github.com/discordjs/discord.js/commit/bc06cc638d2f57ab5c600e8cdb6afc8eb2180166)) + +## 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/ws@0.2.0](https://github.com/discordjs/discord.js/tree/@discordjs/ws@0.2.0) - (2022-07-30) + +## Bug Fixes + +- **WebSocketShard:** Account code 1000 with no prior indication (#8399) ([5137bfc](https://github.com/discordjs/discord.js/commit/5137bfc17d763488083b76ee9008611df333272a)) +- **WebSocketShard:** Use correct import (#8357) ([78d4295](https://github.com/discordjs/discord.js/commit/78d4295a40b83ea4f7cc830ff81927cba2d1d3f0)) + +## Features + +- @discordjs/ws (#8260) ([748d727](https://github.com/discordjs/discord.js/commit/748d7271c45796479a29d8ed3101421de09ef867)) diff --git a/node_modules/@discordjs/ws/LICENSE b/node_modules/@discordjs/ws/LICENSE new file mode 100644 index 0000000..f9786ff --- /dev/null +++ b/node_modules/@discordjs/ws/LICENSE @@ -0,0 +1,191 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2022 Noel Buechler + Copyright 2022 Charlotte Cristea + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@discordjs/ws/README.md b/node_modules/@discordjs/ws/README.md new file mode 100644 index 0000000..b51e75c --- /dev/null +++ b/node_modules/@discordjs/ws/README.md @@ -0,0 +1,196 @@ +
+
+

+ discord.js +

+
+

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

+

+ Vercel + Cloudflare Workers +

+
+ +## About + +`@discordjs/ws` is a powerful wrapper around Discord's gateway. + +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh +npm install @discordjs/ws +yarn add @discordjs/ws +pnpm add @discordjs/ws +``` + +### Optional packages + +- [zlib-sync](https://www.npmjs.com/package/zlib-sync) for WebSocket data compression and inflation (`npm install zlib-sync`) +- [bufferutil](https://www.npmjs.com/package/bufferutil) for a much faster WebSocket connection (`npm install bufferutil`) +- [utf-8-validate](https://www.npmjs.com/package/utf-8-validate) in combination with `bufferutil` for much faster WebSocket processing (`npm install utf-8-validate`) + +## Example usage + +```ts +import { WebSocketManager, WebSocketShardEvents, CompressionMethod } from '@discordjs/ws'; +import { REST } from '@discordjs/rest'; + +const rest = new REST().setToken(process.env.DISCORD_TOKEN); +// This example will spawn Discord's recommended shard count, all under the current process. +const manager = new WebSocketManager({ + token: process.env.DISCORD_TOKEN, + intents: 0, // for no intents + rest, + // uncomment if you have zlib-sync installed and want to use compression + // compression: CompressionMethod.ZlibStream, +}); + +manager.on(WebSocketShardEvents.Dispatch, (event) => { + // Process gateway events here. +}); + +await manager.connect(); +``` + +### Specify shards + +```ts +// Spawn 4 shards +const manager = new WebSocketManager({ + token: process.env.DISCORD_TOKEN, + intents: 0, + rest, + shardCount: 4, +}); + +// The manager also supports being responsible for only a subset of your shards: + +// Your bot will run 8 shards overall +// This manager will only take care of 0, 2, 4, and 6 +const manager = new WebSocketManager({ + token: process.env.DISCORD_TOKEN, + intents: 0, + rest, + shardCount: 8, + shardIds: [0, 2, 4, 6], +}); + +// Alternatively, if your shards are consecutive, you can pass in a range +const manager = new WebSocketManager({ + token: process.env.DISCORD_TOKEN, + intents: 0, + rest, + shardCount: 8, + shardIds: { + start: 0, + end: 4, + }, +}); +``` + +### Specify `worker_threads` + +You can also have the shards spawn in worker threads: + +```ts +import { WebSocketManager, WorkerShardingStrategy } from '@discordjs/ws'; +import { REST } from '@discordjs/rest'; + +const rest = new REST().setToken(process.env.DISCORD_TOKEN); +const manager = new WebSocketManager({ + token: process.env.DISCORD_TOKEN, + intents: 0, + rest, + shardCount: 6, + // This will cause 3 workers to spawn, 2 shards per each + buildStrategy: (manager) => new WorkerShardingStrategy(manager, { shardsPerWorker: 2 }), + // Or maybe you want all your shards under a single worker + buildStrategy: (manager) => new WorkerShardingStrategy(manager, { shardsPerWorker: 'all' }), +}); +``` + +**Note**: By default, this will cause the workers to effectively only be responsible for the WebSocket connection, they simply pass up all the events back to the main process for the manager to emit. If you want to have the workers handle events as well, you can pass in a `workerPath` option to the `WorkerShardingStrategy` constructor: + +```ts +import { WebSocketManager, WorkerShardingStrategy } from '@discordjs/ws'; +import { REST } from '@discordjs/rest'; + +const rest = new REST().setToken(process.env.DISCORD_TOKEN); +const manager = new WebSocketManager({ + token: process.env.DISCORD_TOKEN, + intents: 0, + rest, + buildStrategy: (manager) => + new WorkerShardingStrategy(manager, { + shardsPerWorker: 2, + workerPath: './worker.js', + }), +}); +``` + +And your `worker.ts` file: + +```ts +import { WorkerBootstrapper, WebSocketShardEvents } from '@discordjs/ws'; + +const bootstrapper = new WorkerBootstrapper(); +void bootstrapper.bootstrap({ + // Those will be sent to the main thread for the manager to emit + forwardEvents: [ + WebSocketShardEvents.Closed, + WebSocketShardEvents.Debug, + WebSocketShardEvents.Hello, + WebSocketShardEvents.Ready, + WebSocketShardEvents.Resumed, + ], + shardCallback: (shard) => { + shard.on(WebSocketShardEvents.Dispatch, (event) => { + // Process gateway events here however you want (e.g. send them through a message broker) + // You also have access to shard.id if you need it + }); + }, +}); +``` + +## Links + +- [Website][website] ([source][website-source]) +- [Documentation][documentation] +- [Guide][guide] ([source][guide-source]) + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. +- [discord.js Discord server][discord] +- [Discord API Discord server][discord-api] +- [GitHub][source] +- [npm][npm] +- [Related libraries][related-libs] + +## Contributing + +Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the +[documentation][documentation]. +See [the contribution guide][contributing] if you'd like to submit a PR. + +## Help + +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. + +[website]: https://discord.js.org +[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website +[documentation]: https://discord.js.org/docs/packages/ws/stable +[guide]: https://discordjs.guide/ +[guide-source]: https://github.com/discordjs/guide +[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html +[discord]: https://discord.gg/djs +[discord-api]: https://discord.gg/discord-api +[source]: https://github.com/discordjs/discord.js/tree/main/packages/ws +[npm]: https://www.npmjs.com/package/@discordjs/ws +[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries +[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md diff --git a/node_modules/@discordjs/ws/dist/defaultWorker.d.ts b/node_modules/@discordjs/ws/dist/defaultWorker.d.ts new file mode 100644 index 0000000..c9247d4 --- /dev/null +++ b/node_modules/@discordjs/ws/dist/defaultWorker.d.ts @@ -0,0 +1,2 @@ + +export { } diff --git a/node_modules/@discordjs/ws/dist/defaultWorker.js b/node_modules/@discordjs/ws/dist/defaultWorker.js new file mode 100644 index 0000000..8781558 --- /dev/null +++ b/node_modules/@discordjs/ws/dist/defaultWorker.js @@ -0,0 +1,982 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/utils/WorkerBootstrapper.ts +var import_node_worker_threads3 = require("worker_threads"); +var import_collection7 = require("@discordjs/collection"); + +// src/strategies/context/WorkerContextFetchingStrategy.ts +var import_node_worker_threads2 = require("worker_threads"); +var import_collection2 = require("@discordjs/collection"); + +// src/strategies/sharding/WorkerShardingStrategy.ts +var import_node_events = require("events"); +var import_node_path = require("path"); +var import_node_worker_threads = require("worker_threads"); +var import_collection = require("@discordjs/collection"); + +// src/strategies/context/IContextFetchingStrategy.ts +async function managerToFetchingStrategyOptions(manager) { + const { + buildIdentifyThrottler, + buildStrategy, + retrieveSessionInfo, + updateSessionInfo, + shardCount, + shardIds, + rest, + ...managerOptions + } = manager.options; + return { + ...managerOptions, + gatewayInformation: await manager.fetchGatewayInformation(), + shardCount: await manager.getShardCount() + }; +} +__name(managerToFetchingStrategyOptions, "managerToFetchingStrategyOptions"); + +// src/strategies/context/WorkerContextFetchingStrategy.ts +var WorkerContextFetchingStrategy = class { + constructor(options) { + this.options = options; + if (import_node_worker_threads2.isMainThread) { + throw new Error("Cannot instantiate WorkerContextFetchingStrategy on the main thread"); + } + import_node_worker_threads2.parentPort.on("message", (payload) => { + if (payload.op === 3 /* SessionInfoResponse */) { + this.sessionPromises.get(payload.nonce)?.(payload.session); + this.sessionPromises.delete(payload.nonce); + } + if (payload.op === 4 /* ShardIdentifyResponse */) { + const promise = this.waitForIdentifyPromises.get(payload.nonce); + if (payload.ok) { + promise?.resolve(); + } else { + promise?.reject(); + } + this.waitForIdentifyPromises.delete(payload.nonce); + } + }); + } + sessionPromises = new import_collection2.Collection(); + waitForIdentifyPromises = new import_collection2.Collection(); + async retrieveSessionInfo(shardId) { + const nonce = Math.random(); + const payload = { + op: 3 /* RetrieveSessionInfo */, + shardId, + nonce + }; + const promise = new Promise((resolve2) => this.sessionPromises.set(nonce, resolve2)); + import_node_worker_threads2.parentPort.postMessage(payload); + return promise; + } + updateSessionInfo(shardId, sessionInfo) { + const payload = { + op: 4 /* UpdateSessionInfo */, + shardId, + session: sessionInfo + }; + import_node_worker_threads2.parentPort.postMessage(payload); + } + async waitForIdentify(shardId, signal) { + const nonce = Math.random(); + const payload = { + op: 5 /* WaitForIdentify */, + nonce, + shardId + }; + const promise = new Promise( + (resolve2, reject) => ( + // eslint-disable-next-line no-promise-executor-return + this.waitForIdentifyPromises.set(nonce, { resolve: resolve2, reject }) + ) + ); + import_node_worker_threads2.parentPort.postMessage(payload); + const listener = /* @__PURE__ */ __name(() => { + const payload2 = { + op: 8 /* CancelIdentify */, + nonce + }; + import_node_worker_threads2.parentPort.postMessage(payload2); + }, "listener"); + signal.addEventListener("abort", listener); + try { + await promise; + } finally { + signal.removeEventListener("abort", listener); + } + } +}; +__name(WorkerContextFetchingStrategy, "WorkerContextFetchingStrategy"); + +// src/ws/WebSocketShard.ts +var import_node_buffer = require("buffer"); +var import_node_events2 = require("events"); +var import_node_timers = require("timers"); +var import_promises2 = require("timers/promises"); +var import_node_url = require("url"); +var import_node_util = require("util"); +var import_node_zlib = require("zlib"); +var import_collection6 = require("@discordjs/collection"); +var import_util2 = require("@discordjs/util"); +var import_async_queue2 = require("@sapphire/async-queue"); +var import_async_event_emitter = require("@vladfrangu/async_event_emitter"); +var import_v102 = require("discord-api-types/v10"); +var import_ws = require("ws"); + +// src/utils/constants.ts +var import_node_process = __toESM(require("process")); +var import_collection5 = require("@discordjs/collection"); +var import_util = require("@discordjs/util"); +var import_v10 = require("discord-api-types/v10"); + +// src/strategies/sharding/SimpleShardingStrategy.ts +var import_collection3 = require("@discordjs/collection"); + +// src/strategies/context/SimpleContextFetchingStrategy.ts +var _SimpleContextFetchingStrategy = class { + constructor(manager, options) { + this.manager = manager; + this.options = options; + } + static async ensureThrottler(manager) { + const throttler = _SimpleContextFetchingStrategy.throttlerCache.get(manager); + if (throttler) { + return throttler; + } + const newThrottler = await manager.options.buildIdentifyThrottler(manager); + _SimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler); + return newThrottler; + } + async retrieveSessionInfo(shardId) { + return this.manager.options.retrieveSessionInfo(shardId); + } + updateSessionInfo(shardId, sessionInfo) { + return this.manager.options.updateSessionInfo(shardId, sessionInfo); + } + async waitForIdentify(shardId, signal) { + const throttler = await _SimpleContextFetchingStrategy.ensureThrottler(this.manager); + await throttler.waitForIdentify(shardId, signal); + } +}; +var SimpleContextFetchingStrategy = _SimpleContextFetchingStrategy; +__name(SimpleContextFetchingStrategy, "SimpleContextFetchingStrategy"); +// This strategy assumes every shard is running under the same process - therefore we need a single +// IdentifyThrottler per manager. +__publicField(SimpleContextFetchingStrategy, "throttlerCache", /* @__PURE__ */ new WeakMap()); + +// src/strategies/sharding/SimpleShardingStrategy.ts +var SimpleShardingStrategy = class { + manager; + shards = new import_collection3.Collection(); + constructor(manager) { + this.manager = manager; + } + /** + * {@inheritDoc IShardingStrategy.spawn} + */ + async spawn(shardIds) { + const strategyOptions = await managerToFetchingStrategyOptions(this.manager); + for (const shardId of shardIds) { + const strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions); + const shard = new WebSocketShard(strategy, shardId); + for (const event of Object.values(WebSocketShardEvents)) { + shard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId })); + } + this.shards.set(shardId, shard); + } + } + /** + * {@inheritDoc IShardingStrategy.connect} + */ + async connect() { + const promises = []; + for (const shard of this.shards.values()) { + promises.push(shard.connect()); + } + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.destroy} + */ + async destroy(options) { + const promises = []; + for (const shard of this.shards.values()) { + promises.push(shard.destroy(options)); + } + await Promise.all(promises); + this.shards.clear(); + } + /** + * {@inheritDoc IShardingStrategy.send} + */ + async send(shardId, payload) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} not found`); + } + return shard.send(payload); + } + /** + * {@inheritDoc IShardingStrategy.fetchStatus} + */ + async fetchStatus() { + return this.shards.mapValues((shard) => shard.status); + } +}; +__name(SimpleShardingStrategy, "SimpleShardingStrategy"); + +// src/throttling/SimpleIdentifyThrottler.ts +var import_promises = require("timers/promises"); +var import_collection4 = require("@discordjs/collection"); +var import_async_queue = require("@sapphire/async-queue"); +var SimpleIdentifyThrottler = class { + constructor(maxConcurrency) { + this.maxConcurrency = maxConcurrency; + } + states = new import_collection4.Collection(); + /** + * {@inheritDoc IIdentifyThrottler.waitForIdentify} + */ + async waitForIdentify(shardId, signal) { + const key = shardId % this.maxConcurrency; + const state = this.states.ensure(key, () => { + return { + queue: new import_async_queue.AsyncQueue(), + resetsAt: Number.POSITIVE_INFINITY + }; + }); + await state.queue.wait({ signal }); + try { + const diff = state.resetsAt - Date.now(); + if (diff <= 5e3) { + const time = diff + Math.random() * 1500; + await (0, import_promises.setTimeout)(time); + } + state.resetsAt = Date.now() + 5e3; + } finally { + state.queue.shift(); + } + } +}; +__name(SimpleIdentifyThrottler, "SimpleIdentifyThrottler"); + +// src/utils/constants.ts +var DefaultDeviceProperty = `@discordjs/ws 0.8.3`; +var getDefaultSessionStore = (0, import_util.lazy)(() => new import_collection5.Collection()); +var DefaultWebSocketManagerOptions = { + async buildIdentifyThrottler(manager) { + const info = await manager.fetchGatewayInformation(); + return new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency); + }, + buildStrategy: (manager) => new SimpleShardingStrategy(manager), + shardCount: null, + shardIds: null, + largeThreshold: null, + initialPresence: null, + identifyProperties: { + browser: DefaultDeviceProperty, + device: DefaultDeviceProperty, + os: import_node_process.default.platform + }, + version: import_v10.APIVersion, + encoding: "json" /* JSON */, + compression: null, + retrieveSessionInfo(shardId) { + const store = getDefaultSessionStore(); + return store.get(shardId) ?? null; + }, + updateSessionInfo(shardId, info) { + const store = getDefaultSessionStore(); + if (info) { + store.set(shardId, info); + } else { + store.delete(shardId); + } + }, + handshakeTimeout: 3e4, + helloTimeout: 6e4, + readyTimeout: 15e3 +}; +var ImportantGatewayOpcodes = /* @__PURE__ */ new Set([ + import_v10.GatewayOpcodes.Heartbeat, + import_v10.GatewayOpcodes.Identify, + import_v10.GatewayOpcodes.Resume +]); +function getInitialSendRateLimitState() { + return { + remaining: 120, + resetAt: Date.now() + 6e4 + }; +} +__name(getInitialSendRateLimitState, "getInitialSendRateLimitState"); + +// src/ws/WebSocketShard.ts +var getZlibSync = (0, import_util2.lazy)(async () => import("zlib-sync").then((mod) => mod.default).catch(() => null)); +var WebSocketShardEvents = /* @__PURE__ */ ((WebSocketShardEvents2) => { + WebSocketShardEvents2["Closed"] = "closed"; + WebSocketShardEvents2["Debug"] = "debug"; + WebSocketShardEvents2["Dispatch"] = "dispatch"; + WebSocketShardEvents2["Error"] = "error"; + WebSocketShardEvents2["HeartbeatComplete"] = "heartbeat"; + WebSocketShardEvents2["Hello"] = "hello"; + WebSocketShardEvents2["Ready"] = "ready"; + WebSocketShardEvents2["Resumed"] = "resumed"; + return WebSocketShardEvents2; +})(WebSocketShardEvents || {}); +var WebSocketShardDestroyRecovery = /* @__PURE__ */ ((WebSocketShardDestroyRecovery2) => { + WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Reconnect"] = 0] = "Reconnect"; + WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Resume"] = 1] = "Resume"; + return WebSocketShardDestroyRecovery2; +})(WebSocketShardDestroyRecovery || {}); +var WebSocketShard = class extends import_async_event_emitter.AsyncEventEmitter { + connection = null; + useIdentifyCompress = false; + inflate = null; + textDecoder = new import_node_util.TextDecoder(); + replayedEvents = 0; + isAck = true; + sendRateLimitState = getInitialSendRateLimitState(); + initialHeartbeatTimeoutController = null; + heartbeatInterval = null; + lastHeartbeatAt = -1; + // Indicates whether the shard has already resolved its original connect() call + initialConnectResolved = false; + // Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET) + failedToConnectDueToNetworkError = false; + sendQueue = new import_async_queue2.AsyncQueue(); + timeoutAbortControllers = new import_collection6.Collection(); + strategy; + id; + #status = 0 /* Idle */; + get status() { + return this.#status; + } + constructor(strategy, id) { + super(); + this.strategy = strategy; + this.id = id; + } + async connect() { + const promise = this.initialConnectResolved ? Promise.resolve() : (0, import_node_events2.once)(this, "ready" /* Ready */); + void this.internalConnect(); + await promise; + this.initialConnectResolved = true; + } + async internalConnect() { + if (this.#status !== 0 /* Idle */) { + throw new Error("Tried to connect a shard that wasn't idle"); + } + const { version, encoding, compression } = this.strategy.options; + const params = new import_node_url.URLSearchParams({ v: version, encoding }); + if (compression) { + const zlib = await getZlibSync(); + if (zlib) { + params.append("compress", compression); + this.inflate = new zlib.Inflate({ + chunkSize: 65535, + to: "string" + }); + } else if (!this.useIdentifyCompress) { + this.useIdentifyCompress = true; + console.warn( + "WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress" + ); + } + } + const session = await this.strategy.retrieveSessionInfo(this.id); + const url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`; + this.debug([`Connecting to ${url}`]); + const connection = new import_ws.WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? void 0 }).on("message", this.onMessage.bind(this)).on("error", this.onError.bind(this)).on("close", this.onClose.bind(this)); + connection.binaryType = "arraybuffer"; + this.connection = connection; + this.#status = 1 /* Connecting */; + this.sendRateLimitState = getInitialSendRateLimitState(); + const { ok } = await this.waitForEvent("hello" /* Hello */, this.strategy.options.helloTimeout); + if (!ok) { + return; + } + if (session?.shardCount === this.strategy.options.shardCount) { + await this.resume(session); + } else { + await this.identify(); + } + } + async destroy(options = {}) { + if (this.#status === 0 /* Idle */) { + this.debug(["Tried to destroy a shard that was idle"]); + return; + } + if (!options.code) { + options.code = options.recover === 1 /* Resume */ ? 4200 /* Resuming */ : 1e3 /* Normal */; + } + this.debug([ + "Destroying shard", + `Reason: ${options.reason ?? "none"}`, + `Code: ${options.code}`, + `Recover: ${options.recover === void 0 ? "none" : WebSocketShardDestroyRecovery[options.recover]}` + ]); + this.isAck = true; + if (this.heartbeatInterval) { + (0, import_node_timers.clearInterval)(this.heartbeatInterval); + } + if (this.initialHeartbeatTimeoutController) { + this.initialHeartbeatTimeoutController.abort(); + this.initialHeartbeatTimeoutController = null; + } + this.lastHeartbeatAt = -1; + for (const controller of this.timeoutAbortControllers.values()) { + controller.abort(); + } + this.timeoutAbortControllers.clear(); + this.failedToConnectDueToNetworkError = false; + if (options.recover !== 1 /* Resume */) { + await this.strategy.updateSessionInfo(this.id, null); + } + if (this.connection) { + this.connection.removeAllListeners("message"); + this.connection.removeAllListeners("close"); + const shouldClose = this.connection.readyState === import_ws.WebSocket.OPEN; + this.debug([ + "Connection status during destroy", + `Needs closing: ${shouldClose}`, + `Ready state: ${this.connection.readyState}` + ]); + if (shouldClose) { + this.connection.close(options.code, options.reason); + await (0, import_node_events2.once)(this.connection, "close"); + this.emit("closed" /* Closed */, { code: options.code }); + } + this.connection.removeAllListeners("error"); + } else { + this.debug(["Destroying a shard that has no connection; please open an issue on GitHub"]); + } + this.#status = 0 /* Idle */; + if (options.recover !== void 0) { + await (0, import_promises2.setTimeout)(500); + return this.internalConnect(); + } + } + async waitForEvent(event, timeoutDuration) { + this.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : "indefinitely"}`]); + const timeoutController = new AbortController(); + const timeout = timeoutDuration ? (0, import_node_timers.setTimeout)(() => timeoutController.abort(), timeoutDuration).unref() : null; + this.timeoutAbortControllers.set(event, timeoutController); + const closeController = new AbortController(); + try { + const closed = await Promise.race([ + (0, import_node_events2.once)(this, event, { signal: timeoutController.signal }).then(() => false), + (0, import_node_events2.once)(this, "closed" /* Closed */, { signal: closeController.signal }).then(() => true) + ]); + return { ok: !closed }; + } catch { + void this.destroy({ + code: 1e3 /* Normal */, + reason: "Something timed out or went wrong while waiting for an event", + recover: 0 /* Reconnect */ + }); + return { ok: false }; + } finally { + if (timeout) { + (0, import_node_timers.clearTimeout)(timeout); + } + this.timeoutAbortControllers.delete(event); + if (!closeController.signal.aborted) { + closeController.abort(); + } + } + } + async send(payload) { + if (!this.connection) { + throw new Error("WebSocketShard wasn't connected"); + } + if (this.#status !== 3 /* Ready */ && !ImportantGatewayOpcodes.has(payload.op)) { + this.debug(["Tried to send a non-crucial payload before the shard was ready, waiting"]); + try { + await (0, import_node_events2.once)(this, "ready" /* Ready */); + } catch { + return this.send(payload); + } + } + await this.sendQueue.wait(); + if (--this.sendRateLimitState.remaining <= 0) { + const now = Date.now(); + if (this.sendRateLimitState.resetAt > now) { + const sleepFor = this.sendRateLimitState.resetAt - now; + this.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]); + const controller = new AbortController(); + const interrupted = await Promise.race([ + (0, import_promises2.setTimeout)(sleepFor).then(() => false), + (0, import_node_events2.once)(this, "closed" /* Closed */, { signal: controller.signal }).then(() => true) + ]); + if (interrupted) { + this.debug(["Connection closed while waiting for the send rate limit to reset, re-queueing payload"]); + this.sendQueue.shift(); + return this.send(payload); + } + controller.abort(); + } + this.sendRateLimitState = getInitialSendRateLimitState(); + } + this.sendQueue.shift(); + this.connection.send(JSON.stringify(payload)); + } + async identify() { + this.debug(["Waiting for identify throttle"]); + const controller = new AbortController(); + const closeHandler = /* @__PURE__ */ __name(() => { + controller.abort(); + }, "closeHandler"); + this.on("closed" /* Closed */, closeHandler); + try { + await this.strategy.waitForIdentify(this.id, controller.signal); + } catch { + this.debug(["Was waiting for an identify, but the shard closed in the meantime"]); + return; + } finally { + this.off("closed" /* Closed */, closeHandler); + } + this.debug([ + "Identifying", + `shard id: ${this.id.toString()}`, + `shard count: ${this.strategy.options.shardCount}`, + `intents: ${this.strategy.options.intents}`, + `compression: ${this.inflate ? "zlib-stream" : this.useIdentifyCompress ? "identify" : "none"}` + ]); + const d = { + token: this.strategy.options.token, + properties: this.strategy.options.identifyProperties, + intents: this.strategy.options.intents, + compress: this.useIdentifyCompress, + shard: [this.id, this.strategy.options.shardCount] + }; + if (this.strategy.options.largeThreshold) { + d.large_threshold = this.strategy.options.largeThreshold; + } + if (this.strategy.options.initialPresence) { + d.presence = this.strategy.options.initialPresence; + } + await this.send({ + op: import_v102.GatewayOpcodes.Identify, + d + }); + await this.waitForEvent("ready" /* Ready */, this.strategy.options.readyTimeout); + } + async resume(session) { + this.debug([ + "Resuming session", + `resume url: ${session.resumeURL}`, + `sequence: ${session.sequence}`, + `shard id: ${this.id.toString()}` + ]); + this.#status = 2 /* Resuming */; + this.replayedEvents = 0; + return this.send({ + op: import_v102.GatewayOpcodes.Resume, + d: { + token: this.strategy.options.token, + seq: session.sequence, + session_id: session.sessionId + } + }); + } + async heartbeat(requested = false) { + if (!this.isAck && !requested) { + return this.destroy({ reason: "Zombie connection", recover: 1 /* Resume */ }); + } + const session = await this.strategy.retrieveSessionInfo(this.id); + await this.send({ + op: import_v102.GatewayOpcodes.Heartbeat, + d: session?.sequence ?? null + }); + this.lastHeartbeatAt = Date.now(); + this.isAck = false; + } + async unpackMessage(data, isBinary) { + const decompressable = new Uint8Array(data); + if (!isBinary) { + return JSON.parse(this.textDecoder.decode(decompressable)); + } + if (this.useIdentifyCompress) { + return new Promise((resolve2, reject) => { + (0, import_node_zlib.inflate)(decompressable, { chunkSize: 65535 }, (err, result) => { + if (err) { + reject(err); + return; + } + resolve2(JSON.parse(this.textDecoder.decode(result))); + }); + }); + } + if (this.inflate) { + const l = decompressable.length; + const flush = l >= 4 && decompressable[l - 4] === 0 && decompressable[l - 3] === 0 && decompressable[l - 2] === 255 && decompressable[l - 1] === 255; + const zlib = await getZlibSync(); + this.inflate.push(import_node_buffer.Buffer.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH); + if (this.inflate.err) { + this.emit("error" /* Error */, { + error: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ""}`) + }); + } + if (!flush) { + return null; + } + const { result } = this.inflate; + if (!result) { + return null; + } + return JSON.parse(typeof result === "string" ? result : this.textDecoder.decode(result)); + } + this.debug([ + "Received a message we were unable to decompress", + `isBinary: ${isBinary.toString()}`, + `useIdentifyCompress: ${this.useIdentifyCompress.toString()}`, + `inflate: ${Boolean(this.inflate).toString()}` + ]); + return null; + } + async onMessage(data, isBinary) { + const payload = await this.unpackMessage(data, isBinary); + if (!payload) { + return; + } + switch (payload.op) { + case import_v102.GatewayOpcodes.Dispatch: { + if (this.#status === 2 /* Resuming */) { + this.replayedEvents++; + } + switch (payload.t) { + case import_v102.GatewayDispatchEvents.Ready: { + this.#status = 3 /* Ready */; + const session2 = { + sequence: payload.s, + sessionId: payload.d.session_id, + shardId: this.id, + shardCount: this.strategy.options.shardCount, + resumeURL: payload.d.resume_gateway_url + }; + await this.strategy.updateSessionInfo(this.id, session2); + this.emit("ready" /* Ready */, { data: payload.d }); + break; + } + case import_v102.GatewayDispatchEvents.Resumed: { + this.#status = 3 /* Ready */; + this.debug([`Resumed and replayed ${this.replayedEvents} events`]); + this.emit("resumed" /* Resumed */); + break; + } + default: { + break; + } + } + const session = await this.strategy.retrieveSessionInfo(this.id); + if (session) { + if (payload.s > session.sequence) { + await this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s }); + } + } else { + this.debug([ + `Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect` + ]); + } + this.emit("dispatch" /* Dispatch */, { data: payload }); + break; + } + case import_v102.GatewayOpcodes.Heartbeat: { + await this.heartbeat(true); + break; + } + case import_v102.GatewayOpcodes.Reconnect: { + await this.destroy({ + reason: "Told to reconnect by Discord", + recover: 1 /* Resume */ + }); + break; + } + case import_v102.GatewayOpcodes.InvalidSession: { + this.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]); + const session = await this.strategy.retrieveSessionInfo(this.id); + if (payload.d && session) { + await this.resume(session); + } else { + await this.destroy({ + reason: "Invalid session", + recover: 0 /* Reconnect */ + }); + } + break; + } + case import_v102.GatewayOpcodes.Hello: { + this.emit("hello" /* Hello */); + const jitter = Math.random(); + const firstWait = Math.floor(payload.d.heartbeat_interval * jitter); + this.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]); + try { + const controller = new AbortController(); + this.initialHeartbeatTimeoutController = controller; + await (0, import_promises2.setTimeout)(firstWait, void 0, { signal: controller.signal }); + } catch { + this.debug(["Cancelled initial heartbeat due to #destroy being called"]); + return; + } finally { + this.initialHeartbeatTimeoutController = null; + } + await this.heartbeat(); + this.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]); + this.heartbeatInterval = (0, import_node_timers.setInterval)(() => void this.heartbeat(), payload.d.heartbeat_interval); + break; + } + case import_v102.GatewayOpcodes.HeartbeatAck: { + this.isAck = true; + const ackAt = Date.now(); + this.emit("heartbeat" /* HeartbeatComplete */, { + ackAt, + heartbeatAt: this.lastHeartbeatAt, + latency: ackAt - this.lastHeartbeatAt + }); + break; + } + } + } + onError(error) { + if ("code" in error && ["ECONNRESET", "ECONNREFUSED"].includes(error.code)) { + this.debug(["Failed to connect to the gateway URL specified due to a network error"]); + this.failedToConnectDueToNetworkError = true; + return; + } + this.emit("error" /* Error */, { error }); + } + async onClose(code) { + this.emit("closed" /* Closed */, { code }); + switch (code) { + case 1e3 /* Normal */: { + return this.destroy({ + code, + reason: "Got disconnected by Discord", + recover: 0 /* Reconnect */ + }); + } + case 4200 /* Resuming */: { + break; + } + case import_v102.GatewayCloseCodes.UnknownError: { + this.debug([`An unknown error occurred: ${code}`]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case import_v102.GatewayCloseCodes.UnknownOpcode: { + this.debug(["An invalid opcode was sent to Discord."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case import_v102.GatewayCloseCodes.DecodeError: { + this.debug(["An invalid payload was sent to Discord."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case import_v102.GatewayCloseCodes.NotAuthenticated: { + this.debug(["A request was somehow sent before the identify/resume payload."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case import_v102.GatewayCloseCodes.AuthenticationFailed: { + throw new Error("Authentication failed"); + } + case import_v102.GatewayCloseCodes.AlreadyAuthenticated: { + this.debug(["More than one auth payload was sent."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case import_v102.GatewayCloseCodes.InvalidSeq: { + this.debug(["An invalid sequence was sent."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case import_v102.GatewayCloseCodes.RateLimited: { + this.debug(["The WebSocket rate limit has been hit, this should never happen"]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case import_v102.GatewayCloseCodes.SessionTimedOut: { + this.debug(["Session timed out."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case import_v102.GatewayCloseCodes.InvalidShard: { + throw new Error("Invalid shard"); + } + case import_v102.GatewayCloseCodes.ShardingRequired: { + throw new Error("Sharding is required"); + } + case import_v102.GatewayCloseCodes.InvalidAPIVersion: { + throw new Error("Used an invalid API version"); + } + case import_v102.GatewayCloseCodes.InvalidIntents: { + throw new Error("Used invalid intents"); + } + case import_v102.GatewayCloseCodes.DisallowedIntents: { + throw new Error("Used disallowed intents"); + } + default: { + this.debug([ + `The gateway closed with an unexpected code ${code}, attempting to ${this.failedToConnectDueToNetworkError ? "reconnect" : "resume"}.` + ]); + return this.destroy({ + code, + recover: this.failedToConnectDueToNetworkError ? 0 /* Reconnect */ : 1 /* Resume */ + }); + } + } + } + debug(messages) { + const message = `${messages[0]}${messages.length > 1 ? ` +${messages.slice(1).map((m) => ` ${m}`).join("\n")}` : ""}`; + this.emit("debug" /* Debug */, { message }); + } +}; +__name(WebSocketShard, "WebSocketShard"); + +// src/utils/WorkerBootstrapper.ts +var WorkerBootstrapper = class { + /** + * The data passed to the worker thread + */ + data = import_node_worker_threads3.workerData; + /** + * The shards that are managed by this worker + */ + shards = new import_collection7.Collection(); + constructor() { + if (import_node_worker_threads3.isMainThread) { + throw new Error("Expected WorkerBootstrap to not be used within the main thread"); + } + } + /** + * Helper method to initiate a shard's connection process + */ + async connect(shardId) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} does not exist`); + } + await shard.connect(); + } + /** + * Helper method to destroy a shard + */ + async destroy(shardId, options) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} does not exist`); + } + await shard.destroy(options); + } + /** + * Helper method to attach event listeners to the parentPort + */ + setupThreadEvents() { + import_node_worker_threads3.parentPort.on("messageerror", (err) => { + throw err; + }).on("message", async (payload) => { + switch (payload.op) { + case 0 /* Connect */: { + await this.connect(payload.shardId); + const response = { + op: 0 /* Connected */, + shardId: payload.shardId + }; + import_node_worker_threads3.parentPort.postMessage(response); + break; + } + case 1 /* Destroy */: { + await this.destroy(payload.shardId, payload.options); + const response = { + op: 1 /* Destroyed */, + shardId: payload.shardId + }; + import_node_worker_threads3.parentPort.postMessage(response); + break; + } + case 2 /* Send */: { + const shard = this.shards.get(payload.shardId); + if (!shard) { + throw new RangeError(`Shard ${payload.shardId} does not exist`); + } + await shard.send(payload.payload); + break; + } + case 3 /* SessionInfoResponse */: { + break; + } + case 4 /* ShardIdentifyResponse */: { + break; + } + case 5 /* FetchStatus */: { + const shard = this.shards.get(payload.shardId); + if (!shard) { + throw new Error(`Shard ${payload.shardId} does not exist`); + } + const response = { + op: 6 /* FetchStatusResponse */, + status: shard.status, + nonce: payload.nonce + }; + import_node_worker_threads3.parentPort.postMessage(response); + break; + } + } + }); + } + /** + * Bootstraps the worker thread with the provided options + */ + async bootstrap(options = {}) { + for (const shardId of this.data.shardIds) { + const shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId); + for (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) { + shard.on(event, (data) => { + const payload = { + op: 2 /* Event */, + event, + data, + shardId + }; + import_node_worker_threads3.parentPort.postMessage(payload); + }); + } + await options.shardCallback?.(shard); + this.shards.set(shardId, shard); + } + this.setupThreadEvents(); + const message = { + op: 7 /* WorkerReady */ + }; + import_node_worker_threads3.parentPort.postMessage(message); + } +}; +__name(WorkerBootstrapper, "WorkerBootstrapper"); + +// src/strategies/sharding/defaultWorker.ts +var bootstrapper = new WorkerBootstrapper(); +void bootstrapper.bootstrap(); +//# sourceMappingURL=defaultWorker.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/ws/dist/defaultWorker.js.map b/node_modules/@discordjs/ws/dist/defaultWorker.js.map new file mode 100644 index 0000000..0ac404d --- /dev/null +++ b/node_modules/@discordjs/ws/dist/defaultWorker.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/utils/WorkerBootstrapper.ts","../src/strategies/context/WorkerContextFetchingStrategy.ts","../src/strategies/sharding/WorkerShardingStrategy.ts","../src/strategies/context/IContextFetchingStrategy.ts","../src/ws/WebSocketShard.ts","../src/utils/constants.ts","../src/strategies/sharding/SimpleShardingStrategy.ts","../src/strategies/context/SimpleContextFetchingStrategy.ts","../src/throttling/SimpleIdentifyThrottler.ts","../src/strategies/sharding/defaultWorker.ts"],"sourcesContent":["import { isMainThread, parentPort, workerData } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { Awaitable } from '@discordjs/util';\nimport { WorkerContextFetchingStrategy } from '../strategies/context/WorkerContextFetchingStrategy.js';\nimport {\n\tWorkerReceivePayloadOp,\n\tWorkerSendPayloadOp,\n\ttype WorkerData,\n\ttype WorkerReceivePayload,\n\ttype WorkerSendPayload,\n} from '../strategies/sharding/WorkerShardingStrategy.js';\nimport type { WebSocketShardDestroyOptions } from '../ws/WebSocketShard.js';\nimport { WebSocketShardEvents, WebSocketShard } from '../ws/WebSocketShard.js';\n\n/**\n * Options for bootstrapping the worker\n */\nexport interface BootstrapOptions {\n\t/**\n\t * Shard events to just arbitrarily forward to the parent thread for the manager to emit\n\t * Note: By default, this will include ALL events\n\t * you most likely want to handle dispatch within the worker itself\n\t */\n\tforwardEvents?: WebSocketShardEvents[];\n\t/**\n\t * Function to call when a shard is created for additional setup\n\t */\n\tshardCallback?(shard: WebSocketShard): Awaitable;\n}\n\n/**\n * Utility class for bootstrapping a worker thread to be used for sharding\n */\nexport class WorkerBootstrapper {\n\t/**\n\t * The data passed to the worker thread\n\t */\n\tprotected readonly data = workerData as WorkerData;\n\n\t/**\n\t * The shards that are managed by this worker\n\t */\n\tprotected readonly shards = new Collection();\n\n\tpublic constructor() {\n\t\tif (isMainThread) {\n\t\t\tthrow new Error('Expected WorkerBootstrap to not be used within the main thread');\n\t\t}\n\t}\n\n\t/**\n\t * Helper method to initiate a shard's connection process\n\t */\n\tprotected async connect(shardId: number): Promise {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} does not exist`);\n\t\t}\n\n\t\tawait shard.connect();\n\t}\n\n\t/**\n\t * Helper method to destroy a shard\n\t */\n\tprotected async destroy(shardId: number, options?: WebSocketShardDestroyOptions): Promise {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} does not exist`);\n\t\t}\n\n\t\tawait shard.destroy(options);\n\t}\n\n\t/**\n\t * Helper method to attach event listeners to the parentPort\n\t */\n\tprotected setupThreadEvents(): void {\n\t\tparentPort!\n\t\t\t.on('messageerror', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('message', async (payload: WorkerSendPayload) => {\n\t\t\t\tswitch (payload.op) {\n\t\t\t\t\tcase WorkerSendPayloadOp.Connect: {\n\t\t\t\t\t\tawait this.connect(payload.shardId);\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.Connected,\n\t\t\t\t\t\t\tshardId: payload.shardId,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.Destroy: {\n\t\t\t\t\t\tawait this.destroy(payload.shardId, payload.options);\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.Destroyed,\n\t\t\t\t\t\t\tshardId: payload.shardId,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.Send: {\n\t\t\t\t\t\tconst shard = this.shards.get(payload.shardId);\n\t\t\t\t\t\tif (!shard) {\n\t\t\t\t\t\t\tthrow new RangeError(`Shard ${payload.shardId} does not exist`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait shard.send(payload.payload);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.SessionInfoResponse: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.ShardIdentifyResponse: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.FetchStatus: {\n\t\t\t\t\t\tconst shard = this.shards.get(payload.shardId);\n\t\t\t\t\t\tif (!shard) {\n\t\t\t\t\t\t\tthrow new Error(`Shard ${payload.shardId} does not exist`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.FetchStatusResponse,\n\t\t\t\t\t\t\tstatus: shard.status,\n\t\t\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t}\n\n\t/**\n\t * Bootstraps the worker thread with the provided options\n\t */\n\tpublic async bootstrap(options: Readonly = {}): Promise {\n\t\t// Start by initializing the shards\n\t\tfor (const shardId of this.data.shardIds) {\n\t\t\tconst shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId);\n\t\t\tfor (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) {\n\t\t\t\t// @ts-expect-error: Event types incompatible\n\t\t\t\tshard.on(event, (data) => {\n\t\t\t\t\tconst payload: WorkerReceivePayload = {\n\t\t\t\t\t\top: WorkerReceivePayloadOp.Event,\n\t\t\t\t\t\tevent,\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\tshardId,\n\t\t\t\t\t};\n\t\t\t\t\tparentPort!.postMessage(payload);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Any additional setup the user might want to do\n\t\t\tawait options.shardCallback?.(shard);\n\t\t\tthis.shards.set(shardId, shard);\n\t\t}\n\n\t\t// Lastly, start listening to messages from the parent thread\n\t\tthis.setupThreadEvents();\n\n\t\tconst message: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.WorkerReady,\n\t\t};\n\t\tparentPort!.postMessage(message);\n\t}\n}\n","import { isMainThread, parentPort } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { SessionInfo } from '../../ws/WebSocketManager.js';\nimport {\n\tWorkerReceivePayloadOp,\n\tWorkerSendPayloadOp,\n\ttype WorkerReceivePayload,\n\ttype WorkerSendPayload,\n} from '../sharding/WorkerShardingStrategy.js';\nimport type { FetchingStrategyOptions, IContextFetchingStrategy } from './IContextFetchingStrategy.js';\n\n// Because the global types are incomplete for whatever reason\ninterface PolyFillAbortSignal {\n\treadonly aborted: boolean;\n\taddEventListener(type: 'abort', listener: () => void): void;\n\tremoveEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport class WorkerContextFetchingStrategy implements IContextFetchingStrategy {\n\tprivate readonly sessionPromises = new Collection void>();\n\n\tprivate readonly waitForIdentifyPromises = new Collection();\n\n\tpublic constructor(public readonly options: FetchingStrategyOptions) {\n\t\tif (isMainThread) {\n\t\t\tthrow new Error('Cannot instantiate WorkerContextFetchingStrategy on the main thread');\n\t\t}\n\n\t\tparentPort!.on('message', (payload: WorkerSendPayload) => {\n\t\t\tif (payload.op === WorkerSendPayloadOp.SessionInfoResponse) {\n\t\t\t\tthis.sessionPromises.get(payload.nonce)?.(payload.session);\n\t\t\t\tthis.sessionPromises.delete(payload.nonce);\n\t\t\t}\n\n\t\t\tif (payload.op === WorkerSendPayloadOp.ShardIdentifyResponse) {\n\t\t\t\tconst promise = this.waitForIdentifyPromises.get(payload.nonce);\n\t\t\t\tif (payload.ok) {\n\t\t\t\t\tpromise?.resolve();\n\t\t\t\t} else {\n\t\t\t\t\tpromise?.reject();\n\t\t\t\t}\n\n\t\t\t\tthis.waitForIdentifyPromises.delete(payload.nonce);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async retrieveSessionInfo(shardId: number): Promise {\n\t\tconst nonce = Math.random();\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.RetrieveSessionInfo,\n\t\t\tshardId,\n\t\t\tnonce,\n\t\t};\n\t\t// eslint-disable-next-line no-promise-executor-return\n\t\tconst promise = new Promise((resolve) => this.sessionPromises.set(nonce, resolve));\n\t\tparentPort!.postMessage(payload);\n\t\treturn promise;\n\t}\n\n\tpublic updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null) {\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.UpdateSessionInfo,\n\t\t\tshardId,\n\t\t\tsession: sessionInfo,\n\t\t};\n\t\tparentPort!.postMessage(payload);\n\t}\n\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst nonce = Math.random();\n\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.WaitForIdentify,\n\t\t\tnonce,\n\t\t\tshardId,\n\t\t};\n\t\tconst promise = new Promise((resolve, reject) =>\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tthis.waitForIdentifyPromises.set(nonce, { resolve, reject }),\n\t\t);\n\n\t\tparentPort!.postMessage(payload);\n\n\t\tconst listener = () => {\n\t\t\tconst payload: WorkerReceivePayload = {\n\t\t\t\top: WorkerReceivePayloadOp.CancelIdentify,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\tparentPort!.postMessage(payload);\n\t\t};\n\n\t\t(signal as unknown as PolyFillAbortSignal).addEventListener('abort', listener);\n\n\t\ttry {\n\t\t\tawait promise;\n\t\t} finally {\n\t\t\t(signal as unknown as PolyFillAbortSignal).removeEventListener('abort', listener);\n\t\t}\n\t}\n}\n","import { once } from 'node:events';\nimport { join, isAbsolute, resolve } from 'node:path';\nimport { Worker } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { GatewaySendPayload } from 'discord-api-types/v10';\nimport type { IIdentifyThrottler } from '../../throttling/IIdentifyThrottler.js';\nimport type { SessionInfo, WebSocketManager } from '../../ws/WebSocketManager.js';\nimport type {\n\tWebSocketShardDestroyOptions,\n\tWebSocketShardEvents,\n\tWebSocketShardStatus,\n} from '../../ws/WebSocketShard.js';\nimport { managerToFetchingStrategyOptions, type FetchingStrategyOptions } from '../context/IContextFetchingStrategy.js';\nimport type { IShardingStrategy } from './IShardingStrategy.js';\n\nexport interface WorkerData extends FetchingStrategyOptions {\n\tshardIds: number[];\n}\n\nexport enum WorkerSendPayloadOp {\n\tConnect,\n\tDestroy,\n\tSend,\n\tSessionInfoResponse,\n\tShardIdentifyResponse,\n\tFetchStatus,\n}\n\nexport type WorkerSendPayload =\n\t| { nonce: number; ok: boolean; op: WorkerSendPayloadOp.ShardIdentifyResponse }\n\t| { nonce: number; op: WorkerSendPayloadOp.FetchStatus; shardId: number }\n\t| { nonce: number; op: WorkerSendPayloadOp.SessionInfoResponse; session: SessionInfo | null }\n\t| { op: WorkerSendPayloadOp.Connect; shardId: number }\n\t| { op: WorkerSendPayloadOp.Destroy; options?: WebSocketShardDestroyOptions; shardId: number }\n\t| { op: WorkerSendPayloadOp.Send; payload: GatewaySendPayload; shardId: number };\n\nexport enum WorkerReceivePayloadOp {\n\tConnected,\n\tDestroyed,\n\tEvent,\n\tRetrieveSessionInfo,\n\tUpdateSessionInfo,\n\tWaitForIdentify,\n\tFetchStatusResponse,\n\tWorkerReady,\n\tCancelIdentify,\n}\n\nexport type WorkerReceivePayload =\n\t// Can't seem to get a type-safe union based off of the event, so I'm sadly leaving data as any for now\n\t| { data: any; event: WebSocketShardEvents; op: WorkerReceivePayloadOp.Event; shardId: number }\n\t| { nonce: number; op: WorkerReceivePayloadOp.CancelIdentify }\n\t| { nonce: number; op: WorkerReceivePayloadOp.FetchStatusResponse; status: WebSocketShardStatus }\n\t| { nonce: number; op: WorkerReceivePayloadOp.RetrieveSessionInfo; shardId: number }\n\t| { nonce: number; op: WorkerReceivePayloadOp.WaitForIdentify; shardId: number }\n\t| { op: WorkerReceivePayloadOp.Connected; shardId: number }\n\t| { op: WorkerReceivePayloadOp.Destroyed; shardId: number }\n\t| { op: WorkerReceivePayloadOp.UpdateSessionInfo; session: SessionInfo | null; shardId: number }\n\t| { op: WorkerReceivePayloadOp.WorkerReady };\n\n/**\n * Options for a {@link WorkerShardingStrategy}\n */\nexport interface WorkerShardingStrategyOptions {\n\t/**\n\t * Dictates how many shards should be spawned per worker thread.\n\t */\n\tshardsPerWorker: number | 'all';\n\t/**\n\t * Path to the worker file to use. The worker requires quite a bit of setup, it is recommended you leverage the {@link WorkerBootstrapper} class.\n\t */\n\tworkerPath?: string;\n}\n\n/**\n * Strategy used to spawn threads in worker_threads\n */\nexport class WorkerShardingStrategy implements IShardingStrategy {\n\tprivate readonly manager: WebSocketManager;\n\n\tprivate readonly options: WorkerShardingStrategyOptions;\n\n\t#workers: Worker[] = [];\n\n\treadonly #workerByShardId = new Collection();\n\n\tprivate readonly connectPromises = new Collection void>();\n\n\tprivate readonly destroyPromises = new Collection void>();\n\n\tprivate readonly fetchStatusPromises = new Collection void>();\n\n\tprivate readonly waitForIdentifyControllers = new Collection();\n\n\tprivate throttler?: IIdentifyThrottler;\n\n\tpublic constructor(manager: WebSocketManager, options: WorkerShardingStrategyOptions) {\n\t\tthis.manager = manager;\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.spawn}\n\t */\n\tpublic async spawn(shardIds: number[]) {\n\t\tconst shardsPerWorker = this.options.shardsPerWorker === 'all' ? shardIds.length : this.options.shardsPerWorker;\n\t\tconst strategyOptions = await managerToFetchingStrategyOptions(this.manager);\n\n\t\tconst loops = Math.ceil(shardIds.length / shardsPerWorker);\n\t\tconst promises: Promise[] = [];\n\n\t\tfor (let idx = 0; idx < loops; idx++) {\n\t\t\tconst slice = shardIds.slice(idx * shardsPerWorker, (idx + 1) * shardsPerWorker);\n\t\t\tconst workerData: WorkerData = {\n\t\t\t\t...strategyOptions,\n\t\t\t\tshardIds: slice,\n\t\t\t};\n\n\t\t\tpromises.push(this.setupWorker(workerData));\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.connect}\n\t */\n\tpublic async connect() {\n\t\tconst promises = [];\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.Connect,\n\t\t\t\tshardId,\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tconst promise = new Promise((resolve) => this.connectPromises.set(shardId, resolve));\n\t\t\tworker.postMessage(payload);\n\t\t\tpromises.push(promise);\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.destroy}\n\t */\n\tpublic async destroy(options: Omit = {}) {\n\t\tconst promises = [];\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.Destroy,\n\t\t\t\tshardId,\n\t\t\t\toptions,\n\t\t\t};\n\n\t\t\tpromises.push(\n\t\t\t\t// eslint-disable-next-line no-promise-executor-return, promise/prefer-await-to-then\n\t\t\t\tnew Promise((resolve) => this.destroyPromises.set(shardId, resolve)).then(async () => worker.terminate()),\n\t\t\t);\n\t\t\tworker.postMessage(payload);\n\t\t}\n\n\t\tthis.#workers = [];\n\t\tthis.#workerByShardId.clear();\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.send}\n\t */\n\tpublic send(shardId: number, data: GatewaySendPayload) {\n\t\tconst worker = this.#workerByShardId.get(shardId);\n\t\tif (!worker) {\n\t\t\tthrow new Error(`No worker found for shard ${shardId}`);\n\t\t}\n\n\t\tconst payload: WorkerSendPayload = {\n\t\t\top: WorkerSendPayloadOp.Send,\n\t\t\tshardId,\n\t\t\tpayload: data,\n\t\t};\n\t\tworker.postMessage(payload);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.fetchStatus}\n\t */\n\tpublic async fetchStatus() {\n\t\tconst statuses = new Collection();\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst nonce = Math.random();\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.FetchStatus,\n\t\t\t\tshardId,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tconst promise = new Promise((resolve) => this.fetchStatusPromises.set(nonce, resolve));\n\t\t\tworker.postMessage(payload);\n\n\t\t\tconst status = await promise;\n\t\t\tstatuses.set(shardId, status);\n\t\t}\n\n\t\treturn statuses;\n\t}\n\n\tprivate async setupWorker(workerData: WorkerData) {\n\t\tconst worker = new Worker(this.resolveWorkerPath(), { workerData });\n\n\t\tawait once(worker, 'online');\n\t\t// We do this in case the user has any potentially long running code in their worker\n\t\tawait this.waitForWorkerReady(worker);\n\n\t\tworker\n\t\t\t.on('error', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('messageerror', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('message', async (payload: WorkerReceivePayload) => this.onMessage(worker, payload));\n\n\t\tthis.#workers.push(worker);\n\t\tfor (const shardId of workerData.shardIds) {\n\t\t\tthis.#workerByShardId.set(shardId, worker);\n\t\t}\n\t}\n\n\tprivate resolveWorkerPath(): string {\n\t\tconst path = this.options.workerPath;\n\n\t\tif (!path) {\n\t\t\treturn join(__dirname, 'defaultWorker.js');\n\t\t}\n\n\t\tif (isAbsolute(path)) {\n\t\t\treturn path;\n\t\t}\n\n\t\tif (/^\\.\\.?[/\\\\]/.test(path)) {\n\t\t\treturn resolve(path);\n\t\t}\n\n\t\ttry {\n\t\t\treturn require.resolve(path);\n\t\t} catch {\n\t\t\treturn resolve(path);\n\t\t}\n\t}\n\n\tprivate async waitForWorkerReady(worker: Worker): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst handler = (payload: WorkerReceivePayload) => {\n\t\t\t\tif (payload.op === WorkerReceivePayloadOp.WorkerReady) {\n\t\t\t\t\tresolve();\n\t\t\t\t\tworker.off('message', handler);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tworker.on('message', handler);\n\t\t});\n\t}\n\n\tprivate async onMessage(worker: Worker, payload: WorkerReceivePayload) {\n\t\tswitch (payload.op) {\n\t\t\tcase WorkerReceivePayloadOp.Connected: {\n\t\t\t\tthis.connectPromises.get(payload.shardId)?.();\n\t\t\t\tthis.connectPromises.delete(payload.shardId);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.Destroyed: {\n\t\t\t\tthis.destroyPromises.get(payload.shardId)?.();\n\t\t\t\tthis.destroyPromises.delete(payload.shardId);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.Event: {\n\t\t\t\tthis.manager.emit(payload.event, { ...payload.data, shardId: payload.shardId });\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.RetrieveSessionInfo: {\n\t\t\t\tconst session = await this.manager.options.retrieveSessionInfo(payload.shardId);\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.SessionInfoResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tsession,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.UpdateSessionInfo: {\n\t\t\t\tawait this.manager.options.updateSessionInfo(payload.shardId, payload.session);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.WaitForIdentify: {\n\t\t\t\tconst throttler = await this.ensureThrottler();\n\n\t\t\t\t// If this rejects it means we aborted, in which case we reply elsewhere.\n\t\t\t\ttry {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\tthis.waitForIdentifyControllers.set(payload.nonce, controller);\n\t\t\t\t\tawait throttler.waitForIdentify(payload.shardId, controller.signal);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.ShardIdentifyResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tok: true,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.FetchStatusResponse: {\n\t\t\t\tthis.fetchStatusPromises.get(payload.nonce)?.(payload.status);\n\t\t\t\tthis.fetchStatusPromises.delete(payload.nonce);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.WorkerReady: {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.CancelIdentify: {\n\t\t\t\tthis.waitForIdentifyControllers.get(payload.nonce)?.abort();\n\t\t\t\tthis.waitForIdentifyControllers.delete(payload.nonce);\n\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.ShardIdentifyResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tok: false,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async ensureThrottler(): Promise {\n\t\tthis.throttler ??= await this.manager.options.buildIdentifyThrottler(this.manager);\n\t\treturn this.throttler;\n\t}\n}\n","import type { Awaitable } from '@discordjs/util';\nimport type { APIGatewayBotInfo } from 'discord-api-types/v10';\nimport type { SessionInfo, WebSocketManager, WebSocketManagerOptions } from '../../ws/WebSocketManager.js';\n\nexport interface FetchingStrategyOptions\n\textends Omit<\n\t\tWebSocketManagerOptions,\n\t\t| 'buildIdentifyThrottler'\n\t\t| 'buildStrategy'\n\t\t| 'rest'\n\t\t| 'retrieveSessionInfo'\n\t\t| 'shardCount'\n\t\t| 'shardIds'\n\t\t| 'updateSessionInfo'\n\t> {\n\treadonly gatewayInformation: APIGatewayBotInfo;\n\treadonly shardCount: number;\n}\n\n/**\n * Strategies responsible solely for making manager information accessible\n */\nexport interface IContextFetchingStrategy {\n\treadonly options: FetchingStrategyOptions;\n\tretrieveSessionInfo(shardId: number): Awaitable;\n\tupdateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable;\n\t/**\n\t * Resolves once the given shard should be allowed to identify, or rejects if the operation was aborted\n\t */\n\twaitForIdentify(shardId: number, signal: AbortSignal): Promise;\n}\n\nexport async function managerToFetchingStrategyOptions(manager: WebSocketManager): Promise {\n\t/* eslint-disable @typescript-eslint/unbound-method */\n\tconst {\n\t\tbuildIdentifyThrottler,\n\t\tbuildStrategy,\n\t\tretrieveSessionInfo,\n\t\tupdateSessionInfo,\n\t\tshardCount,\n\t\tshardIds,\n\t\trest,\n\t\t...managerOptions\n\t} = manager.options;\n\t/* eslint-enable @typescript-eslint/unbound-method */\n\n\treturn {\n\t\t...managerOptions,\n\t\tgatewayInformation: await manager.fetchGatewayInformation(),\n\t\tshardCount: await manager.getShardCount(),\n\t};\n}\n","/* eslint-disable id-length */\nimport { Buffer } from 'node:buffer';\nimport { once } from 'node:events';\nimport { clearInterval, clearTimeout, setInterval, setTimeout } from 'node:timers';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { URLSearchParams } from 'node:url';\nimport { TextDecoder } from 'node:util';\nimport { inflate } from 'node:zlib';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\nimport {\n\tGatewayCloseCodes,\n\tGatewayDispatchEvents,\n\tGatewayOpcodes,\n\ttype GatewayDispatchPayload,\n\ttype GatewayIdentifyData,\n\ttype GatewayReadyDispatchData,\n\ttype GatewayReceivePayload,\n\ttype GatewaySendPayload,\n} from 'discord-api-types/v10';\nimport { WebSocket, type RawData } from 'ws';\nimport type { Inflate } from 'zlib-sync';\nimport type { IContextFetchingStrategy } from '../strategies/context/IContextFetchingStrategy.js';\nimport { ImportantGatewayOpcodes, getInitialSendRateLimitState } from '../utils/constants.js';\nimport type { SessionInfo } from './WebSocketManager.js';\n\n// eslint-disable-next-line promise/prefer-await-to-then\nconst getZlibSync = lazy(async () => import('zlib-sync').then((mod) => mod.default).catch(() => null));\n\nexport enum WebSocketShardEvents {\n\tClosed = 'closed',\n\tDebug = 'debug',\n\tDispatch = 'dispatch',\n\tError = 'error',\n\tHeartbeatComplete = 'heartbeat',\n\tHello = 'hello',\n\tReady = 'ready',\n\tResumed = 'resumed',\n}\n\nexport enum WebSocketShardStatus {\n\tIdle,\n\tConnecting,\n\tResuming,\n\tReady,\n}\n\nexport enum WebSocketShardDestroyRecovery {\n\tReconnect,\n\tResume,\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport type WebSocketShardEventsMap = {\n\t[WebSocketShardEvents.Closed]: [{ code: number }];\n\t[WebSocketShardEvents.Debug]: [payload: { message: string }];\n\t[WebSocketShardEvents.Dispatch]: [payload: { data: GatewayDispatchPayload }];\n\t[WebSocketShardEvents.Error]: [payload: { error: Error }];\n\t[WebSocketShardEvents.Hello]: [];\n\t[WebSocketShardEvents.Ready]: [payload: { data: GatewayReadyDispatchData }];\n\t[WebSocketShardEvents.Resumed]: [];\n\t[WebSocketShardEvents.HeartbeatComplete]: [payload: { ackAt: number; heartbeatAt: number; latency: number }];\n};\n\nexport interface WebSocketShardDestroyOptions {\n\tcode?: number;\n\treason?: string;\n\trecover?: WebSocketShardDestroyRecovery;\n}\n\nexport enum CloseCodes {\n\tNormal = 1_000,\n\tResuming = 4_200,\n}\n\nexport interface SendRateLimitState {\n\tremaining: number;\n\tresetAt: number;\n}\n\nexport class WebSocketShard extends AsyncEventEmitter {\n\tprivate connection: WebSocket | null = null;\n\n\tprivate useIdentifyCompress = false;\n\n\tprivate inflate: Inflate | null = null;\n\n\tprivate readonly textDecoder = new TextDecoder();\n\n\tprivate replayedEvents = 0;\n\n\tprivate isAck = true;\n\n\tprivate sendRateLimitState: SendRateLimitState = getInitialSendRateLimitState();\n\n\tprivate initialHeartbeatTimeoutController: AbortController | null = null;\n\n\tprivate heartbeatInterval: NodeJS.Timer | null = null;\n\n\tprivate lastHeartbeatAt = -1;\n\n\t// Indicates whether the shard has already resolved its original connect() call\n\tprivate initialConnectResolved = false;\n\n\t// Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET)\n\tprivate failedToConnectDueToNetworkError = false;\n\n\tprivate readonly sendQueue = new AsyncQueue();\n\n\tprivate readonly timeoutAbortControllers = new Collection();\n\n\tprivate readonly strategy: IContextFetchingStrategy;\n\n\tpublic readonly id: number;\n\n\t#status: WebSocketShardStatus = WebSocketShardStatus.Idle;\n\n\tpublic get status(): WebSocketShardStatus {\n\t\treturn this.#status;\n\t}\n\n\tpublic constructor(strategy: IContextFetchingStrategy, id: number) {\n\t\tsuper();\n\t\tthis.strategy = strategy;\n\t\tthis.id = id;\n\t}\n\n\tpublic async connect() {\n\t\tconst promise = this.initialConnectResolved ? Promise.resolve() : once(this, WebSocketShardEvents.Ready);\n\t\tvoid this.internalConnect();\n\n\t\tawait promise;\n\t\tthis.initialConnectResolved = true;\n\t}\n\n\tprivate async internalConnect() {\n\t\tif (this.#status !== WebSocketShardStatus.Idle) {\n\t\t\tthrow new Error(\"Tried to connect a shard that wasn't idle\");\n\t\t}\n\n\t\tconst { version, encoding, compression } = this.strategy.options;\n\t\tconst params = new URLSearchParams({ v: version, encoding });\n\t\tif (compression) {\n\t\t\tconst zlib = await getZlibSync();\n\t\t\tif (zlib) {\n\t\t\t\tparams.append('compress', compression);\n\t\t\t\tthis.inflate = new zlib.Inflate({\n\t\t\t\t\tchunkSize: 65_535,\n\t\t\t\t\tto: 'string',\n\t\t\t\t});\n\t\t\t} else if (!this.useIdentifyCompress) {\n\t\t\t\tthis.useIdentifyCompress = true;\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\n\t\tconst url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`;\n\t\tthis.debug([`Connecting to ${url}`]);\n\t\tconst connection = new WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? undefined })\n\t\t\t.on('message', this.onMessage.bind(this))\n\t\t\t.on('error', this.onError.bind(this))\n\t\t\t.on('close', this.onClose.bind(this));\n\n\t\tconnection.binaryType = 'arraybuffer';\n\t\tthis.connection = connection;\n\n\t\tthis.#status = WebSocketShardStatus.Connecting;\n\n\t\tthis.sendRateLimitState = getInitialSendRateLimitState();\n\n\t\tconst { ok } = await this.waitForEvent(WebSocketShardEvents.Hello, this.strategy.options.helloTimeout);\n\t\tif (!ok) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (session?.shardCount === this.strategy.options.shardCount) {\n\t\t\tawait this.resume(session);\n\t\t} else {\n\t\t\tawait this.identify();\n\t\t}\n\t}\n\n\tpublic async destroy(options: WebSocketShardDestroyOptions = {}) {\n\t\tif (this.#status === WebSocketShardStatus.Idle) {\n\t\t\tthis.debug(['Tried to destroy a shard that was idle']);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!options.code) {\n\t\t\toptions.code = options.recover === WebSocketShardDestroyRecovery.Resume ? CloseCodes.Resuming : CloseCodes.Normal;\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Destroying shard',\n\t\t\t`Reason: ${options.reason ?? 'none'}`,\n\t\t\t`Code: ${options.code}`,\n\t\t\t`Recover: ${options.recover === undefined ? 'none' : WebSocketShardDestroyRecovery[options.recover]!}`,\n\t\t]);\n\n\t\t// Reset state\n\t\tthis.isAck = true;\n\t\tif (this.heartbeatInterval) {\n\t\t\tclearInterval(this.heartbeatInterval);\n\t\t}\n\n\t\tif (this.initialHeartbeatTimeoutController) {\n\t\t\tthis.initialHeartbeatTimeoutController.abort();\n\t\t\tthis.initialHeartbeatTimeoutController = null;\n\t\t}\n\n\t\tthis.lastHeartbeatAt = -1;\n\n\t\tfor (const controller of this.timeoutAbortControllers.values()) {\n\t\t\tcontroller.abort();\n\t\t}\n\n\t\tthis.timeoutAbortControllers.clear();\n\n\t\tthis.failedToConnectDueToNetworkError = false;\n\n\t\t// Clear session state if applicable\n\t\tif (options.recover !== WebSocketShardDestroyRecovery.Resume) {\n\t\t\tawait this.strategy.updateSessionInfo(this.id, null);\n\t\t}\n\n\t\tif (this.connection) {\n\t\t\t// No longer need to listen to messages\n\t\t\tthis.connection.removeAllListeners('message');\n\t\t\t// Prevent a reconnection loop by unbinding the main close event\n\t\t\tthis.connection.removeAllListeners('close');\n\n\t\t\tconst shouldClose = this.connection.readyState === WebSocket.OPEN;\n\n\t\t\tthis.debug([\n\t\t\t\t'Connection status during destroy',\n\t\t\t\t`Needs closing: ${shouldClose}`,\n\t\t\t\t`Ready state: ${this.connection.readyState}`,\n\t\t\t]);\n\n\t\t\tif (shouldClose) {\n\t\t\t\tthis.connection.close(options.code, options.reason);\n\t\t\t\tawait once(this.connection, 'close');\n\t\t\t\tthis.emit(WebSocketShardEvents.Closed, { code: options.code });\n\t\t\t}\n\n\t\t\t// Lastly, remove the error event.\n\t\t\t// Doing this earlier would cause a hard crash in case an error event fired on our `close` call\n\t\t\tthis.connection.removeAllListeners('error');\n\t\t} else {\n\t\t\tthis.debug(['Destroying a shard that has no connection; please open an issue on GitHub']);\n\t\t}\n\n\t\tthis.#status = WebSocketShardStatus.Idle;\n\n\t\tif (options.recover !== undefined) {\n\t\t\t// There's cases (like no internet connection) where we immediately fail to connect,\n\t\t\t// causing a very fast and draining reconnection loop.\n\t\t\tawait sleep(500);\n\t\t\treturn this.internalConnect();\n\t\t}\n\t}\n\n\tprivate async waitForEvent(event: WebSocketShardEvents, timeoutDuration?: number | null): Promise<{ ok: boolean }> {\n\t\tthis.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : 'indefinitely'}`]);\n\t\tconst timeoutController = new AbortController();\n\t\tconst timeout = timeoutDuration ? setTimeout(() => timeoutController.abort(), timeoutDuration).unref() : null;\n\n\t\tthis.timeoutAbortControllers.set(event, timeoutController);\n\n\t\tconst closeController = new AbortController();\n\n\t\ttry {\n\t\t\t// If the first promise resolves, all is well. If the 2nd promise resolves,\n\t\t\t// the shard has meanwhile closed. In that case, a destroy is already ongoing, so we just need to\n\t\t\t// return false. Meanwhile, if something rejects (error event) or the first controller is aborted,\n\t\t\t// we enter the catch block and trigger a destroy there.\n\t\t\tconst closed = await Promise.race([\n\t\t\t\tonce(this, event, { signal: timeoutController.signal }).then(() => false),\n\t\t\t\tonce(this, WebSocketShardEvents.Closed, { signal: closeController.signal }).then(() => true),\n\t\t\t]);\n\n\t\t\treturn { ok: !closed };\n\t\t} catch {\n\t\t\t// If we're here because of other reasons, we need to destroy the shard\n\t\t\tvoid this.destroy({\n\t\t\t\tcode: CloseCodes.Normal,\n\t\t\t\treason: 'Something timed out or went wrong while waiting for an event',\n\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t});\n\n\t\t\treturn { ok: false };\n\t\t} finally {\n\t\t\tif (timeout) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t}\n\n\t\t\tthis.timeoutAbortControllers.delete(event);\n\n\t\t\t// Clean up the close listener to not leak memory\n\t\t\tif (!closeController.signal.aborted) {\n\t\t\t\tcloseController.abort();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async send(payload: GatewaySendPayload): Promise {\n\t\tif (!this.connection) {\n\t\t\tthrow new Error(\"WebSocketShard wasn't connected\");\n\t\t}\n\n\t\tif (this.#status !== WebSocketShardStatus.Ready && !ImportantGatewayOpcodes.has(payload.op)) {\n\t\t\tthis.debug(['Tried to send a non-crucial payload before the shard was ready, waiting']);\n\t\t\t// This will throw if the shard throws an error event in the meantime, just requeue the payload\n\t\t\ttry {\n\t\t\t\tawait once(this, WebSocketShardEvents.Ready);\n\t\t\t} catch {\n\t\t\t\treturn this.send(payload);\n\t\t\t}\n\t\t}\n\n\t\tawait this.sendQueue.wait();\n\n\t\tif (--this.sendRateLimitState.remaining <= 0) {\n\t\t\tconst now = Date.now();\n\n\t\t\tif (this.sendRateLimitState.resetAt > now) {\n\t\t\t\tconst sleepFor = this.sendRateLimitState.resetAt - now;\n\n\t\t\t\tthis.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]);\n\t\t\t\tconst controller = new AbortController();\n\n\t\t\t\t// Sleep for the remaining time, but if the connection closes in the meantime, we shouldn't wait the remainder to avoid blocking the new conn\n\t\t\t\tconst interrupted = await Promise.race([\n\t\t\t\t\tsleep(sleepFor).then(() => false),\n\t\t\t\t\tonce(this, WebSocketShardEvents.Closed, { signal: controller.signal }).then(() => true),\n\t\t\t\t]);\n\n\t\t\t\tif (interrupted) {\n\t\t\t\t\tthis.debug(['Connection closed while waiting for the send rate limit to reset, re-queueing payload']);\n\t\t\t\t\tthis.sendQueue.shift();\n\t\t\t\t\treturn this.send(payload);\n\t\t\t\t}\n\n\t\t\t\t// This is so the listener from the `once` call is removed\n\t\t\t\tcontroller.abort();\n\t\t\t}\n\n\t\t\tthis.sendRateLimitState = getInitialSendRateLimitState();\n\t\t}\n\n\t\tthis.sendQueue.shift();\n\t\tthis.connection.send(JSON.stringify(payload));\n\t}\n\n\tprivate async identify() {\n\t\tthis.debug(['Waiting for identify throttle']);\n\n\t\tconst controller = new AbortController();\n\t\tconst closeHandler = () => {\n\t\t\tcontroller.abort();\n\t\t};\n\n\t\tthis.on(WebSocketShardEvents.Closed, closeHandler);\n\n\t\ttry {\n\t\t\tawait this.strategy.waitForIdentify(this.id, controller.signal);\n\t\t} catch {\n\t\t\tthis.debug(['Was waiting for an identify, but the shard closed in the meantime']);\n\t\t\treturn;\n\t\t} finally {\n\t\t\tthis.off(WebSocketShardEvents.Closed, closeHandler);\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Identifying',\n\t\t\t`shard id: ${this.id.toString()}`,\n\t\t\t`shard count: ${this.strategy.options.shardCount}`,\n\t\t\t`intents: ${this.strategy.options.intents}`,\n\t\t\t`compression: ${this.inflate ? 'zlib-stream' : this.useIdentifyCompress ? 'identify' : 'none'}`,\n\t\t]);\n\n\t\tconst d: GatewayIdentifyData = {\n\t\t\ttoken: this.strategy.options.token,\n\t\t\tproperties: this.strategy.options.identifyProperties,\n\t\t\tintents: this.strategy.options.intents,\n\t\t\tcompress: this.useIdentifyCompress,\n\t\t\tshard: [this.id, this.strategy.options.shardCount],\n\t\t};\n\n\t\tif (this.strategy.options.largeThreshold) {\n\t\t\td.large_threshold = this.strategy.options.largeThreshold;\n\t\t}\n\n\t\tif (this.strategy.options.initialPresence) {\n\t\t\td.presence = this.strategy.options.initialPresence;\n\t\t}\n\n\t\tawait this.send({\n\t\t\top: GatewayOpcodes.Identify,\n\t\t\td,\n\t\t});\n\n\t\tawait this.waitForEvent(WebSocketShardEvents.Ready, this.strategy.options.readyTimeout);\n\t}\n\n\tprivate async resume(session: SessionInfo) {\n\t\tthis.debug([\n\t\t\t'Resuming session',\n\t\t\t`resume url: ${session.resumeURL}`,\n\t\t\t`sequence: ${session.sequence}`,\n\t\t\t`shard id: ${this.id.toString()}`,\n\t\t]);\n\n\t\tthis.#status = WebSocketShardStatus.Resuming;\n\t\tthis.replayedEvents = 0;\n\t\treturn this.send({\n\t\t\top: GatewayOpcodes.Resume,\n\t\t\td: {\n\t\t\t\ttoken: this.strategy.options.token,\n\t\t\t\tseq: session.sequence,\n\t\t\t\tsession_id: session.sessionId,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async heartbeat(requested = false) {\n\t\tif (!this.isAck && !requested) {\n\t\t\treturn this.destroy({ reason: 'Zombie connection', recover: WebSocketShardDestroyRecovery.Resume });\n\t\t}\n\n\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\n\t\tawait this.send({\n\t\t\top: GatewayOpcodes.Heartbeat,\n\t\t\td: session?.sequence ?? null,\n\t\t});\n\n\t\tthis.lastHeartbeatAt = Date.now();\n\t\tthis.isAck = false;\n\t}\n\n\tprivate async unpackMessage(data: ArrayBuffer | Buffer, isBinary: boolean): Promise {\n\t\tconst decompressable = new Uint8Array(data);\n\n\t\t// Deal with no compression\n\t\tif (!isBinary) {\n\t\t\treturn JSON.parse(this.textDecoder.decode(decompressable)) as GatewayReceivePayload;\n\t\t}\n\n\t\t// Deal with identify compress\n\t\tif (this.useIdentifyCompress) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tinflate(decompressable, { chunkSize: 65_535 }, (err, result) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(JSON.parse(this.textDecoder.decode(result)) as GatewayReceivePayload);\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\t// Deal with gw wide zlib-stream compression\n\t\tif (this.inflate) {\n\t\t\tconst l = decompressable.length;\n\t\t\tconst flush =\n\t\t\t\tl >= 4 &&\n\t\t\t\tdecompressable[l - 4] === 0x00 &&\n\t\t\t\tdecompressable[l - 3] === 0x00 &&\n\t\t\t\tdecompressable[l - 2] === 0xff &&\n\t\t\t\tdecompressable[l - 1] === 0xff;\n\n\t\t\tconst zlib = (await getZlibSync())!;\n\t\t\tthis.inflate.push(Buffer.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH);\n\n\t\t\tif (this.inflate.err) {\n\t\t\t\tthis.emit(WebSocketShardEvents.Error, {\n\t\t\t\t\terror: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ''}`),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!flush) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst { result } = this.inflate;\n\t\t\tif (!result) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn JSON.parse(typeof result === 'string' ? result : this.textDecoder.decode(result)) as GatewayReceivePayload;\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Received a message we were unable to decompress',\n\t\t\t`isBinary: ${isBinary.toString()}`,\n\t\t\t`useIdentifyCompress: ${this.useIdentifyCompress.toString()}`,\n\t\t\t`inflate: ${Boolean(this.inflate).toString()}`,\n\t\t]);\n\n\t\treturn null;\n\t}\n\n\tprivate async onMessage(data: RawData, isBinary: boolean) {\n\t\tconst payload = await this.unpackMessage(data as ArrayBuffer | Buffer, isBinary);\n\t\tif (!payload) {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (payload.op) {\n\t\t\tcase GatewayOpcodes.Dispatch: {\n\t\t\t\tif (this.#status === WebSocketShardStatus.Resuming) {\n\t\t\t\t\tthis.replayedEvents++;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line sonarjs/no-nested-switch\n\t\t\t\tswitch (payload.t) {\n\t\t\t\t\tcase GatewayDispatchEvents.Ready: {\n\t\t\t\t\t\tthis.#status = WebSocketShardStatus.Ready;\n\n\t\t\t\t\t\tconst session = {\n\t\t\t\t\t\t\tsequence: payload.s,\n\t\t\t\t\t\t\tsessionId: payload.d.session_id,\n\t\t\t\t\t\t\tshardId: this.id,\n\t\t\t\t\t\t\tshardCount: this.strategy.options.shardCount,\n\t\t\t\t\t\t\tresumeURL: payload.d.resume_gateway_url,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tawait this.strategy.updateSessionInfo(this.id, session);\n\n\t\t\t\t\t\tthis.emit(WebSocketShardEvents.Ready, { data: payload.d });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase GatewayDispatchEvents.Resumed: {\n\t\t\t\t\t\tthis.#status = WebSocketShardStatus.Ready;\n\t\t\t\t\t\tthis.debug([`Resumed and replayed ${this.replayedEvents} events`]);\n\t\t\t\t\t\tthis.emit(WebSocketShardEvents.Resumed);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\t\t\t\tif (session) {\n\t\t\t\t\tif (payload.s > session.sequence) {\n\t\t\t\t\t\tawait this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s });\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.debug([\n\t\t\t\t\t\t`Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect`,\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tthis.emit(WebSocketShardEvents.Dispatch, { data: payload });\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Heartbeat: {\n\t\t\t\tawait this.heartbeat(true);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Reconnect: {\n\t\t\t\tawait this.destroy({\n\t\t\t\t\treason: 'Told to reconnect by Discord',\n\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Resume,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.InvalidSession: {\n\t\t\t\tthis.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]);\n\t\t\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\t\t\t\tif (payload.d && session) {\n\t\t\t\t\tawait this.resume(session);\n\t\t\t\t} else {\n\t\t\t\t\tawait this.destroy({\n\t\t\t\t\t\treason: 'Invalid session',\n\t\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Hello: {\n\t\t\t\tthis.emit(WebSocketShardEvents.Hello);\n\t\t\t\tconst jitter = Math.random();\n\t\t\t\tconst firstWait = Math.floor(payload.d.heartbeat_interval * jitter);\n\t\t\t\tthis.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\tthis.initialHeartbeatTimeoutController = controller;\n\t\t\t\t\tawait sleep(firstWait, undefined, { signal: controller.signal });\n\t\t\t\t} catch {\n\t\t\t\t\tthis.debug(['Cancelled initial heartbeat due to #destroy being called']);\n\t\t\t\t\treturn;\n\t\t\t\t} finally {\n\t\t\t\t\tthis.initialHeartbeatTimeoutController = null;\n\t\t\t\t}\n\n\t\t\t\tawait this.heartbeat();\n\n\t\t\t\tthis.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]);\n\t\t\t\tthis.heartbeatInterval = setInterval(() => void this.heartbeat(), payload.d.heartbeat_interval);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.HeartbeatAck: {\n\t\t\t\tthis.isAck = true;\n\n\t\t\t\tconst ackAt = Date.now();\n\t\t\t\tthis.emit(WebSocketShardEvents.HeartbeatComplete, {\n\t\t\t\t\tackAt,\n\t\t\t\t\theartbeatAt: this.lastHeartbeatAt,\n\t\t\t\t\tlatency: ackAt - this.lastHeartbeatAt,\n\t\t\t\t});\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate onError(error: Error) {\n\t\tif ('code' in error && ['ECONNRESET', 'ECONNREFUSED'].includes(error.code as string)) {\n\t\t\tthis.debug(['Failed to connect to the gateway URL specified due to a network error']);\n\t\t\tthis.failedToConnectDueToNetworkError = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.emit(WebSocketShardEvents.Error, { error });\n\t}\n\n\tprivate async onClose(code: number) {\n\t\tthis.emit(WebSocketShardEvents.Closed, { code });\n\n\t\tswitch (code) {\n\t\t\tcase CloseCodes.Normal: {\n\t\t\t\treturn this.destroy({\n\t\t\t\t\tcode,\n\t\t\t\t\treason: 'Got disconnected by Discord',\n\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase CloseCodes.Resuming: {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.UnknownError: {\n\t\t\t\tthis.debug([`An unknown error occurred: ${code}`]);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.UnknownOpcode: {\n\t\t\t\tthis.debug(['An invalid opcode was sent to Discord.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.DecodeError: {\n\t\t\t\tthis.debug(['An invalid payload was sent to Discord.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.NotAuthenticated: {\n\t\t\t\tthis.debug(['A request was somehow sent before the identify/resume payload.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.AuthenticationFailed: {\n\t\t\t\tthrow new Error('Authentication failed');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.AlreadyAuthenticated: {\n\t\t\t\tthis.debug(['More than one auth payload was sent.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidSeq: {\n\t\t\t\tthis.debug(['An invalid sequence was sent.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.RateLimited: {\n\t\t\t\tthis.debug(['The WebSocket rate limit has been hit, this should never happen']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.SessionTimedOut: {\n\t\t\t\tthis.debug(['Session timed out.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidShard: {\n\t\t\t\tthrow new Error('Invalid shard');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.ShardingRequired: {\n\t\t\t\tthrow new Error('Sharding is required');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidAPIVersion: {\n\t\t\t\tthrow new Error('Used an invalid API version');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidIntents: {\n\t\t\t\tthrow new Error('Used invalid intents');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.DisallowedIntents: {\n\t\t\t\tthrow new Error('Used disallowed intents');\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tthis.debug([\n\t\t\t\t\t`The gateway closed with an unexpected code ${code}, attempting to ${\n\t\t\t\t\t\tthis.failedToConnectDueToNetworkError ? 'reconnect' : 'resume'\n\t\t\t\t\t}.`,\n\t\t\t\t]);\n\t\t\t\treturn this.destroy({\n\t\t\t\t\tcode,\n\t\t\t\t\trecover: this.failedToConnectDueToNetworkError\n\t\t\t\t\t\t? WebSocketShardDestroyRecovery.Reconnect\n\t\t\t\t\t\t: WebSocketShardDestroyRecovery.Resume,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate debug(messages: [string, ...string[]]) {\n\t\tconst message = `${messages[0]}${\n\t\t\tmessages.length > 1\n\t\t\t\t? `\\n${messages\n\t\t\t\t\t\t.slice(1)\n\t\t\t\t\t\t.map((m) => `\t${m}`)\n\t\t\t\t\t\t.join('\\n')}`\n\t\t\t\t: ''\n\t\t}`;\n\n\t\tthis.emit(WebSocketShardEvents.Debug, { message });\n\t}\n}\n","import process from 'node:process';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { APIVersion, GatewayOpcodes } from 'discord-api-types/v10';\nimport { SimpleShardingStrategy } from '../strategies/sharding/SimpleShardingStrategy.js';\nimport { SimpleIdentifyThrottler } from '../throttling/SimpleIdentifyThrottler.js';\nimport type { SessionInfo, OptionalWebSocketManagerOptions, WebSocketManager } from '../ws/WebSocketManager.js';\nimport type { SendRateLimitState } from '../ws/WebSocketShard.js';\n\n/**\n * Valid encoding types\n */\nexport enum Encoding {\n\tJSON = 'json',\n}\n\n/**\n * Valid compression methods\n */\nexport enum CompressionMethod {\n\tZlibStream = 'zlib-stream',\n}\n\nexport const DefaultDeviceProperty = `@discordjs/ws 0.8.3` as `@discordjs/ws ${string}`;\n\nconst getDefaultSessionStore = lazy(() => new Collection());\n\n/**\n * Default options used by the manager\n */\nexport const DefaultWebSocketManagerOptions = {\n\tasync buildIdentifyThrottler(manager: WebSocketManager) {\n\t\tconst info = await manager.fetchGatewayInformation();\n\t\treturn new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency);\n\t},\n\tbuildStrategy: (manager) => new SimpleShardingStrategy(manager),\n\tshardCount: null,\n\tshardIds: null,\n\tlargeThreshold: null,\n\tinitialPresence: null,\n\tidentifyProperties: {\n\t\tbrowser: DefaultDeviceProperty,\n\t\tdevice: DefaultDeviceProperty,\n\t\tos: process.platform,\n\t},\n\tversion: APIVersion,\n\tencoding: Encoding.JSON,\n\tcompression: null,\n\tretrieveSessionInfo(shardId) {\n\t\tconst store = getDefaultSessionStore();\n\t\treturn store.get(shardId) ?? null;\n\t},\n\tupdateSessionInfo(shardId: number, info: SessionInfo | null) {\n\t\tconst store = getDefaultSessionStore();\n\t\tif (info) {\n\t\t\tstore.set(shardId, info);\n\t\t} else {\n\t\t\tstore.delete(shardId);\n\t\t}\n\t},\n\thandshakeTimeout: 30_000,\n\thelloTimeout: 60_000,\n\treadyTimeout: 15_000,\n} as const satisfies OptionalWebSocketManagerOptions;\n\nexport const ImportantGatewayOpcodes = new Set([\n\tGatewayOpcodes.Heartbeat,\n\tGatewayOpcodes.Identify,\n\tGatewayOpcodes.Resume,\n]);\n\nexport function getInitialSendRateLimitState(): SendRateLimitState {\n\treturn {\n\t\tremaining: 120,\n\t\tresetAt: Date.now() + 60_000,\n\t};\n}\n","import { Collection } from '@discordjs/collection';\nimport type { GatewaySendPayload } from 'discord-api-types/v10';\nimport type { WebSocketManager } from '../../ws/WebSocketManager.js';\nimport { WebSocketShard, WebSocketShardEvents, type WebSocketShardDestroyOptions } from '../../ws/WebSocketShard.js';\nimport { managerToFetchingStrategyOptions } from '../context/IContextFetchingStrategy.js';\nimport { SimpleContextFetchingStrategy } from '../context/SimpleContextFetchingStrategy.js';\nimport type { IShardingStrategy } from './IShardingStrategy.js';\n\n/**\n * Simple strategy that just spawns shards in the current process\n */\nexport class SimpleShardingStrategy implements IShardingStrategy {\n\tprivate readonly manager: WebSocketManager;\n\n\tprivate readonly shards = new Collection();\n\n\tpublic constructor(manager: WebSocketManager) {\n\t\tthis.manager = manager;\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.spawn}\n\t */\n\tpublic async spawn(shardIds: number[]) {\n\t\tconst strategyOptions = await managerToFetchingStrategyOptions(this.manager);\n\n\t\tfor (const shardId of shardIds) {\n\t\t\tconst strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions);\n\t\t\tconst shard = new WebSocketShard(strategy, shardId);\n\t\t\tfor (const event of Object.values(WebSocketShardEvents)) {\n\t\t\t\t// @ts-expect-error: Intentional\n\t\t\t\tshard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId }));\n\t\t\t}\n\n\t\t\tthis.shards.set(shardId, shard);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.connect}\n\t */\n\tpublic async connect() {\n\t\tconst promises = [];\n\n\t\tfor (const shard of this.shards.values()) {\n\t\t\tpromises.push(shard.connect());\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.destroy}\n\t */\n\tpublic async destroy(options?: Omit) {\n\t\tconst promises = [];\n\n\t\tfor (const shard of this.shards.values()) {\n\t\t\tpromises.push(shard.destroy(options));\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t\tthis.shards.clear();\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.send}\n\t */\n\tpublic async send(shardId: number, payload: GatewaySendPayload) {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} not found`);\n\t\t}\n\n\t\treturn shard.send(payload);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.fetchStatus}\n\t */\n\tpublic async fetchStatus() {\n\t\treturn this.shards.mapValues((shard) => shard.status);\n\t}\n}\n","import type { IIdentifyThrottler } from '../../throttling/IIdentifyThrottler.js';\nimport type { SessionInfo, WebSocketManager } from '../../ws/WebSocketManager.js';\nimport type { FetchingStrategyOptions, IContextFetchingStrategy } from './IContextFetchingStrategy.js';\n\nexport class SimpleContextFetchingStrategy implements IContextFetchingStrategy {\n\t// This strategy assumes every shard is running under the same process - therefore we need a single\n\t// IdentifyThrottler per manager.\n\tprivate static throttlerCache = new WeakMap();\n\n\tprivate static async ensureThrottler(manager: WebSocketManager): Promise {\n\t\tconst throttler = SimpleContextFetchingStrategy.throttlerCache.get(manager);\n\t\tif (throttler) {\n\t\t\treturn throttler;\n\t\t}\n\n\t\tconst newThrottler = await manager.options.buildIdentifyThrottler(manager);\n\t\tSimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler);\n\n\t\treturn newThrottler;\n\t}\n\n\tpublic constructor(private readonly manager: WebSocketManager, public readonly options: FetchingStrategyOptions) {}\n\n\tpublic async retrieveSessionInfo(shardId: number): Promise {\n\t\treturn this.manager.options.retrieveSessionInfo(shardId);\n\t}\n\n\tpublic updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null) {\n\t\treturn this.manager.options.updateSessionInfo(shardId, sessionInfo);\n\t}\n\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst throttler = await SimpleContextFetchingStrategy.ensureThrottler(this.manager);\n\t\tawait throttler.waitForIdentify(shardId, signal);\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport { Collection } from '@discordjs/collection';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport type { IIdentifyThrottler } from './IIdentifyThrottler.js';\n\n/**\n * The state of a rate limit key's identify queue.\n */\nexport interface IdentifyState {\n\tqueue: AsyncQueue;\n\tresetsAt: number;\n}\n\n/**\n * Local, in-memory identify throttler.\n */\nexport class SimpleIdentifyThrottler implements IIdentifyThrottler {\n\tprivate readonly states = new Collection();\n\n\tpublic constructor(private readonly maxConcurrency: number) {}\n\n\t/**\n\t * {@inheritDoc IIdentifyThrottler.waitForIdentify}\n\t */\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst key = shardId % this.maxConcurrency;\n\n\t\tconst state = this.states.ensure(key, () => {\n\t\t\treturn {\n\t\t\t\tqueue: new AsyncQueue(),\n\t\t\t\tresetsAt: Number.POSITIVE_INFINITY,\n\t\t\t};\n\t\t});\n\n\t\tawait state.queue.wait({ signal });\n\n\t\ttry {\n\t\t\tconst diff = state.resetsAt - Date.now();\n\t\t\tif (diff <= 5_000) {\n\t\t\t\t// To account for the latency the IDENTIFY payload goes through, we add a bit more wait time\n\t\t\t\tconst time = diff + Math.random() * 1_500;\n\t\t\t\tawait sleep(time);\n\t\t\t}\n\n\t\t\tstate.resetsAt = Date.now() + 5_000;\n\t\t} finally {\n\t\t\tstate.queue.shift();\n\t\t}\n\t}\n}\n","import { WorkerBootstrapper } from '../../utils/WorkerBootstrapper.js';\n\nconst bootstrapper = new WorkerBootstrapper();\nvoid bootstrapper.bootstrap();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,8BAAqD;AACrD,IAAAC,qBAA2B;;;ACD3B,IAAAC,8BAAyC;AACzC,IAAAC,qBAA2B;;;ACD3B,yBAAqB;AACrB,uBAA0C;AAC1C,iCAAuB;AACvB,wBAA2B;;;AC6B3B,eAAsB,iCAAiC,SAA6D;AAEnH,QAAM;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACJ,IAAI,QAAQ;AAGZ,SAAO;AAAA,IACN,GAAG;AAAA,IACH,oBAAoB,MAAM,QAAQ,wBAAwB;AAAA,I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;AAChC;AAAA,QACD;AAAA,MACD;AAAA,IACD,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAa,UAAU,UAAsC,CAAC,GAAkB;AAE/E,eAAW,WAAW,KAAK,KAAK,UAAU;AACzC,YAAM,QAAQ,IAAI,eAAe,IAAI,8BAA8B,KAAK,IAAI,GAAG,OAAO;AACtF,iBAAW,SAAS,QAAQ,iBAAiB,OAAO,OAAO,oBAAoB,GAAG;AAEjF,cAAM,GAAG,OAAO,CAAC,SAAS;AACzB,gBAAM,UAAgC;AAAA,YACrC;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACD;AACA,iDAAY,YAAY,OAAO;AAAA,QAChC,CAAC;AAAA,MACF;AAGA,YAAM,QAAQ,gBAAgB,KAAK;AACnC,WAAK,OAAO,IAAI,SAAS,KAAK;AAAA,IAC/B;AAGA,SAAK,kBAAkB;AAEvB,UAAM,UAAgC;AAAA,MACrC;AAAA,IACD;AACA,2CAAY,YAAY,OAAO;AAAA,EAChC;AACD;AA9Ia;;;AS/Bb,IAAM,eAAe,IAAI,mBAAmB;AAC5C,KAAK,aAAa,UAAU;","names":["import_node_worker_threads","import_collection","import_node_worker_threads","import_collection","resolve","payload","import_node_events","import_promises","import_collection","import_util","import_async_queue","import_v10","import_collection","import_collection","import_collection","sleep","process","WebSocketShardEvents","WebSocketShardDestroyRecovery","sleep","resolve","session"]} \ No newline at end of file diff --git a/node_modules/@discordjs/ws/dist/defaultWorker.mjs b/node_modules/@discordjs/ws/dist/defaultWorker.mjs new file mode 100644 index 0000000..96e9c3b --- /dev/null +++ b/node_modules/@discordjs/ws/dist/defaultWorker.mjs @@ -0,0 +1,964 @@ +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/utils/WorkerBootstrapper.ts +import { isMainThread as isMainThread2, parentPort as parentPort2, workerData } from "node:worker_threads"; +import { Collection as Collection7 } from "@discordjs/collection"; + +// src/strategies/context/WorkerContextFetchingStrategy.ts +import { isMainThread, parentPort } from "node:worker_threads"; +import { Collection as Collection2 } from "@discordjs/collection"; + +// src/strategies/sharding/WorkerShardingStrategy.ts +import { once } from "node:events"; +import { join, isAbsolute, resolve } from "node:path"; +import { Worker } from "node:worker_threads"; +import { Collection } from "@discordjs/collection"; + +// src/strategies/context/IContextFetchingStrategy.ts +async function managerToFetchingStrategyOptions(manager) { + const { + buildIdentifyThrottler, + buildStrategy, + retrieveSessionInfo, + updateSessionInfo, + shardCount, + shardIds, + rest, + ...managerOptions + } = manager.options; + return { + ...managerOptions, + gatewayInformation: await manager.fetchGatewayInformation(), + shardCount: await manager.getShardCount() + }; +} +__name(managerToFetchingStrategyOptions, "managerToFetchingStrategyOptions"); + +// src/strategies/context/WorkerContextFetchingStrategy.ts +var WorkerContextFetchingStrategy = class { + constructor(options) { + this.options = options; + if (isMainThread) { + throw new Error("Cannot instantiate WorkerContextFetchingStrategy on the main thread"); + } + parentPort.on("message", (payload) => { + if (payload.op === 3 /* SessionInfoResponse */) { + this.sessionPromises.get(payload.nonce)?.(payload.session); + this.sessionPromises.delete(payload.nonce); + } + if (payload.op === 4 /* ShardIdentifyResponse */) { + const promise = this.waitForIdentifyPromises.get(payload.nonce); + if (payload.ok) { + promise?.resolve(); + } else { + promise?.reject(); + } + this.waitForIdentifyPromises.delete(payload.nonce); + } + }); + } + sessionPromises = new Collection2(); + waitForIdentifyPromises = new Collection2(); + async retrieveSessionInfo(shardId) { + const nonce = Math.random(); + const payload = { + op: 3 /* RetrieveSessionInfo */, + shardId, + nonce + }; + const promise = new Promise((resolve2) => this.sessionPromises.set(nonce, resolve2)); + parentPort.postMessage(payload); + return promise; + } + updateSessionInfo(shardId, sessionInfo) { + const payload = { + op: 4 /* UpdateSessionInfo */, + shardId, + session: sessionInfo + }; + parentPort.postMessage(payload); + } + async waitForIdentify(shardId, signal) { + const nonce = Math.random(); + const payload = { + op: 5 /* WaitForIdentify */, + nonce, + shardId + }; + const promise = new Promise( + (resolve2, reject) => ( + // eslint-disable-next-line no-promise-executor-return + this.waitForIdentifyPromises.set(nonce, { resolve: resolve2, reject }) + ) + ); + parentPort.postMessage(payload); + const listener = /* @__PURE__ */ __name(() => { + const payload2 = { + op: 8 /* CancelIdentify */, + nonce + }; + parentPort.postMessage(payload2); + }, "listener"); + signal.addEventListener("abort", listener); + try { + await promise; + } finally { + signal.removeEventListener("abort", listener); + } + } +}; +__name(WorkerContextFetchingStrategy, "WorkerContextFetchingStrategy"); + +// src/ws/WebSocketShard.ts +import { Buffer as Buffer2 } from "node:buffer"; +import { once as once2 } from "node:events"; +import { clearInterval, clearTimeout, setInterval, setTimeout } from "node:timers"; +import { setTimeout as sleep2 } from "node:timers/promises"; +import { URLSearchParams } from "node:url"; +import { TextDecoder } from "node:util"; +import { inflate } from "node:zlib"; +import { Collection as Collection6 } from "@discordjs/collection"; +import { lazy as lazy2 } from "@discordjs/util"; +import { AsyncQueue as AsyncQueue2 } from "@sapphire/async-queue"; +import { AsyncEventEmitter } from "@vladfrangu/async_event_emitter"; +import { + GatewayCloseCodes, + GatewayDispatchEvents, + GatewayOpcodes as GatewayOpcodes2 +} from "discord-api-types/v10"; +import { WebSocket } from "ws"; + +// src/utils/constants.ts +import process from "node:process"; +import { Collection as Collection5 } from "@discordjs/collection"; +import { lazy } from "@discordjs/util"; +import { APIVersion, GatewayOpcodes } from "discord-api-types/v10"; + +// src/strategies/sharding/SimpleShardingStrategy.ts +import { Collection as Collection3 } from "@discordjs/collection"; + +// src/strategies/context/SimpleContextFetchingStrategy.ts +var _SimpleContextFetchingStrategy = class { + constructor(manager, options) { + this.manager = manager; + this.options = options; + } + static async ensureThrottler(manager) { + const throttler = _SimpleContextFetchingStrategy.throttlerCache.get(manager); + if (throttler) { + return throttler; + } + const newThrottler = await manager.options.buildIdentifyThrottler(manager); + _SimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler); + return newThrottler; + } + async retrieveSessionInfo(shardId) { + return this.manager.options.retrieveSessionInfo(shardId); + } + updateSessionInfo(shardId, sessionInfo) { + return this.manager.options.updateSessionInfo(shardId, sessionInfo); + } + async waitForIdentify(shardId, signal) { + const throttler = await _SimpleContextFetchingStrategy.ensureThrottler(this.manager); + await throttler.waitForIdentify(shardId, signal); + } +}; +var SimpleContextFetchingStrategy = _SimpleContextFetchingStrategy; +__name(SimpleContextFetchingStrategy, "SimpleContextFetchingStrategy"); +// This strategy assumes every shard is running under the same process - therefore we need a single +// IdentifyThrottler per manager. +__publicField(SimpleContextFetchingStrategy, "throttlerCache", /* @__PURE__ */ new WeakMap()); + +// src/strategies/sharding/SimpleShardingStrategy.ts +var SimpleShardingStrategy = class { + manager; + shards = new Collection3(); + constructor(manager) { + this.manager = manager; + } + /** + * {@inheritDoc IShardingStrategy.spawn} + */ + async spawn(shardIds) { + const strategyOptions = await managerToFetchingStrategyOptions(this.manager); + for (const shardId of shardIds) { + const strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions); + const shard = new WebSocketShard(strategy, shardId); + for (const event of Object.values(WebSocketShardEvents)) { + shard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId })); + } + this.shards.set(shardId, shard); + } + } + /** + * {@inheritDoc IShardingStrategy.connect} + */ + async connect() { + const promises = []; + for (const shard of this.shards.values()) { + promises.push(shard.connect()); + } + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.destroy} + */ + async destroy(options) { + const promises = []; + for (const shard of this.shards.values()) { + promises.push(shard.destroy(options)); + } + await Promise.all(promises); + this.shards.clear(); + } + /** + * {@inheritDoc IShardingStrategy.send} + */ + async send(shardId, payload) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} not found`); + } + return shard.send(payload); + } + /** + * {@inheritDoc IShardingStrategy.fetchStatus} + */ + async fetchStatus() { + return this.shards.mapValues((shard) => shard.status); + } +}; +__name(SimpleShardingStrategy, "SimpleShardingStrategy"); + +// src/throttling/SimpleIdentifyThrottler.ts +import { setTimeout as sleep } from "node:timers/promises"; +import { Collection as Collection4 } from "@discordjs/collection"; +import { AsyncQueue } from "@sapphire/async-queue"; +var SimpleIdentifyThrottler = class { + constructor(maxConcurrency) { + this.maxConcurrency = maxConcurrency; + } + states = new Collection4(); + /** + * {@inheritDoc IIdentifyThrottler.waitForIdentify} + */ + async waitForIdentify(shardId, signal) { + const key = shardId % this.maxConcurrency; + const state = this.states.ensure(key, () => { + return { + queue: new AsyncQueue(), + resetsAt: Number.POSITIVE_INFINITY + }; + }); + await state.queue.wait({ signal }); + try { + const diff = state.resetsAt - Date.now(); + if (diff <= 5e3) { + const time = diff + Math.random() * 1500; + await sleep(time); + } + state.resetsAt = Date.now() + 5e3; + } finally { + state.queue.shift(); + } + } +}; +__name(SimpleIdentifyThrottler, "SimpleIdentifyThrottler"); + +// src/utils/constants.ts +var DefaultDeviceProperty = `@discordjs/ws 0.8.3`; +var getDefaultSessionStore = lazy(() => new Collection5()); +var DefaultWebSocketManagerOptions = { + async buildIdentifyThrottler(manager) { + const info = await manager.fetchGatewayInformation(); + return new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency); + }, + buildStrategy: (manager) => new SimpleShardingStrategy(manager), + shardCount: null, + shardIds: null, + largeThreshold: null, + initialPresence: null, + identifyProperties: { + browser: DefaultDeviceProperty, + device: DefaultDeviceProperty, + os: process.platform + }, + version: APIVersion, + encoding: "json" /* JSON */, + compression: null, + retrieveSessionInfo(shardId) { + const store = getDefaultSessionStore(); + return store.get(shardId) ?? null; + }, + updateSessionInfo(shardId, info) { + const store = getDefaultSessionStore(); + if (info) { + store.set(shardId, info); + } else { + store.delete(shardId); + } + }, + handshakeTimeout: 3e4, + helloTimeout: 6e4, + readyTimeout: 15e3 +}; +var ImportantGatewayOpcodes = /* @__PURE__ */ new Set([ + GatewayOpcodes.Heartbeat, + GatewayOpcodes.Identify, + GatewayOpcodes.Resume +]); +function getInitialSendRateLimitState() { + return { + remaining: 120, + resetAt: Date.now() + 6e4 + }; +} +__name(getInitialSendRateLimitState, "getInitialSendRateLimitState"); + +// src/ws/WebSocketShard.ts +var getZlibSync = lazy2(async () => import("zlib-sync").then((mod) => mod.default).catch(() => null)); +var WebSocketShardEvents = /* @__PURE__ */ ((WebSocketShardEvents2) => { + WebSocketShardEvents2["Closed"] = "closed"; + WebSocketShardEvents2["Debug"] = "debug"; + WebSocketShardEvents2["Dispatch"] = "dispatch"; + WebSocketShardEvents2["Error"] = "error"; + WebSocketShardEvents2["HeartbeatComplete"] = "heartbeat"; + WebSocketShardEvents2["Hello"] = "hello"; + WebSocketShardEvents2["Ready"] = "ready"; + WebSocketShardEvents2["Resumed"] = "resumed"; + return WebSocketShardEvents2; +})(WebSocketShardEvents || {}); +var WebSocketShardDestroyRecovery = /* @__PURE__ */ ((WebSocketShardDestroyRecovery2) => { + WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Reconnect"] = 0] = "Reconnect"; + WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Resume"] = 1] = "Resume"; + return WebSocketShardDestroyRecovery2; +})(WebSocketShardDestroyRecovery || {}); +var WebSocketShard = class extends AsyncEventEmitter { + connection = null; + useIdentifyCompress = false; + inflate = null; + textDecoder = new TextDecoder(); + replayedEvents = 0; + isAck = true; + sendRateLimitState = getInitialSendRateLimitState(); + initialHeartbeatTimeoutController = null; + heartbeatInterval = null; + lastHeartbeatAt = -1; + // Indicates whether the shard has already resolved its original connect() call + initialConnectResolved = false; + // Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET) + failedToConnectDueToNetworkError = false; + sendQueue = new AsyncQueue2(); + timeoutAbortControllers = new Collection6(); + strategy; + id; + #status = 0 /* Idle */; + get status() { + return this.#status; + } + constructor(strategy, id) { + super(); + this.strategy = strategy; + this.id = id; + } + async connect() { + const promise = this.initialConnectResolved ? Promise.resolve() : once2(this, "ready" /* Ready */); + void this.internalConnect(); + await promise; + this.initialConnectResolved = true; + } + async internalConnect() { + if (this.#status !== 0 /* Idle */) { + throw new Error("Tried to connect a shard that wasn't idle"); + } + const { version, encoding, compression } = this.strategy.options; + const params = new URLSearchParams({ v: version, encoding }); + if (compression) { + const zlib = await getZlibSync(); + if (zlib) { + params.append("compress", compression); + this.inflate = new zlib.Inflate({ + chunkSize: 65535, + to: "string" + }); + } else if (!this.useIdentifyCompress) { + this.useIdentifyCompress = true; + console.warn( + "WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress" + ); + } + } + const session = await this.strategy.retrieveSessionInfo(this.id); + const url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`; + this.debug([`Connecting to ${url}`]); + const connection = new WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? void 0 }).on("message", this.onMessage.bind(this)).on("error", this.onError.bind(this)).on("close", this.onClose.bind(this)); + connection.binaryType = "arraybuffer"; + this.connection = connection; + this.#status = 1 /* Connecting */; + this.sendRateLimitState = getInitialSendRateLimitState(); + const { ok } = await this.waitForEvent("hello" /* Hello */, this.strategy.options.helloTimeout); + if (!ok) { + return; + } + if (session?.shardCount === this.strategy.options.shardCount) { + await this.resume(session); + } else { + await this.identify(); + } + } + async destroy(options = {}) { + if (this.#status === 0 /* Idle */) { + this.debug(["Tried to destroy a shard that was idle"]); + return; + } + if (!options.code) { + options.code = options.recover === 1 /* Resume */ ? 4200 /* Resuming */ : 1e3 /* Normal */; + } + this.debug([ + "Destroying shard", + `Reason: ${options.reason ?? "none"}`, + `Code: ${options.code}`, + `Recover: ${options.recover === void 0 ? "none" : WebSocketShardDestroyRecovery[options.recover]}` + ]); + this.isAck = true; + if (this.heartbeatInterval) { + clearInterval(this.heartbeatInterval); + } + if (this.initialHeartbeatTimeoutController) { + this.initialHeartbeatTimeoutController.abort(); + this.initialHeartbeatTimeoutController = null; + } + this.lastHeartbeatAt = -1; + for (const controller of this.timeoutAbortControllers.values()) { + controller.abort(); + } + this.timeoutAbortControllers.clear(); + this.failedToConnectDueToNetworkError = false; + if (options.recover !== 1 /* Resume */) { + await this.strategy.updateSessionInfo(this.id, null); + } + if (this.connection) { + this.connection.removeAllListeners("message"); + this.connection.removeAllListeners("close"); + const shouldClose = this.connection.readyState === WebSocket.OPEN; + this.debug([ + "Connection status during destroy", + `Needs closing: ${shouldClose}`, + `Ready state: ${this.connection.readyState}` + ]); + if (shouldClose) { + this.connection.close(options.code, options.reason); + await once2(this.connection, "close"); + this.emit("closed" /* Closed */, { code: options.code }); + } + this.connection.removeAllListeners("error"); + } else { + this.debug(["Destroying a shard that has no connection; please open an issue on GitHub"]); + } + this.#status = 0 /* Idle */; + if (options.recover !== void 0) { + await sleep2(500); + return this.internalConnect(); + } + } + async waitForEvent(event, timeoutDuration) { + this.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : "indefinitely"}`]); + const timeoutController = new AbortController(); + const timeout = timeoutDuration ? setTimeout(() => timeoutController.abort(), timeoutDuration).unref() : null; + this.timeoutAbortControllers.set(event, timeoutController); + const closeController = new AbortController(); + try { + const closed = await Promise.race([ + once2(this, event, { signal: timeoutController.signal }).then(() => false), + once2(this, "closed" /* Closed */, { signal: closeController.signal }).then(() => true) + ]); + return { ok: !closed }; + } catch { + void this.destroy({ + code: 1e3 /* Normal */, + reason: "Something timed out or went wrong while waiting for an event", + recover: 0 /* Reconnect */ + }); + return { ok: false }; + } finally { + if (timeout) { + clearTimeout(timeout); + } + this.timeoutAbortControllers.delete(event); + if (!closeController.signal.aborted) { + closeController.abort(); + } + } + } + async send(payload) { + if (!this.connection) { + throw new Error("WebSocketShard wasn't connected"); + } + if (this.#status !== 3 /* Ready */ && !ImportantGatewayOpcodes.has(payload.op)) { + this.debug(["Tried to send a non-crucial payload before the shard was ready, waiting"]); + try { + await once2(this, "ready" /* Ready */); + } catch { + return this.send(payload); + } + } + await this.sendQueue.wait(); + if (--this.sendRateLimitState.remaining <= 0) { + const now = Date.now(); + if (this.sendRateLimitState.resetAt > now) { + const sleepFor = this.sendRateLimitState.resetAt - now; + this.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]); + const controller = new AbortController(); + const interrupted = await Promise.race([ + sleep2(sleepFor).then(() => false), + once2(this, "closed" /* Closed */, { signal: controller.signal }).then(() => true) + ]); + if (interrupted) { + this.debug(["Connection closed while waiting for the send rate limit to reset, re-queueing payload"]); + this.sendQueue.shift(); + return this.send(payload); + } + controller.abort(); + } + this.sendRateLimitState = getInitialSendRateLimitState(); + } + this.sendQueue.shift(); + this.connection.send(JSON.stringify(payload)); + } + async identify() { + this.debug(["Waiting for identify throttle"]); + const controller = new AbortController(); + const closeHandler = /* @__PURE__ */ __name(() => { + controller.abort(); + }, "closeHandler"); + this.on("closed" /* Closed */, closeHandler); + try { + await this.strategy.waitForIdentify(this.id, controller.signal); + } catch { + this.debug(["Was waiting for an identify, but the shard closed in the meantime"]); + return; + } finally { + this.off("closed" /* Closed */, closeHandler); + } + this.debug([ + "Identifying", + `shard id: ${this.id.toString()}`, + `shard count: ${this.strategy.options.shardCount}`, + `intents: ${this.strategy.options.intents}`, + `compression: ${this.inflate ? "zlib-stream" : this.useIdentifyCompress ? "identify" : "none"}` + ]); + const d = { + token: this.strategy.options.token, + properties: this.strategy.options.identifyProperties, + intents: this.strategy.options.intents, + compress: this.useIdentifyCompress, + shard: [this.id, this.strategy.options.shardCount] + }; + if (this.strategy.options.largeThreshold) { + d.large_threshold = this.strategy.options.largeThreshold; + } + if (this.strategy.options.initialPresence) { + d.presence = this.strategy.options.initialPresence; + } + await this.send({ + op: GatewayOpcodes2.Identify, + d + }); + await this.waitForEvent("ready" /* Ready */, this.strategy.options.readyTimeout); + } + async resume(session) { + this.debug([ + "Resuming session", + `resume url: ${session.resumeURL}`, + `sequence: ${session.sequence}`, + `shard id: ${this.id.toString()}` + ]); + this.#status = 2 /* Resuming */; + this.replayedEvents = 0; + return this.send({ + op: GatewayOpcodes2.Resume, + d: { + token: this.strategy.options.token, + seq: session.sequence, + session_id: session.sessionId + } + }); + } + async heartbeat(requested = false) { + if (!this.isAck && !requested) { + return this.destroy({ reason: "Zombie connection", recover: 1 /* Resume */ }); + } + const session = await this.strategy.retrieveSessionInfo(this.id); + await this.send({ + op: GatewayOpcodes2.Heartbeat, + d: session?.sequence ?? null + }); + this.lastHeartbeatAt = Date.now(); + this.isAck = false; + } + async unpackMessage(data, isBinary) { + const decompressable = new Uint8Array(data); + if (!isBinary) { + return JSON.parse(this.textDecoder.decode(decompressable)); + } + if (this.useIdentifyCompress) { + return new Promise((resolve2, reject) => { + inflate(decompressable, { chunkSize: 65535 }, (err, result) => { + if (err) { + reject(err); + return; + } + resolve2(JSON.parse(this.textDecoder.decode(result))); + }); + }); + } + if (this.inflate) { + const l = decompressable.length; + const flush = l >= 4 && decompressable[l - 4] === 0 && decompressable[l - 3] === 0 && decompressable[l - 2] === 255 && decompressable[l - 1] === 255; + const zlib = await getZlibSync(); + this.inflate.push(Buffer2.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH); + if (this.inflate.err) { + this.emit("error" /* Error */, { + error: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ""}`) + }); + } + if (!flush) { + return null; + } + const { result } = this.inflate; + if (!result) { + return null; + } + return JSON.parse(typeof result === "string" ? result : this.textDecoder.decode(result)); + } + this.debug([ + "Received a message we were unable to decompress", + `isBinary: ${isBinary.toString()}`, + `useIdentifyCompress: ${this.useIdentifyCompress.toString()}`, + `inflate: ${Boolean(this.inflate).toString()}` + ]); + return null; + } + async onMessage(data, isBinary) { + const payload = await this.unpackMessage(data, isBinary); + if (!payload) { + return; + } + switch (payload.op) { + case GatewayOpcodes2.Dispatch: { + if (this.#status === 2 /* Resuming */) { + this.replayedEvents++; + } + switch (payload.t) { + case GatewayDispatchEvents.Ready: { + this.#status = 3 /* Ready */; + const session2 = { + sequence: payload.s, + sessionId: payload.d.session_id, + shardId: this.id, + shardCount: this.strategy.options.shardCount, + resumeURL: payload.d.resume_gateway_url + }; + await this.strategy.updateSessionInfo(this.id, session2); + this.emit("ready" /* Ready */, { data: payload.d }); + break; + } + case GatewayDispatchEvents.Resumed: { + this.#status = 3 /* Ready */; + this.debug([`Resumed and replayed ${this.replayedEvents} events`]); + this.emit("resumed" /* Resumed */); + break; + } + default: { + break; + } + } + const session = await this.strategy.retrieveSessionInfo(this.id); + if (session) { + if (payload.s > session.sequence) { + await this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s }); + } + } else { + this.debug([ + `Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect` + ]); + } + this.emit("dispatch" /* Dispatch */, { data: payload }); + break; + } + case GatewayOpcodes2.Heartbeat: { + await this.heartbeat(true); + break; + } + case GatewayOpcodes2.Reconnect: { + await this.destroy({ + reason: "Told to reconnect by Discord", + recover: 1 /* Resume */ + }); + break; + } + case GatewayOpcodes2.InvalidSession: { + this.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]); + const session = await this.strategy.retrieveSessionInfo(this.id); + if (payload.d && session) { + await this.resume(session); + } else { + await this.destroy({ + reason: "Invalid session", + recover: 0 /* Reconnect */ + }); + } + break; + } + case GatewayOpcodes2.Hello: { + this.emit("hello" /* Hello */); + const jitter = Math.random(); + const firstWait = Math.floor(payload.d.heartbeat_interval * jitter); + this.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]); + try { + const controller = new AbortController(); + this.initialHeartbeatTimeoutController = controller; + await sleep2(firstWait, void 0, { signal: controller.signal }); + } catch { + this.debug(["Cancelled initial heartbeat due to #destroy being called"]); + return; + } finally { + this.initialHeartbeatTimeoutController = null; + } + await this.heartbeat(); + this.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]); + this.heartbeatInterval = setInterval(() => void this.heartbeat(), payload.d.heartbeat_interval); + break; + } + case GatewayOpcodes2.HeartbeatAck: { + this.isAck = true; + const ackAt = Date.now(); + this.emit("heartbeat" /* HeartbeatComplete */, { + ackAt, + heartbeatAt: this.lastHeartbeatAt, + latency: ackAt - this.lastHeartbeatAt + }); + break; + } + } + } + onError(error) { + if ("code" in error && ["ECONNRESET", "ECONNREFUSED"].includes(error.code)) { + this.debug(["Failed to connect to the gateway URL specified due to a network error"]); + this.failedToConnectDueToNetworkError = true; + return; + } + this.emit("error" /* Error */, { error }); + } + async onClose(code) { + this.emit("closed" /* Closed */, { code }); + switch (code) { + case 1e3 /* Normal */: { + return this.destroy({ + code, + reason: "Got disconnected by Discord", + recover: 0 /* Reconnect */ + }); + } + case 4200 /* Resuming */: { + break; + } + case GatewayCloseCodes.UnknownError: { + this.debug([`An unknown error occurred: ${code}`]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case GatewayCloseCodes.UnknownOpcode: { + this.debug(["An invalid opcode was sent to Discord."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case GatewayCloseCodes.DecodeError: { + this.debug(["An invalid payload was sent to Discord."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case GatewayCloseCodes.NotAuthenticated: { + this.debug(["A request was somehow sent before the identify/resume payload."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case GatewayCloseCodes.AuthenticationFailed: { + throw new Error("Authentication failed"); + } + case GatewayCloseCodes.AlreadyAuthenticated: { + this.debug(["More than one auth payload was sent."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case GatewayCloseCodes.InvalidSeq: { + this.debug(["An invalid sequence was sent."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case GatewayCloseCodes.RateLimited: { + this.debug(["The WebSocket rate limit has been hit, this should never happen"]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case GatewayCloseCodes.SessionTimedOut: { + this.debug(["Session timed out."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case GatewayCloseCodes.InvalidShard: { + throw new Error("Invalid shard"); + } + case GatewayCloseCodes.ShardingRequired: { + throw new Error("Sharding is required"); + } + case GatewayCloseCodes.InvalidAPIVersion: { + throw new Error("Used an invalid API version"); + } + case GatewayCloseCodes.InvalidIntents: { + throw new Error("Used invalid intents"); + } + case GatewayCloseCodes.DisallowedIntents: { + throw new Error("Used disallowed intents"); + } + default: { + this.debug([ + `The gateway closed with an unexpected code ${code}, attempting to ${this.failedToConnectDueToNetworkError ? "reconnect" : "resume"}.` + ]); + return this.destroy({ + code, + recover: this.failedToConnectDueToNetworkError ? 0 /* Reconnect */ : 1 /* Resume */ + }); + } + } + } + debug(messages) { + const message = `${messages[0]}${messages.length > 1 ? ` +${messages.slice(1).map((m) => ` ${m}`).join("\n")}` : ""}`; + this.emit("debug" /* Debug */, { message }); + } +}; +__name(WebSocketShard, "WebSocketShard"); + +// src/utils/WorkerBootstrapper.ts +var WorkerBootstrapper = class { + /** + * The data passed to the worker thread + */ + data = workerData; + /** + * The shards that are managed by this worker + */ + shards = new Collection7(); + constructor() { + if (isMainThread2) { + throw new Error("Expected WorkerBootstrap to not be used within the main thread"); + } + } + /** + * Helper method to initiate a shard's connection process + */ + async connect(shardId) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} does not exist`); + } + await shard.connect(); + } + /** + * Helper method to destroy a shard + */ + async destroy(shardId, options) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} does not exist`); + } + await shard.destroy(options); + } + /** + * Helper method to attach event listeners to the parentPort + */ + setupThreadEvents() { + parentPort2.on("messageerror", (err) => { + throw err; + }).on("message", async (payload) => { + switch (payload.op) { + case 0 /* Connect */: { + await this.connect(payload.shardId); + const response = { + op: 0 /* Connected */, + shardId: payload.shardId + }; + parentPort2.postMessage(response); + break; + } + case 1 /* Destroy */: { + await this.destroy(payload.shardId, payload.options); + const response = { + op: 1 /* Destroyed */, + shardId: payload.shardId + }; + parentPort2.postMessage(response); + break; + } + case 2 /* Send */: { + const shard = this.shards.get(payload.shardId); + if (!shard) { + throw new RangeError(`Shard ${payload.shardId} does not exist`); + } + await shard.send(payload.payload); + break; + } + case 3 /* SessionInfoResponse */: { + break; + } + case 4 /* ShardIdentifyResponse */: { + break; + } + case 5 /* FetchStatus */: { + const shard = this.shards.get(payload.shardId); + if (!shard) { + throw new Error(`Shard ${payload.shardId} does not exist`); + } + const response = { + op: 6 /* FetchStatusResponse */, + status: shard.status, + nonce: payload.nonce + }; + parentPort2.postMessage(response); + break; + } + } + }); + } + /** + * Bootstraps the worker thread with the provided options + */ + async bootstrap(options = {}) { + for (const shardId of this.data.shardIds) { + const shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId); + for (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) { + shard.on(event, (data) => { + const payload = { + op: 2 /* Event */, + event, + data, + shardId + }; + parentPort2.postMessage(payload); + }); + } + await options.shardCallback?.(shard); + this.shards.set(shardId, shard); + } + this.setupThreadEvents(); + const message = { + op: 7 /* WorkerReady */ + }; + parentPort2.postMessage(message); + } +}; +__name(WorkerBootstrapper, "WorkerBootstrapper"); + +// src/strategies/sharding/defaultWorker.ts +var bootstrapper = new WorkerBootstrapper(); +void bootstrapper.bootstrap(); +//# sourceMappingURL=defaultWorker.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/ws/dist/defaultWorker.mjs.map b/node_modules/@discordjs/ws/dist/defaultWorker.mjs.map new file mode 100644 index 0000000..e690f2c --- /dev/null +++ b/node_modules/@discordjs/ws/dist/defaultWorker.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/utils/WorkerBootstrapper.ts","../src/strategies/context/WorkerContextFetchingStrategy.ts","../src/strategies/sharding/WorkerShardingStrategy.ts","../src/strategies/context/IContextFetchingStrategy.ts","../src/ws/WebSocketShard.ts","../src/utils/constants.ts","../src/strategies/sharding/SimpleShardingStrategy.ts","../src/strategies/context/SimpleContextFetchingStrategy.ts","../src/throttling/SimpleIdentifyThrottler.ts","../src/strategies/sharding/defaultWorker.ts"],"sourcesContent":["import { isMainThread, parentPort, workerData } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { Awaitable } from '@discordjs/util';\nimport { WorkerContextFetchingStrategy } from '../strategies/context/WorkerContextFetchingStrategy.js';\nimport {\n\tWorkerReceivePayloadOp,\n\tWorkerSendPayloadOp,\n\ttype WorkerData,\n\ttype WorkerReceivePayload,\n\ttype WorkerSendPayload,\n} from '../strategies/sharding/WorkerShardingStrategy.js';\nimport type { WebSocketShardDestroyOptions } from '../ws/WebSocketShard.js';\nimport { WebSocketShardEvents, WebSocketShard } from '../ws/WebSocketShard.js';\n\n/**\n * Options for bootstrapping the worker\n */\nexport interface BootstrapOptions {\n\t/**\n\t * Shard events to just arbitrarily forward to the parent thread for the manager to emit\n\t * Note: By default, this will include ALL events\n\t * you most likely want to handle dispatch within the worker itself\n\t */\n\tforwardEvents?: WebSocketShardEvents[];\n\t/**\n\t * Function to call when a shard is created for additional setup\n\t */\n\tshardCallback?(shard: WebSocketShard): Awaitable;\n}\n\n/**\n * Utility class for bootstrapping a worker thread to be used for sharding\n */\nexport class WorkerBootstrapper {\n\t/**\n\t * The data passed to the worker thread\n\t */\n\tprotected readonly data = workerData as WorkerData;\n\n\t/**\n\t * The shards that are managed by this worker\n\t */\n\tprotected readonly shards = new Collection();\n\n\tpublic constructor() {\n\t\tif (isMainThread) {\n\t\t\tthrow new Error('Expected WorkerBootstrap to not be used within the main thread');\n\t\t}\n\t}\n\n\t/**\n\t * Helper method to initiate a shard's connection process\n\t */\n\tprotected async connect(shardId: number): Promise {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} does not exist`);\n\t\t}\n\n\t\tawait shard.connect();\n\t}\n\n\t/**\n\t * Helper method to destroy a shard\n\t */\n\tprotected async destroy(shardId: number, options?: WebSocketShardDestroyOptions): Promise {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} does not exist`);\n\t\t}\n\n\t\tawait shard.destroy(options);\n\t}\n\n\t/**\n\t * Helper method to attach event listeners to the parentPort\n\t */\n\tprotected setupThreadEvents(): void {\n\t\tparentPort!\n\t\t\t.on('messageerror', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('message', async (payload: WorkerSendPayload) => {\n\t\t\t\tswitch (payload.op) {\n\t\t\t\t\tcase WorkerSendPayloadOp.Connect: {\n\t\t\t\t\t\tawait this.connect(payload.shardId);\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.Connected,\n\t\t\t\t\t\t\tshardId: payload.shardId,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.Destroy: {\n\t\t\t\t\t\tawait this.destroy(payload.shardId, payload.options);\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.Destroyed,\n\t\t\t\t\t\t\tshardId: payload.shardId,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.Send: {\n\t\t\t\t\t\tconst shard = this.shards.get(payload.shardId);\n\t\t\t\t\t\tif (!shard) {\n\t\t\t\t\t\t\tthrow new RangeError(`Shard ${payload.shardId} does not exist`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait shard.send(payload.payload);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.SessionInfoResponse: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.ShardIdentifyResponse: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.FetchStatus: {\n\t\t\t\t\t\tconst shard = this.shards.get(payload.shardId);\n\t\t\t\t\t\tif (!shard) {\n\t\t\t\t\t\t\tthrow new Error(`Shard ${payload.shardId} does not exist`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.FetchStatusResponse,\n\t\t\t\t\t\t\tstatus: shard.status,\n\t\t\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t}\n\n\t/**\n\t * Bootstraps the worker thread with the provided options\n\t */\n\tpublic async bootstrap(options: Readonly = {}): Promise {\n\t\t// Start by initializing the shards\n\t\tfor (const shardId of this.data.shardIds) {\n\t\t\tconst shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId);\n\t\t\tfor (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) {\n\t\t\t\t// @ts-expect-error: Event types incompatible\n\t\t\t\tshard.on(event, (data) => {\n\t\t\t\t\tconst payload: WorkerReceivePayload = {\n\t\t\t\t\t\top: WorkerReceivePayloadOp.Event,\n\t\t\t\t\t\tevent,\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\tshardId,\n\t\t\t\t\t};\n\t\t\t\t\tparentPort!.postMessage(payload);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Any additional setup the user might want to do\n\t\t\tawait options.shardCallback?.(shard);\n\t\t\tthis.shards.set(shardId, shard);\n\t\t}\n\n\t\t// Lastly, start listening to messages from the parent thread\n\t\tthis.setupThreadEvents();\n\n\t\tconst message: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.WorkerReady,\n\t\t};\n\t\tparentPort!.postMessage(message);\n\t}\n}\n","import { isMainThread, parentPort } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { SessionInfo } from '../../ws/WebSocketManager.js';\nimport {\n\tWorkerReceivePayloadOp,\n\tWorkerSendPayloadOp,\n\ttype WorkerReceivePayload,\n\ttype WorkerSendPayload,\n} from '../sharding/WorkerShardingStrategy.js';\nimport type { FetchingStrategyOptions, IContextFetchingStrategy } from './IContextFetchingStrategy.js';\n\n// Because the global types are incomplete for whatever reason\ninterface PolyFillAbortSignal {\n\treadonly aborted: boolean;\n\taddEventListener(type: 'abort', listener: () => void): void;\n\tremoveEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport class WorkerContextFetchingStrategy implements IContextFetchingStrategy {\n\tprivate readonly sessionPromises = new Collection void>();\n\n\tprivate readonly waitForIdentifyPromises = new Collection();\n\n\tpublic constructor(public readonly options: FetchingStrategyOptions) {\n\t\tif (isMainThread) {\n\t\t\tthrow new Error('Cannot instantiate WorkerContextFetchingStrategy on the main thread');\n\t\t}\n\n\t\tparentPort!.on('message', (payload: WorkerSendPayload) => {\n\t\t\tif (payload.op === WorkerSendPayloadOp.SessionInfoResponse) {\n\t\t\t\tthis.sessionPromises.get(payload.nonce)?.(payload.session);\n\t\t\t\tthis.sessionPromises.delete(payload.nonce);\n\t\t\t}\n\n\t\t\tif (payload.op === WorkerSendPayloadOp.ShardIdentifyResponse) {\n\t\t\t\tconst promise = this.waitForIdentifyPromises.get(payload.nonce);\n\t\t\t\tif (payload.ok) {\n\t\t\t\t\tpromise?.resolve();\n\t\t\t\t} else {\n\t\t\t\t\tpromise?.reject();\n\t\t\t\t}\n\n\t\t\t\tthis.waitForIdentifyPromises.delete(payload.nonce);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async retrieveSessionInfo(shardId: number): Promise {\n\t\tconst nonce = Math.random();\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.RetrieveSessionInfo,\n\t\t\tshardId,\n\t\t\tnonce,\n\t\t};\n\t\t// eslint-disable-next-line no-promise-executor-return\n\t\tconst promise = new Promise((resolve) => this.sessionPromises.set(nonce, resolve));\n\t\tparentPort!.postMessage(payload);\n\t\treturn promise;\n\t}\n\n\tpublic updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null) {\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.UpdateSessionInfo,\n\t\t\tshardId,\n\t\t\tsession: sessionInfo,\n\t\t};\n\t\tparentPort!.postMessage(payload);\n\t}\n\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst nonce = Math.random();\n\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.WaitForIdentify,\n\t\t\tnonce,\n\t\t\tshardId,\n\t\t};\n\t\tconst promise = new Promise((resolve, reject) =>\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tthis.waitForIdentifyPromises.set(nonce, { resolve, reject }),\n\t\t);\n\n\t\tparentPort!.postMessage(payload);\n\n\t\tconst listener = () => {\n\t\t\tconst payload: WorkerReceivePayload = {\n\t\t\t\top: WorkerReceivePayloadOp.CancelIdentify,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\tparentPort!.postMessage(payload);\n\t\t};\n\n\t\t(signal as unknown as PolyFillAbortSignal).addEventListener('abort', listener);\n\n\t\ttry {\n\t\t\tawait promise;\n\t\t} finally {\n\t\t\t(signal as unknown as PolyFillAbortSignal).removeEventListener('abort', listener);\n\t\t}\n\t}\n}\n","import { once } from 'node:events';\nimport { join, isAbsolute, resolve } from 'node:path';\nimport { Worker } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { GatewaySendPayload } from 'discord-api-types/v10';\nimport type { IIdentifyThrottler } from '../../throttling/IIdentifyThrottler.js';\nimport type { SessionInfo, WebSocketManager } from '../../ws/WebSocketManager.js';\nimport type {\n\tWebSocketShardDestroyOptions,\n\tWebSocketShardEvents,\n\tWebSocketShardStatus,\n} from '../../ws/WebSocketShard.js';\nimport { managerToFetchingStrategyOptions, type FetchingStrategyOptions } from '../context/IContextFetchingStrategy.js';\nimport type { IShardingStrategy } from './IShardingStrategy.js';\n\nexport interface WorkerData extends FetchingStrategyOptions {\n\tshardIds: number[];\n}\n\nexport enum WorkerSendPayloadOp {\n\tConnect,\n\tDestroy,\n\tSend,\n\tSessionInfoResponse,\n\tShardIdentifyResponse,\n\tFetchStatus,\n}\n\nexport type WorkerSendPayload =\n\t| { nonce: number; ok: boolean; op: WorkerSendPayloadOp.ShardIdentifyResponse }\n\t| { nonce: number; op: WorkerSendPayloadOp.FetchStatus; shardId: number }\n\t| { nonce: number; op: WorkerSendPayloadOp.SessionInfoResponse; session: SessionInfo | null }\n\t| { op: WorkerSendPayloadOp.Connect; shardId: number }\n\t| { op: WorkerSendPayloadOp.Destroy; options?: WebSocketShardDestroyOptions; shardId: number }\n\t| { op: WorkerSendPayloadOp.Send; payload: GatewaySendPayload; shardId: number };\n\nexport enum WorkerReceivePayloadOp {\n\tConnected,\n\tDestroyed,\n\tEvent,\n\tRetrieveSessionInfo,\n\tUpdateSessionInfo,\n\tWaitForIdentify,\n\tFetchStatusResponse,\n\tWorkerReady,\n\tCancelIdentify,\n}\n\nexport type WorkerReceivePayload =\n\t// Can't seem to get a type-safe union based off of the event, so I'm sadly leaving data as any for now\n\t| { data: any; event: WebSocketShardEvents; op: WorkerReceivePayloadOp.Event; shardId: number }\n\t| { nonce: number; op: WorkerReceivePayloadOp.CancelIdentify }\n\t| { nonce: number; op: WorkerReceivePayloadOp.FetchStatusResponse; status: WebSocketShardStatus }\n\t| { nonce: number; op: WorkerReceivePayloadOp.RetrieveSessionInfo; shardId: number }\n\t| { nonce: number; op: WorkerReceivePayloadOp.WaitForIdentify; shardId: number }\n\t| { op: WorkerReceivePayloadOp.Connected; shardId: number }\n\t| { op: WorkerReceivePayloadOp.Destroyed; shardId: number }\n\t| { op: WorkerReceivePayloadOp.UpdateSessionInfo; session: SessionInfo | null; shardId: number }\n\t| { op: WorkerReceivePayloadOp.WorkerReady };\n\n/**\n * Options for a {@link WorkerShardingStrategy}\n */\nexport interface WorkerShardingStrategyOptions {\n\t/**\n\t * Dictates how many shards should be spawned per worker thread.\n\t */\n\tshardsPerWorker: number | 'all';\n\t/**\n\t * Path to the worker file to use. The worker requires quite a bit of setup, it is recommended you leverage the {@link WorkerBootstrapper} class.\n\t */\n\tworkerPath?: string;\n}\n\n/**\n * Strategy used to spawn threads in worker_threads\n */\nexport class WorkerShardingStrategy implements IShardingStrategy {\n\tprivate readonly manager: WebSocketManager;\n\n\tprivate readonly options: WorkerShardingStrategyOptions;\n\n\t#workers: Worker[] = [];\n\n\treadonly #workerByShardId = new Collection();\n\n\tprivate readonly connectPromises = new Collection void>();\n\n\tprivate readonly destroyPromises = new Collection void>();\n\n\tprivate readonly fetchStatusPromises = new Collection void>();\n\n\tprivate readonly waitForIdentifyControllers = new Collection();\n\n\tprivate throttler?: IIdentifyThrottler;\n\n\tpublic constructor(manager: WebSocketManager, options: WorkerShardingStrategyOptions) {\n\t\tthis.manager = manager;\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.spawn}\n\t */\n\tpublic async spawn(shardIds: number[]) {\n\t\tconst shardsPerWorker = this.options.shardsPerWorker === 'all' ? shardIds.length : this.options.shardsPerWorker;\n\t\tconst strategyOptions = await managerToFetchingStrategyOptions(this.manager);\n\n\t\tconst loops = Math.ceil(shardIds.length / shardsPerWorker);\n\t\tconst promises: Promise[] = [];\n\n\t\tfor (let idx = 0; idx < loops; idx++) {\n\t\t\tconst slice = shardIds.slice(idx * shardsPerWorker, (idx + 1) * shardsPerWorker);\n\t\t\tconst workerData: WorkerData = {\n\t\t\t\t...strategyOptions,\n\t\t\t\tshardIds: slice,\n\t\t\t};\n\n\t\t\tpromises.push(this.setupWorker(workerData));\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.connect}\n\t */\n\tpublic async connect() {\n\t\tconst promises = [];\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.Connect,\n\t\t\t\tshardId,\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tconst promise = new Promise((resolve) => this.connectPromises.set(shardId, resolve));\n\t\t\tworker.postMessage(payload);\n\t\t\tpromises.push(promise);\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.destroy}\n\t */\n\tpublic async destroy(options: Omit = {}) {\n\t\tconst promises = [];\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.Destroy,\n\t\t\t\tshardId,\n\t\t\t\toptions,\n\t\t\t};\n\n\t\t\tpromises.push(\n\t\t\t\t// eslint-disable-next-line no-promise-executor-return, promise/prefer-await-to-then\n\t\t\t\tnew Promise((resolve) => this.destroyPromises.set(shardId, resolve)).then(async () => worker.terminate()),\n\t\t\t);\n\t\t\tworker.postMessage(payload);\n\t\t}\n\n\t\tthis.#workers = [];\n\t\tthis.#workerByShardId.clear();\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.send}\n\t */\n\tpublic send(shardId: number, data: GatewaySendPayload) {\n\t\tconst worker = this.#workerByShardId.get(shardId);\n\t\tif (!worker) {\n\t\t\tthrow new Error(`No worker found for shard ${shardId}`);\n\t\t}\n\n\t\tconst payload: WorkerSendPayload = {\n\t\t\top: WorkerSendPayloadOp.Send,\n\t\t\tshardId,\n\t\t\tpayload: data,\n\t\t};\n\t\tworker.postMessage(payload);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.fetchStatus}\n\t */\n\tpublic async fetchStatus() {\n\t\tconst statuses = new Collection();\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst nonce = Math.random();\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.FetchStatus,\n\t\t\t\tshardId,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tconst promise = new Promise((resolve) => this.fetchStatusPromises.set(nonce, resolve));\n\t\t\tworker.postMessage(payload);\n\n\t\t\tconst status = await promise;\n\t\t\tstatuses.set(shardId, status);\n\t\t}\n\n\t\treturn statuses;\n\t}\n\n\tprivate async setupWorker(workerData: WorkerData) {\n\t\tconst worker = new Worker(this.resolveWorkerPath(), { workerData });\n\n\t\tawait once(worker, 'online');\n\t\t// We do this in case the user has any potentially long running code in their worker\n\t\tawait this.waitForWorkerReady(worker);\n\n\t\tworker\n\t\t\t.on('error', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('messageerror', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('message', async (payload: WorkerReceivePayload) => this.onMessage(worker, payload));\n\n\t\tthis.#workers.push(worker);\n\t\tfor (const shardId of workerData.shardIds) {\n\t\t\tthis.#workerByShardId.set(shardId, worker);\n\t\t}\n\t}\n\n\tprivate resolveWorkerPath(): string {\n\t\tconst path = this.options.workerPath;\n\n\t\tif (!path) {\n\t\t\treturn join(__dirname, 'defaultWorker.js');\n\t\t}\n\n\t\tif (isAbsolute(path)) {\n\t\t\treturn path;\n\t\t}\n\n\t\tif (/^\\.\\.?[/\\\\]/.test(path)) {\n\t\t\treturn resolve(path);\n\t\t}\n\n\t\ttry {\n\t\t\treturn require.resolve(path);\n\t\t} catch {\n\t\t\treturn resolve(path);\n\t\t}\n\t}\n\n\tprivate async waitForWorkerReady(worker: Worker): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst handler = (payload: WorkerReceivePayload) => {\n\t\t\t\tif (payload.op === WorkerReceivePayloadOp.WorkerReady) {\n\t\t\t\t\tresolve();\n\t\t\t\t\tworker.off('message', handler);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tworker.on('message', handler);\n\t\t});\n\t}\n\n\tprivate async onMessage(worker: Worker, payload: WorkerReceivePayload) {\n\t\tswitch (payload.op) {\n\t\t\tcase WorkerReceivePayloadOp.Connected: {\n\t\t\t\tthis.connectPromises.get(payload.shardId)?.();\n\t\t\t\tthis.connectPromises.delete(payload.shardId);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.Destroyed: {\n\t\t\t\tthis.destroyPromises.get(payload.shardId)?.();\n\t\t\t\tthis.destroyPromises.delete(payload.shardId);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.Event: {\n\t\t\t\tthis.manager.emit(payload.event, { ...payload.data, shardId: payload.shardId });\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.RetrieveSessionInfo: {\n\t\t\t\tconst session = await this.manager.options.retrieveSessionInfo(payload.shardId);\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.SessionInfoResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tsession,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.UpdateSessionInfo: {\n\t\t\t\tawait this.manager.options.updateSessionInfo(payload.shardId, payload.session);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.WaitForIdentify: {\n\t\t\t\tconst throttler = await this.ensureThrottler();\n\n\t\t\t\t// If this rejects it means we aborted, in which case we reply elsewhere.\n\t\t\t\ttry {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\tthis.waitForIdentifyControllers.set(payload.nonce, controller);\n\t\t\t\t\tawait throttler.waitForIdentify(payload.shardId, controller.signal);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.ShardIdentifyResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tok: true,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.FetchStatusResponse: {\n\t\t\t\tthis.fetchStatusPromises.get(payload.nonce)?.(payload.status);\n\t\t\t\tthis.fetchStatusPromises.delete(payload.nonce);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.WorkerReady: {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.CancelIdentify: {\n\t\t\t\tthis.waitForIdentifyControllers.get(payload.nonce)?.abort();\n\t\t\t\tthis.waitForIdentifyControllers.delete(payload.nonce);\n\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.ShardIdentifyResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tok: false,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async ensureThrottler(): Promise {\n\t\tthis.throttler ??= await this.manager.options.buildIdentifyThrottler(this.manager);\n\t\treturn this.throttler;\n\t}\n}\n","import type { Awaitable } from '@discordjs/util';\nimport type { APIGatewayBotInfo } from 'discord-api-types/v10';\nimport type { SessionInfo, WebSocketManager, WebSocketManagerOptions } from '../../ws/WebSocketManager.js';\n\nexport interface FetchingStrategyOptions\n\textends Omit<\n\t\tWebSocketManagerOptions,\n\t\t| 'buildIdentifyThrottler'\n\t\t| 'buildStrategy'\n\t\t| 'rest'\n\t\t| 'retrieveSessionInfo'\n\t\t| 'shardCount'\n\t\t| 'shardIds'\n\t\t| 'updateSessionInfo'\n\t> {\n\treadonly gatewayInformation: APIGatewayBotInfo;\n\treadonly shardCount: number;\n}\n\n/**\n * Strategies responsible solely for making manager information accessible\n */\nexport interface IContextFetchingStrategy {\n\treadonly options: FetchingStrategyOptions;\n\tretrieveSessionInfo(shardId: number): Awaitable;\n\tupdateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable;\n\t/**\n\t * Resolves once the given shard should be allowed to identify, or rejects if the operation was aborted\n\t */\n\twaitForIdentify(shardId: number, signal: AbortSignal): Promise;\n}\n\nexport async function managerToFetchingStrategyOptions(manager: WebSocketManager): Promise {\n\t/* eslint-disable @typescript-eslint/unbound-method */\n\tconst {\n\t\tbuildIdentifyThrottler,\n\t\tbuildStrategy,\n\t\tretrieveSessionInfo,\n\t\tupdateSessionInfo,\n\t\tshardCount,\n\t\tshardIds,\n\t\trest,\n\t\t...managerOptions\n\t} = manager.options;\n\t/* eslint-enable @typescript-eslint/unbound-method */\n\n\treturn {\n\t\t...managerOptions,\n\t\tgatewayInformation: await manager.fetchGatewayInformation(),\n\t\tshardCount: await manager.getShardCount(),\n\t};\n}\n","/* eslint-disable id-length */\nimport { Buffer } from 'node:buffer';\nimport { once } from 'node:events';\nimport { clearInterval, clearTimeout, setInterval, setTimeout } from 'node:timers';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { URLSearchParams } from 'node:url';\nimport { TextDecoder } from 'node:util';\nimport { inflate } from 'node:zlib';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\nimport {\n\tGatewayCloseCodes,\n\tGatewayDispatchEvents,\n\tGatewayOpcodes,\n\ttype GatewayDispatchPayload,\n\ttype GatewayIdentifyData,\n\ttype GatewayReadyDispatchData,\n\ttype GatewayReceivePayload,\n\ttype GatewaySendPayload,\n} from 'discord-api-types/v10';\nimport { WebSocket, type RawData } from 'ws';\nimport type { Inflate } from 'zlib-sync';\nimport type { IContextFetchingStrategy } from '../strategies/context/IContextFetchingStrategy.js';\nimport { ImportantGatewayOpcodes, getInitialSendRateLimitState } from '../utils/constants.js';\nimport type { SessionInfo } from './WebSocketManager.js';\n\n// eslint-disable-next-line promise/prefer-await-to-then\nconst getZlibSync = lazy(async () => import('zlib-sync').then((mod) => mod.default).catch(() => null));\n\nexport enum WebSocketShardEvents {\n\tClosed = 'closed',\n\tDebug = 'debug',\n\tDispatch = 'dispatch',\n\tError = 'error',\n\tHeartbeatComplete = 'heartbeat',\n\tHello = 'hello',\n\tReady = 'ready',\n\tResumed = 'resumed',\n}\n\nexport enum WebSocketShardStatus {\n\tIdle,\n\tConnecting,\n\tResuming,\n\tReady,\n}\n\nexport enum WebSocketShardDestroyRecovery {\n\tReconnect,\n\tResume,\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport type WebSocketShardEventsMap = {\n\t[WebSocketShardEvents.Closed]: [{ code: number }];\n\t[WebSocketShardEvents.Debug]: [payload: { message: string }];\n\t[WebSocketShardEvents.Dispatch]: [payload: { data: GatewayDispatchPayload }];\n\t[WebSocketShardEvents.Error]: [payload: { error: Error }];\n\t[WebSocketShardEvents.Hello]: [];\n\t[WebSocketShardEvents.Ready]: [payload: { data: GatewayReadyDispatchData }];\n\t[WebSocketShardEvents.Resumed]: [];\n\t[WebSocketShardEvents.HeartbeatComplete]: [payload: { ackAt: number; heartbeatAt: number; latency: number }];\n};\n\nexport interface WebSocketShardDestroyOptions {\n\tcode?: number;\n\treason?: string;\n\trecover?: WebSocketShardDestroyRecovery;\n}\n\nexport enum CloseCodes {\n\tNormal = 1_000,\n\tResuming = 4_200,\n}\n\nexport interface SendRateLimitState {\n\tremaining: number;\n\tresetAt: number;\n}\n\nexport class WebSocketShard extends AsyncEventEmitter {\n\tprivate connection: WebSocket | null = null;\n\n\tprivate useIdentifyCompress = false;\n\n\tprivate inflate: Inflate | null = null;\n\n\tprivate readonly textDecoder = new TextDecoder();\n\n\tprivate replayedEvents = 0;\n\n\tprivate isAck = true;\n\n\tprivate sendRateLimitState: SendRateLimitState = getInitialSendRateLimitState();\n\n\tprivate initialHeartbeatTimeoutController: AbortController | null = null;\n\n\tprivate heartbeatInterval: NodeJS.Timer | null = null;\n\n\tprivate lastHeartbeatAt = -1;\n\n\t// Indicates whether the shard has already resolved its original connect() call\n\tprivate initialConnectResolved = false;\n\n\t// Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET)\n\tprivate failedToConnectDueToNetworkError = false;\n\n\tprivate readonly sendQueue = new AsyncQueue();\n\n\tprivate readonly timeoutAbortControllers = new Collection();\n\n\tprivate readonly strategy: IContextFetchingStrategy;\n\n\tpublic readonly id: number;\n\n\t#status: WebSocketShardStatus = WebSocketShardStatus.Idle;\n\n\tpublic get status(): WebSocketShardStatus {\n\t\treturn this.#status;\n\t}\n\n\tpublic constructor(strategy: IContextFetchingStrategy, id: number) {\n\t\tsuper();\n\t\tthis.strategy = strategy;\n\t\tthis.id = id;\n\t}\n\n\tpublic async connect() {\n\t\tconst promise = this.initialConnectResolved ? Promise.resolve() : once(this, WebSocketShardEvents.Ready);\n\t\tvoid this.internalConnect();\n\n\t\tawait promise;\n\t\tthis.initialConnectResolved = true;\n\t}\n\n\tprivate async internalConnect() {\n\t\tif (this.#status !== WebSocketShardStatus.Idle) {\n\t\t\tthrow new Error(\"Tried to connect a shard that wasn't idle\");\n\t\t}\n\n\t\tconst { version, encoding, compression } = this.strategy.options;\n\t\tconst params = new URLSearchParams({ v: version, encoding });\n\t\tif (compression) {\n\t\t\tconst zlib = await getZlibSync();\n\t\t\tif (zlib) {\n\t\t\t\tparams.append('compress', compression);\n\t\t\t\tthis.inflate = new zlib.Inflate({\n\t\t\t\t\tchunkSize: 65_535,\n\t\t\t\t\tto: 'string',\n\t\t\t\t});\n\t\t\t} else if (!this.useIdentifyCompress) {\n\t\t\t\tthis.useIdentifyCompress = true;\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\n\t\tconst url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`;\n\t\tthis.debug([`Connecting to ${url}`]);\n\t\tconst connection = new WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? undefined })\n\t\t\t.on('message', this.onMessage.bind(this))\n\t\t\t.on('error', this.onError.bind(this))\n\t\t\t.on('close', this.onClose.bind(this));\n\n\t\tconnection.binaryType = 'arraybuffer';\n\t\tthis.connection = connection;\n\n\t\tthis.#status = WebSocketShardStatus.Connecting;\n\n\t\tthis.sendRateLimitState = getInitialSendRateLimitState();\n\n\t\tconst { ok } = await this.waitForEvent(WebSocketShardEvents.Hello, this.strategy.options.helloTimeout);\n\t\tif (!ok) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (session?.shardCount === this.strategy.options.shardCount) {\n\t\t\tawait this.resume(session);\n\t\t} else {\n\t\t\tawait this.identify();\n\t\t}\n\t}\n\n\tpublic async destroy(options: WebSocketShardDestroyOptions = {}) {\n\t\tif (this.#status === WebSocketShardStatus.Idle) {\n\t\t\tthis.debug(['Tried to destroy a shard that was idle']);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!options.code) {\n\t\t\toptions.code = options.recover === WebSocketShardDestroyRecovery.Resume ? CloseCodes.Resuming : CloseCodes.Normal;\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Destroying shard',\n\t\t\t`Reason: ${options.reason ?? 'none'}`,\n\t\t\t`Code: ${options.code}`,\n\t\t\t`Recover: ${options.recover === undefined ? 'none' : WebSocketShardDestroyRecovery[options.recover]!}`,\n\t\t]);\n\n\t\t// Reset state\n\t\tthis.isAck = true;\n\t\tif (this.heartbeatInterval) {\n\t\t\tclearInterval(this.heartbeatInterval);\n\t\t}\n\n\t\tif (this.initialHeartbeatTimeoutController) {\n\t\t\tthis.initialHeartbeatTimeoutController.abort();\n\t\t\tthis.initialHeartbeatTimeoutController = null;\n\t\t}\n\n\t\tthis.lastHeartbeatAt = -1;\n\n\t\tfor (const controller of this.timeoutAbortControllers.values()) {\n\t\t\tcontroller.abort();\n\t\t}\n\n\t\tthis.timeoutAbortControllers.clear();\n\n\t\tthis.failedToConnectDueToNetworkError = false;\n\n\t\t// Clear session state if applicable\n\t\tif (options.recover !== WebSocketShardDestroyRecovery.Resume) {\n\t\t\tawait this.strategy.updateSessionInfo(this.id, null);\n\t\t}\n\n\t\tif (this.connection) {\n\t\t\t// No longer need to listen to messages\n\t\t\tthis.connection.removeAllListeners('message');\n\t\t\t// Prevent a reconnection loop by unbinding the main close event\n\t\t\tthis.connection.removeAllListeners('close');\n\n\t\t\tconst shouldClose = this.connection.readyState === WebSocket.OPEN;\n\n\t\t\tthis.debug([\n\t\t\t\t'Connection status during destroy',\n\t\t\t\t`Needs closing: ${shouldClose}`,\n\t\t\t\t`Ready state: ${this.connection.readyState}`,\n\t\t\t]);\n\n\t\t\tif (shouldClose) {\n\t\t\t\tthis.connection.close(options.code, options.reason);\n\t\t\t\tawait once(this.connection, 'close');\n\t\t\t\tthis.emit(WebSocketShardEvents.Closed, { code: options.code });\n\t\t\t}\n\n\t\t\t// Lastly, remove the error event.\n\t\t\t// Doing this earlier would cause a hard crash in case an error event fired on our `close` call\n\t\t\tthis.connection.removeAllListeners('error');\n\t\t} else {\n\t\t\tthis.debug(['Destroying a shard that has no connection; please open an issue on GitHub']);\n\t\t}\n\n\t\tthis.#status = WebSocketShardStatus.Idle;\n\n\t\tif (options.recover !== undefined) {\n\t\t\t// There's cases (like no internet connection) where we immediately fail to connect,\n\t\t\t// causing a very fast and draining reconnection loop.\n\t\t\tawait sleep(500);\n\t\t\treturn this.internalConnect();\n\t\t}\n\t}\n\n\tprivate async waitForEvent(event: WebSocketShardEvents, timeoutDuration?: number | null): Promise<{ ok: boolean }> {\n\t\tthis.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : 'indefinitely'}`]);\n\t\tconst timeoutController = new AbortController();\n\t\tconst timeout = timeoutDuration ? setTimeout(() => timeoutController.abort(), timeoutDuration).unref() : null;\n\n\t\tthis.timeoutAbortControllers.set(event, timeoutController);\n\n\t\tconst closeController = new AbortController();\n\n\t\ttry {\n\t\t\t// If the first promise resolves, all is well. If the 2nd promise resolves,\n\t\t\t// the shard has meanwhile closed. In that case, a destroy is already ongoing, so we just need to\n\t\t\t// return false. Meanwhile, if something rejects (error event) or the first controller is aborted,\n\t\t\t// we enter the catch block and trigger a destroy there.\n\t\t\tconst closed = await Promise.race([\n\t\t\t\tonce(this, event, { signal: timeoutController.signal }).then(() => false),\n\t\t\t\tonce(this, WebSocketShardEvents.Closed, { signal: closeController.signal }).then(() => true),\n\t\t\t]);\n\n\t\t\treturn { ok: !closed };\n\t\t} catch {\n\t\t\t// If we're here because of other reasons, we need to destroy the shard\n\t\t\tvoid this.destroy({\n\t\t\t\tcode: CloseCodes.Normal,\n\t\t\t\treason: 'Something timed out or went wrong while waiting for an event',\n\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t});\n\n\t\t\treturn { ok: false };\n\t\t} finally {\n\t\t\tif (timeout) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t}\n\n\t\t\tthis.timeoutAbortControllers.delete(event);\n\n\t\t\t// Clean up the close listener to not leak memory\n\t\t\tif (!closeController.signal.aborted) {\n\t\t\t\tcloseController.abort();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async send(payload: GatewaySendPayload): Promise {\n\t\tif (!this.connection) {\n\t\t\tthrow new Error(\"WebSocketShard wasn't connected\");\n\t\t}\n\n\t\tif (this.#status !== WebSocketShardStatus.Ready && !ImportantGatewayOpcodes.has(payload.op)) {\n\t\t\tthis.debug(['Tried to send a non-crucial payload before the shard was ready, waiting']);\n\t\t\t// This will throw if the shard throws an error event in the meantime, just requeue the payload\n\t\t\ttry {\n\t\t\t\tawait once(this, WebSocketShardEvents.Ready);\n\t\t\t} catch {\n\t\t\t\treturn this.send(payload);\n\t\t\t}\n\t\t}\n\n\t\tawait this.sendQueue.wait();\n\n\t\tif (--this.sendRateLimitState.remaining <= 0) {\n\t\t\tconst now = Date.now();\n\n\t\t\tif (this.sendRateLimitState.resetAt > now) {\n\t\t\t\tconst sleepFor = this.sendRateLimitState.resetAt - now;\n\n\t\t\t\tthis.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]);\n\t\t\t\tconst controller = new AbortController();\n\n\t\t\t\t// Sleep for the remaining time, but if the connection closes in the meantime, we shouldn't wait the remainder to avoid blocking the new conn\n\t\t\t\tconst interrupted = await Promise.race([\n\t\t\t\t\tsleep(sleepFor).then(() => false),\n\t\t\t\t\tonce(this, WebSocketShardEvents.Closed, { signal: controller.signal }).then(() => true),\n\t\t\t\t]);\n\n\t\t\t\tif (interrupted) {\n\t\t\t\t\tthis.debug(['Connection closed while waiting for the send rate limit to reset, re-queueing payload']);\n\t\t\t\t\tthis.sendQueue.shift();\n\t\t\t\t\treturn this.send(payload);\n\t\t\t\t}\n\n\t\t\t\t// This is so the listener from the `once` call is removed\n\t\t\t\tcontroller.abort();\n\t\t\t}\n\n\t\t\tthis.sendRateLimitState = getInitialSendRateLimitState();\n\t\t}\n\n\t\tthis.sendQueue.shift();\n\t\tthis.connection.send(JSON.stringify(payload));\n\t}\n\n\tprivate async identify() {\n\t\tthis.debug(['Waiting for identify throttle']);\n\n\t\tconst controller = new AbortController();\n\t\tconst closeHandler = () => {\n\t\t\tcontroller.abort();\n\t\t};\n\n\t\tthis.on(WebSocketShardEvents.Closed, closeHandler);\n\n\t\ttry {\n\t\t\tawait this.strategy.waitForIdentify(this.id, controller.signal);\n\t\t} catch {\n\t\t\tthis.debug(['Was waiting for an identify, but the shard closed in the meantime']);\n\t\t\treturn;\n\t\t} finally {\n\t\t\tthis.off(WebSocketShardEvents.Closed, closeHandler);\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Identifying',\n\t\t\t`shard id: ${this.id.toString()}`,\n\t\t\t`shard count: ${this.strategy.options.shardCount}`,\n\t\t\t`intents: ${this.strategy.options.intents}`,\n\t\t\t`compression: ${this.inflate ? 'zlib-stream' : this.useIdentifyCompress ? 'identify' : 'none'}`,\n\t\t]);\n\n\t\tconst d: GatewayIdentifyData = {\n\t\t\ttoken: this.strategy.options.token,\n\t\t\tproperties: this.strategy.options.identifyProperties,\n\t\t\tintents: this.strategy.options.intents,\n\t\t\tcompress: this.useIdentifyCompress,\n\t\t\tshard: [this.id, this.strategy.options.shardCount],\n\t\t};\n\n\t\tif (this.strategy.options.largeThreshold) {\n\t\t\td.large_threshold = this.strategy.options.largeThreshold;\n\t\t}\n\n\t\tif (this.strategy.options.initialPresence) {\n\t\t\td.presence = this.strategy.options.initialPresence;\n\t\t}\n\n\t\tawait this.send({\n\t\t\top: GatewayOpcodes.Identify,\n\t\t\td,\n\t\t});\n\n\t\tawait this.waitForEvent(WebSocketShardEvents.Ready, this.strategy.options.readyTimeout);\n\t}\n\n\tprivate async resume(session: SessionInfo) {\n\t\tthis.debug([\n\t\t\t'Resuming session',\n\t\t\t`resume url: ${session.resumeURL}`,\n\t\t\t`sequence: ${session.sequence}`,\n\t\t\t`shard id: ${this.id.toString()}`,\n\t\t]);\n\n\t\tthis.#status = WebSocketShardStatus.Resuming;\n\t\tthis.replayedEvents = 0;\n\t\treturn this.send({\n\t\t\top: GatewayOpcodes.Resume,\n\t\t\td: {\n\t\t\t\ttoken: this.strategy.options.token,\n\t\t\t\tseq: session.sequence,\n\t\t\t\tsession_id: session.sessionId,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async heartbeat(requested = false) {\n\t\tif (!this.isAck && !requested) {\n\t\t\treturn this.destroy({ reason: 'Zombie connection', recover: WebSocketShardDestroyRecovery.Resume });\n\t\t}\n\n\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\n\t\tawait this.send({\n\t\t\top: GatewayOpcodes.Heartbeat,\n\t\t\td: session?.sequence ?? null,\n\t\t});\n\n\t\tthis.lastHeartbeatAt = Date.now();\n\t\tthis.isAck = false;\n\t}\n\n\tprivate async unpackMessage(data: ArrayBuffer | Buffer, isBinary: boolean): Promise {\n\t\tconst decompressable = new Uint8Array(data);\n\n\t\t// Deal with no compression\n\t\tif (!isBinary) {\n\t\t\treturn JSON.parse(this.textDecoder.decode(decompressable)) as GatewayReceivePayload;\n\t\t}\n\n\t\t// Deal with identify compress\n\t\tif (this.useIdentifyCompress) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tinflate(decompressable, { chunkSize: 65_535 }, (err, result) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(JSON.parse(this.textDecoder.decode(result)) as GatewayReceivePayload);\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\t// Deal with gw wide zlib-stream compression\n\t\tif (this.inflate) {\n\t\t\tconst l = decompressable.length;\n\t\t\tconst flush =\n\t\t\t\tl >= 4 &&\n\t\t\t\tdecompressable[l - 4] === 0x00 &&\n\t\t\t\tdecompressable[l - 3] === 0x00 &&\n\t\t\t\tdecompressable[l - 2] === 0xff &&\n\t\t\t\tdecompressable[l - 1] === 0xff;\n\n\t\t\tconst zlib = (await getZlibSync())!;\n\t\t\tthis.inflate.push(Buffer.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH);\n\n\t\t\tif (this.inflate.err) {\n\t\t\t\tthis.emit(WebSocketShardEvents.Error, {\n\t\t\t\t\terror: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ''}`),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!flush) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst { result } = this.inflate;\n\t\t\tif (!result) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn JSON.parse(typeof result === 'string' ? result : this.textDecoder.decode(result)) as GatewayReceivePayload;\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Received a message we were unable to decompress',\n\t\t\t`isBinary: ${isBinary.toString()}`,\n\t\t\t`useIdentifyCompress: ${this.useIdentifyCompress.toString()}`,\n\t\t\t`inflate: ${Boolean(this.inflate).toString()}`,\n\t\t]);\n\n\t\treturn null;\n\t}\n\n\tprivate async onMessage(data: RawData, isBinary: boolean) {\n\t\tconst payload = await this.unpackMessage(data as ArrayBuffer | Buffer, isBinary);\n\t\tif (!payload) {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (payload.op) {\n\t\t\tcase GatewayOpcodes.Dispatch: {\n\t\t\t\tif (this.#status === WebSocketShardStatus.Resuming) {\n\t\t\t\t\tthis.replayedEvents++;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line sonarjs/no-nested-switch\n\t\t\t\tswitch (payload.t) {\n\t\t\t\t\tcase GatewayDispatchEvents.Ready: {\n\t\t\t\t\t\tthis.#status = WebSocketShardStatus.Ready;\n\n\t\t\t\t\t\tconst session = {\n\t\t\t\t\t\t\tsequence: payload.s,\n\t\t\t\t\t\t\tsessionId: payload.d.session_id,\n\t\t\t\t\t\t\tshardId: this.id,\n\t\t\t\t\t\t\tshardCount: this.strategy.options.shardCount,\n\t\t\t\t\t\t\tresumeURL: payload.d.resume_gateway_url,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tawait this.strategy.updateSessionInfo(this.id, session);\n\n\t\t\t\t\t\tthis.emit(WebSocketShardEvents.Ready, { data: payload.d });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase GatewayDispatchEvents.Resumed: {\n\t\t\t\t\t\tthis.#status = WebSocketShardStatus.Ready;\n\t\t\t\t\t\tthis.debug([`Resumed and replayed ${this.replayedEvents} events`]);\n\t\t\t\t\t\tthis.emit(WebSocketShardEvents.Resumed);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\t\t\t\tif (session) {\n\t\t\t\t\tif (payload.s > session.sequence) {\n\t\t\t\t\t\tawait this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s });\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.debug([\n\t\t\t\t\t\t`Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect`,\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tthis.emit(WebSocketShardEvents.Dispatch, { data: payload });\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Heartbeat: {\n\t\t\t\tawait this.heartbeat(true);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Reconnect: {\n\t\t\t\tawait this.destroy({\n\t\t\t\t\treason: 'Told to reconnect by Discord',\n\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Resume,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.InvalidSession: {\n\t\t\t\tthis.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]);\n\t\t\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\t\t\t\tif (payload.d && session) {\n\t\t\t\t\tawait this.resume(session);\n\t\t\t\t} else {\n\t\t\t\t\tawait this.destroy({\n\t\t\t\t\t\treason: 'Invalid session',\n\t\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Hello: {\n\t\t\t\tthis.emit(WebSocketShardEvents.Hello);\n\t\t\t\tconst jitter = Math.random();\n\t\t\t\tconst firstWait = Math.floor(payload.d.heartbeat_interval * jitter);\n\t\t\t\tthis.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\tthis.initialHeartbeatTimeoutController = controller;\n\t\t\t\t\tawait sleep(firstWait, undefined, { signal: controller.signal });\n\t\t\t\t} catch {\n\t\t\t\t\tthis.debug(['Cancelled initial heartbeat due to #destroy being called']);\n\t\t\t\t\treturn;\n\t\t\t\t} finally {\n\t\t\t\t\tthis.initialHeartbeatTimeoutController = null;\n\t\t\t\t}\n\n\t\t\t\tawait this.heartbeat();\n\n\t\t\t\tthis.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]);\n\t\t\t\tthis.heartbeatInterval = setInterval(() => void this.heartbeat(), payload.d.heartbeat_interval);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.HeartbeatAck: {\n\t\t\t\tthis.isAck = true;\n\n\t\t\t\tconst ackAt = Date.now();\n\t\t\t\tthis.emit(WebSocketShardEvents.HeartbeatComplete, {\n\t\t\t\t\tackAt,\n\t\t\t\t\theartbeatAt: this.lastHeartbeatAt,\n\t\t\t\t\tlatency: ackAt - this.lastHeartbeatAt,\n\t\t\t\t});\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate onError(error: Error) {\n\t\tif ('code' in error && ['ECONNRESET', 'ECONNREFUSED'].includes(error.code as string)) {\n\t\t\tthis.debug(['Failed to connect to the gateway URL specified due to a network error']);\n\t\t\tthis.failedToConnectDueToNetworkError = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.emit(WebSocketShardEvents.Error, { error });\n\t}\n\n\tprivate async onClose(code: number) {\n\t\tthis.emit(WebSocketShardEvents.Closed, { code });\n\n\t\tswitch (code) {\n\t\t\tcase CloseCodes.Normal: {\n\t\t\t\treturn this.destroy({\n\t\t\t\t\tcode,\n\t\t\t\t\treason: 'Got disconnected by Discord',\n\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase CloseCodes.Resuming: {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.UnknownError: {\n\t\t\t\tthis.debug([`An unknown error occurred: ${code}`]);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.UnknownOpcode: {\n\t\t\t\tthis.debug(['An invalid opcode was sent to Discord.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.DecodeError: {\n\t\t\t\tthis.debug(['An invalid payload was sent to Discord.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.NotAuthenticated: {\n\t\t\t\tthis.debug(['A request was somehow sent before the identify/resume payload.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.AuthenticationFailed: {\n\t\t\t\tthrow new Error('Authentication failed');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.AlreadyAuthenticated: {\n\t\t\t\tthis.debug(['More than one auth payload was sent.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidSeq: {\n\t\t\t\tthis.debug(['An invalid sequence was sent.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.RateLimited: {\n\t\t\t\tthis.debug(['The WebSocket rate limit has been hit, this should never happen']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.SessionTimedOut: {\n\t\t\t\tthis.debug(['Session timed out.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidShard: {\n\t\t\t\tthrow new Error('Invalid shard');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.ShardingRequired: {\n\t\t\t\tthrow new Error('Sharding is required');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidAPIVersion: {\n\t\t\t\tthrow new Error('Used an invalid API version');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidIntents: {\n\t\t\t\tthrow new Error('Used invalid intents');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.DisallowedIntents: {\n\t\t\t\tthrow new Error('Used disallowed intents');\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tthis.debug([\n\t\t\t\t\t`The gateway closed with an unexpected code ${code}, attempting to ${\n\t\t\t\t\t\tthis.failedToConnectDueToNetworkError ? 'reconnect' : 'resume'\n\t\t\t\t\t}.`,\n\t\t\t\t]);\n\t\t\t\treturn this.destroy({\n\t\t\t\t\tcode,\n\t\t\t\t\trecover: this.failedToConnectDueToNetworkError\n\t\t\t\t\t\t? WebSocketShardDestroyRecovery.Reconnect\n\t\t\t\t\t\t: WebSocketShardDestroyRecovery.Resume,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate debug(messages: [string, ...string[]]) {\n\t\tconst message = `${messages[0]}${\n\t\t\tmessages.length > 1\n\t\t\t\t? `\\n${messages\n\t\t\t\t\t\t.slice(1)\n\t\t\t\t\t\t.map((m) => `\t${m}`)\n\t\t\t\t\t\t.join('\\n')}`\n\t\t\t\t: ''\n\t\t}`;\n\n\t\tthis.emit(WebSocketShardEvents.Debug, { message });\n\t}\n}\n","import process from 'node:process';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { APIVersion, GatewayOpcodes } from 'discord-api-types/v10';\nimport { SimpleShardingStrategy } from '../strategies/sharding/SimpleShardingStrategy.js';\nimport { SimpleIdentifyThrottler } from '../throttling/SimpleIdentifyThrottler.js';\nimport type { SessionInfo, OptionalWebSocketManagerOptions, WebSocketManager } from '../ws/WebSocketManager.js';\nimport type { SendRateLimitState } from '../ws/WebSocketShard.js';\n\n/**\n * Valid encoding types\n */\nexport enum Encoding {\n\tJSON = 'json',\n}\n\n/**\n * Valid compression methods\n */\nexport enum CompressionMethod {\n\tZlibStream = 'zlib-stream',\n}\n\nexport const DefaultDeviceProperty = `@discordjs/ws 0.8.3` as `@discordjs/ws ${string}`;\n\nconst getDefaultSessionStore = lazy(() => new Collection());\n\n/**\n * Default options used by the manager\n */\nexport const DefaultWebSocketManagerOptions = {\n\tasync buildIdentifyThrottler(manager: WebSocketManager) {\n\t\tconst info = await manager.fetchGatewayInformation();\n\t\treturn new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency);\n\t},\n\tbuildStrategy: (manager) => new SimpleShardingStrategy(manager),\n\tshardCount: null,\n\tshardIds: null,\n\tlargeThreshold: null,\n\tinitialPresence: null,\n\tidentifyProperties: {\n\t\tbrowser: DefaultDeviceProperty,\n\t\tdevice: DefaultDeviceProperty,\n\t\tos: process.platform,\n\t},\n\tversion: APIVersion,\n\tencoding: Encoding.JSON,\n\tcompression: null,\n\tretrieveSessionInfo(shardId) {\n\t\tconst store = getDefaultSessionStore();\n\t\treturn store.get(shardId) ?? null;\n\t},\n\tupdateSessionInfo(shardId: number, info: SessionInfo | null) {\n\t\tconst store = getDefaultSessionStore();\n\t\tif (info) {\n\t\t\tstore.set(shardId, info);\n\t\t} else {\n\t\t\tstore.delete(shardId);\n\t\t}\n\t},\n\thandshakeTimeout: 30_000,\n\thelloTimeout: 60_000,\n\treadyTimeout: 15_000,\n} as const satisfies OptionalWebSocketManagerOptions;\n\nexport const ImportantGatewayOpcodes = new Set([\n\tGatewayOpcodes.Heartbeat,\n\tGatewayOpcodes.Identify,\n\tGatewayOpcodes.Resume,\n]);\n\nexport function getInitialSendRateLimitState(): SendRateLimitState {\n\treturn {\n\t\tremaining: 120,\n\t\tresetAt: Date.now() + 60_000,\n\t};\n}\n","import { Collection } from '@discordjs/collection';\nimport type { GatewaySendPayload } from 'discord-api-types/v10';\nimport type { WebSocketManager } from '../../ws/WebSocketManager.js';\nimport { WebSocketShard, WebSocketShardEvents, type WebSocketShardDestroyOptions } from '../../ws/WebSocketShard.js';\nimport { managerToFetchingStrategyOptions } from '../context/IContextFetchingStrategy.js';\nimport { SimpleContextFetchingStrategy } from '../context/SimpleContextFetchingStrategy.js';\nimport type { IShardingStrategy } from './IShardingStrategy.js';\n\n/**\n * Simple strategy that just spawns shards in the current process\n */\nexport class SimpleShardingStrategy implements IShardingStrategy {\n\tprivate readonly manager: WebSocketManager;\n\n\tprivate readonly shards = new Collection();\n\n\tpublic constructor(manager: WebSocketManager) {\n\t\tthis.manager = manager;\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.spawn}\n\t */\n\tpublic async spawn(shardIds: number[]) {\n\t\tconst strategyOptions = await managerToFetchingStrategyOptions(this.manager);\n\n\t\tfor (const shardId of shardIds) {\n\t\t\tconst strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions);\n\t\t\tconst shard = new WebSocketShard(strategy, shardId);\n\t\t\tfor (const event of Object.values(WebSocketShardEvents)) {\n\t\t\t\t// @ts-expect-error: Intentional\n\t\t\t\tshard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId }));\n\t\t\t}\n\n\t\t\tthis.shards.set(shardId, shard);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.connect}\n\t */\n\tpublic async connect() {\n\t\tconst promises = [];\n\n\t\tfor (const shard of this.shards.values()) {\n\t\t\tpromises.push(shard.connect());\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.destroy}\n\t */\n\tpublic async destroy(options?: Omit) {\n\t\tconst promises = [];\n\n\t\tfor (const shard of this.shards.values()) {\n\t\t\tpromises.push(shard.destroy(options));\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t\tthis.shards.clear();\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.send}\n\t */\n\tpublic async send(shardId: number, payload: GatewaySendPayload) {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} not found`);\n\t\t}\n\n\t\treturn shard.send(payload);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.fetchStatus}\n\t */\n\tpublic async fetchStatus() {\n\t\treturn this.shards.mapValues((shard) => shard.status);\n\t}\n}\n","import type { IIdentifyThrottler } from '../../throttling/IIdentifyThrottler.js';\nimport type { SessionInfo, WebSocketManager } from '../../ws/WebSocketManager.js';\nimport type { FetchingStrategyOptions, IContextFetchingStrategy } from './IContextFetchingStrategy.js';\n\nexport class SimpleContextFetchingStrategy implements IContextFetchingStrategy {\n\t// This strategy assumes every shard is running under the same process - therefore we need a single\n\t// IdentifyThrottler per manager.\n\tprivate static throttlerCache = new WeakMap();\n\n\tprivate static async ensureThrottler(manager: WebSocketManager): Promise {\n\t\tconst throttler = SimpleContextFetchingStrategy.throttlerCache.get(manager);\n\t\tif (throttler) {\n\t\t\treturn throttler;\n\t\t}\n\n\t\tconst newThrottler = await manager.options.buildIdentifyThrottler(manager);\n\t\tSimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler);\n\n\t\treturn newThrottler;\n\t}\n\n\tpublic constructor(private readonly manager: WebSocketManager, public readonly options: FetchingStrategyOptions) {}\n\n\tpublic async retrieveSessionInfo(shardId: number): Promise {\n\t\treturn this.manager.options.retrieveSessionInfo(shardId);\n\t}\n\n\tpublic updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null) {\n\t\treturn this.manager.options.updateSessionInfo(shardId, sessionInfo);\n\t}\n\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst throttler = await SimpleContextFetchingStrategy.ensureThrottler(this.manager);\n\t\tawait throttler.waitForIdentify(shardId, signal);\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport { Collection } from '@discordjs/collection';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport type { IIdentifyThrottler } from './IIdentifyThrottler.js';\n\n/**\n * The state of a rate limit key's identify queue.\n */\nexport interface IdentifyState {\n\tqueue: AsyncQueue;\n\tresetsAt: number;\n}\n\n/**\n * Local, in-memory identify throttler.\n */\nexport class SimpleIdentifyThrottler implements IIdentifyThrottler {\n\tprivate readonly states = new Collection();\n\n\tpublic constructor(private readonly maxConcurrency: number) {}\n\n\t/**\n\t * {@inheritDoc IIdentifyThrottler.waitForIdentify}\n\t */\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst key = shardId % this.maxConcurrency;\n\n\t\tconst state = this.states.ensure(key, () => {\n\t\t\treturn {\n\t\t\t\tqueue: new AsyncQueue(),\n\t\t\t\tresetsAt: Number.POSITIVE_INFINITY,\n\t\t\t};\n\t\t});\n\n\t\tawait state.queue.wait({ signal });\n\n\t\ttry {\n\t\t\tconst diff = state.resetsAt - Date.now();\n\t\t\tif (diff <= 5_000) {\n\t\t\t\t// To account for the latency the IDENTIFY payload goes through, we add a bit more wait time\n\t\t\t\tconst time = diff + Math.random() * 1_500;\n\t\t\t\tawait sleep(time);\n\t\t\t}\n\n\t\t\tstate.resetsAt = Date.now() + 5_000;\n\t\t} finally {\n\t\t\tstate.queue.shift();\n\t\t}\n\t}\n}\n","import { WorkerBootstrapper } from '../../utils/WorkerBootstrapper.js';\n\nconst bootstrapper = new WorkerBootstrapper();\nvoid bootstrapper.bootstrap();\n"],"mappings":";;;;;;;;;AAAA,SAAS,gBAAAA,eAAc,cAAAC,aAAY,kBAAkB;AACrD,SAAS,cAAAC,mBAAkB;;;ACD3B,SAAS,cAAc,kBAAkB;AACzC,SAAS,cAAAC,mBAAkB;;;ACD3B,SAAS,YAAY;AACr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","once","sleep","Collection","lazy","AsyncQueue","GatewayOpcodes","Collection","Collection","Collection","Collection","Collection","Collection","lazy","WebSocketShardEvents","WebSocketShardDestroyRecovery","AsyncQueue","Collection","once","sleep","GatewayOpcodes","resolve","Buffer","session","Collection","isMainThread","parentPort"]} \ No newline at end of file diff --git a/node_modules/@discordjs/ws/dist/index.d.ts b/node_modules/@discordjs/ws/dist/index.d.ts new file mode 100644 index 0000000..a79c561 --- /dev/null +++ b/node_modules/@discordjs/ws/dist/index.d.ts @@ -0,0 +1,667 @@ +import * as _discordjs_util from '@discordjs/util'; +import { Awaitable } from '@discordjs/util'; +import { GatewayDispatchPayload, GatewayReadyDispatchData, GatewaySendPayload, GatewayOpcodes, GatewayIntentBits, GatewayIdentifyProperties, GatewayPresenceUpdateData, APIGatewayBotInfo } from 'discord-api-types/v10'; +import * as _discordjs_collection from '@discordjs/collection'; +import { Collection } from '@discordjs/collection'; +import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter'; +import { REST } from '@discordjs/rest'; +import { AsyncQueue } from '@sapphire/async-queue'; + +declare enum WebSocketShardEvents { + Closed = "closed", + Debug = "debug", + Dispatch = "dispatch", + Error = "error", + HeartbeatComplete = "heartbeat", + Hello = "hello", + Ready = "ready", + Resumed = "resumed" +} +declare enum WebSocketShardStatus { + Idle = 0, + Connecting = 1, + Resuming = 2, + Ready = 3 +} +declare enum WebSocketShardDestroyRecovery { + Reconnect = 0, + Resume = 1 +} +type WebSocketShardEventsMap = { + [WebSocketShardEvents.Closed]: [{ + code: number; + }]; + [WebSocketShardEvents.Debug]: [payload: { + message: string; + }]; + [WebSocketShardEvents.Dispatch]: [payload: { + data: GatewayDispatchPayload; + }]; + [WebSocketShardEvents.Error]: [payload: { + error: Error; + }]; + [WebSocketShardEvents.Hello]: []; + [WebSocketShardEvents.Ready]: [payload: { + data: GatewayReadyDispatchData; + }]; + [WebSocketShardEvents.Resumed]: []; + [WebSocketShardEvents.HeartbeatComplete]: [payload: { + ackAt: number; + heartbeatAt: number; + latency: number; + }]; +}; +interface WebSocketShardDestroyOptions { + code?: number; + reason?: string; + recover?: WebSocketShardDestroyRecovery; +} +declare enum CloseCodes { + Normal = 1000, + Resuming = 4200 +} +interface SendRateLimitState { + remaining: number; + resetAt: number; +} +declare class WebSocketShard extends AsyncEventEmitter { + #private; + private connection; + private useIdentifyCompress; + private inflate; + private readonly textDecoder; + private replayedEvents; + private isAck; + private sendRateLimitState; + private initialHeartbeatTimeoutController; + private heartbeatInterval; + private lastHeartbeatAt; + private initialConnectResolved; + private failedToConnectDueToNetworkError; + private readonly sendQueue; + private readonly timeoutAbortControllers; + private readonly strategy; + readonly id: number; + get status(): WebSocketShardStatus; + constructor(strategy: IContextFetchingStrategy, id: number); + connect(): Promise; + private internalConnect; + destroy(options?: WebSocketShardDestroyOptions): Promise; + private waitForEvent; + send(payload: GatewaySendPayload): Promise; + private identify; + private resume; + private heartbeat; + private unpackMessage; + private onMessage; + private onError; + private onClose; + private debug; +} + +/** + * Strategies responsible for spawning, initializing connections, destroying shards, and relaying events + */ +interface IShardingStrategy { + /** + * Initializes all the shards + */ + connect(): Awaitable; + /** + * Destroys all the shards + */ + destroy(options?: Omit): Awaitable; + /** + * Fetches the status of all the shards + */ + fetchStatus(): Awaitable>; + /** + * Sends a payload to a shard + */ + send(shardId: number, payload: GatewaySendPayload): Awaitable; + /** + * Spawns all the shards + */ + spawn(shardIds: number[]): Awaitable; +} + +/** + * IdentifyThrottlers are responsible for dictating when a shard is allowed to identify. + * + * @see {@link https://discord.com/developers/docs/topics/gateway#sharding-max-concurrency} + */ +interface IIdentifyThrottler { + /** + * Resolves once the given shard should be allowed to identify, or rejects if the operation was aborted. + */ + waitForIdentify(shardId: number, signal: AbortSignal): Promise; +} + +/** + * Simple strategy that just spawns shards in the current process + */ +declare class SimpleShardingStrategy implements IShardingStrategy { + private readonly manager; + private readonly shards; + constructor(manager: WebSocketManager); + /** + * {@inheritDoc IShardingStrategy.spawn} + */ + spawn(shardIds: number[]): Promise; + /** + * {@inheritDoc IShardingStrategy.connect} + */ + connect(): Promise; + /** + * {@inheritDoc IShardingStrategy.destroy} + */ + destroy(options?: Omit): Promise; + /** + * {@inheritDoc IShardingStrategy.send} + */ + send(shardId: number, payload: GatewaySendPayload): Promise; + /** + * {@inheritDoc IShardingStrategy.fetchStatus} + */ + fetchStatus(): Promise>; +} + +/** + * The state of a rate limit key's identify queue. + */ +interface IdentifyState { + queue: AsyncQueue; + resetsAt: number; +} +/** + * Local, in-memory identify throttler. + */ +declare class SimpleIdentifyThrottler implements IIdentifyThrottler { + private readonly maxConcurrency; + private readonly states; + constructor(maxConcurrency: number); + /** + * {@inheritDoc IIdentifyThrottler.waitForIdentify} + */ + waitForIdentify(shardId: number, signal: AbortSignal): Promise; +} + +/** + * Valid encoding types + */ +declare enum Encoding { + JSON = "json" +} +/** + * Valid compression methods + */ +declare enum CompressionMethod { + ZlibStream = "zlib-stream" +} +declare const DefaultDeviceProperty: `@discordjs/ws ${string}`; +/** + * Default options used by the manager + */ +declare const DefaultWebSocketManagerOptions: { + readonly buildIdentifyThrottler: (manager: WebSocketManager) => Promise; + readonly buildStrategy: (manager: WebSocketManager) => SimpleShardingStrategy; + readonly shardCount: null; + readonly shardIds: null; + readonly largeThreshold: null; + readonly initialPresence: null; + readonly identifyProperties: { + readonly browser: `@discordjs/ws ${string}`; + readonly device: `@discordjs/ws ${string}`; + readonly os: NodeJS.Platform; + }; + readonly version: "10"; + readonly encoding: Encoding; + readonly compression: null; + readonly retrieveSessionInfo: (shardId: number) => SessionInfo | null; + readonly updateSessionInfo: (shardId: number, info: SessionInfo | null) => void; + readonly handshakeTimeout: 30000; + readonly helloTimeout: 60000; + readonly readyTimeout: 15000; +}; +declare const ImportantGatewayOpcodes: Set; +declare function getInitialSendRateLimitState(): SendRateLimitState; + +/** + * Represents a range of shard ids + */ +interface ShardRange { + end: number; + start: number; +} +/** + * Session information for a given shard, used to resume a session + */ +interface SessionInfo { + /** + * URL to use when resuming + */ + resumeURL: string; + /** + * The sequence number of the last message sent by the shard + */ + sequence: number; + /** + * Session id for this shard + */ + sessionId: string; + /** + * The total number of shards at the time of this shard identifying + */ + shardCount: number; + /** + * The id of the shard + */ + shardId: number; +} +/** + * Required options for the WebSocketManager + */ +interface RequiredWebSocketManagerOptions { + /** + * The intents to request + */ + intents: GatewayIntentBits | 0; + /** + * The REST instance to use for fetching gateway information + */ + rest: REST; + /** + * The token to use for identifying with the gateway + */ + token: string; +} +/** + * Optional additional configuration for the WebSocketManager + */ +interface OptionalWebSocketManagerOptions { + /** + * Builds an identify throttler to use for this manager's shards + */ + buildIdentifyThrottler(manager: WebSocketManager): Awaitable; + /** + * Builds the strategy to use for sharding + * + * @example + * ```ts + * const manager = new WebSocketManager({ + * token: process.env.DISCORD_TOKEN, + * intents: 0, // for no intents + * rest, + * buildStrategy: (manager) => new WorkerShardingStrategy(manager, { shardsPerWorker: 2 }), + * }); + * ``` + */ + buildStrategy(manager: WebSocketManager): IShardingStrategy; + /** + * The compression method to use + * + * @defaultValue `null` (no compression) + */ + compression: CompressionMethod | null; + /** + * The encoding to use + * + * @defaultValue `'json'` + */ + encoding: Encoding; + /** + * How long to wait for a shard to connect before giving up + */ + handshakeTimeout: number | null; + /** + * How long to wait for a shard's HELLO packet before giving up + */ + helloTimeout: number | null; + /** + * Properties to send to the gateway when identifying + */ + identifyProperties: GatewayIdentifyProperties; + /** + * Initial presence data to send to the gateway when identifying + */ + initialPresence: GatewayPresenceUpdateData | null; + /** + * Value between 50 and 250, total number of members where the gateway will stop sending offline members in the guild member list + */ + largeThreshold: number | null; + /** + * How long to wait for a shard's READY packet before giving up + */ + readyTimeout: number | null; + /** + * Function used to retrieve session information (and attempt to resume) for a given shard + * + * @example + * ```ts + * const manager = new WebSocketManager({ + * async retrieveSessionInfo(shardId): Awaitable { + * // Fetch this info from redis or similar + * return { sessionId: string, sequence: number }; + * // Return null if no information is found + * }, + * }); + * ``` + */ + retrieveSessionInfo(shardId: number): Awaitable; + /** + * The total number of shards across all WebsocketManagers you intend to instantiate. + * Use `null` to use Discord's recommended shard count + */ + shardCount: number | null; + /** + * The ids of the shards this WebSocketManager should manage. + * Use `null` to simply spawn 0 through `shardCount - 1` + * + * @example + * ```ts + * const manager = new WebSocketManager({ + * shardIds: [1, 3, 7], // spawns shard 1, 3, and 7, nothing else + * }); + * ``` + * @example + * ```ts + * const manager = new WebSocketManager({ + * shardIds: { + * start: 3, + * end: 6, + * }, // spawns shards 3, 4, 5, and 6 + * }); + * ``` + */ + shardIds: number[] | ShardRange | null; + /** + * Function used to store session information for a given shard + */ + updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable; + /** + * The gateway version to use + * + * @defaultValue `'10'` + */ + version: string; +} +type WebSocketManagerOptions = OptionalWebSocketManagerOptions & RequiredWebSocketManagerOptions; +type ManagerShardEventsMap = { + [K in keyof WebSocketShardEventsMap]: [ + WebSocketShardEventsMap[K] extends [] ? { + shardId: number; + } : WebSocketShardEventsMap[K][0] & { + shardId: number; + } + ]; +}; +declare class WebSocketManager extends AsyncEventEmitter { + /** + * The options being used by this manager + */ + readonly options: WebSocketManagerOptions; + /** + * Internal cache for a GET /gateway/bot result + */ + private gatewayInformation; + /** + * Internal cache for the shard ids + */ + private shardIds; + /** + * Strategy used to manage shards + * + * @defaultValue `SimpleShardingStrategy` + */ + private readonly strategy; + constructor(options: Partial & RequiredWebSocketManagerOptions); + /** + * Fetches the gateway information from Discord - or returns it from cache if available + * + * @param force - Whether to ignore the cache and force a fresh fetch + */ + fetchGatewayInformation(force?: boolean): Promise; + /** + * Updates your total shard count on-the-fly, spawning shards as needed + * + * @param shardCount - The new shard count to use + */ + updateShardCount(shardCount: number | null): Promise; + /** + * Yields the total number of shards across for your bot, accounting for Discord recommendations + */ + getShardCount(): Promise; + /** + * Yields the ids of the shards this manager should manage + */ + getShardIds(force?: boolean): Promise; + connect(): Promise; + destroy(options?: Omit): Awaitable; + send(shardId: number, payload: GatewaySendPayload): Awaitable; + fetchStatus(): Awaitable<_discordjs_collection.Collection>; +} + +interface FetchingStrategyOptions extends Omit { + readonly gatewayInformation: APIGatewayBotInfo; + readonly shardCount: number; +} +/** + * Strategies responsible solely for making manager information accessible + */ +interface IContextFetchingStrategy { + readonly options: FetchingStrategyOptions; + retrieveSessionInfo(shardId: number): Awaitable; + updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable; + /** + * Resolves once the given shard should be allowed to identify, or rejects if the operation was aborted + */ + waitForIdentify(shardId: number, signal: AbortSignal): Promise; +} +declare function managerToFetchingStrategyOptions(manager: WebSocketManager): Promise; + +declare class SimpleContextFetchingStrategy implements IContextFetchingStrategy { + private readonly manager; + readonly options: FetchingStrategyOptions; + private static throttlerCache; + private static ensureThrottler; + constructor(manager: WebSocketManager, options: FetchingStrategyOptions); + retrieveSessionInfo(shardId: number): Promise; + updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): _discordjs_util.Awaitable; + waitForIdentify(shardId: number, signal: AbortSignal): Promise; +} + +declare class WorkerContextFetchingStrategy implements IContextFetchingStrategy { + readonly options: FetchingStrategyOptions; + private readonly sessionPromises; + private readonly waitForIdentifyPromises; + constructor(options: FetchingStrategyOptions); + retrieveSessionInfo(shardId: number): Promise; + updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): void; + waitForIdentify(shardId: number, signal: AbortSignal): Promise; +} + +interface WorkerData extends FetchingStrategyOptions { + shardIds: number[]; +} +declare enum WorkerSendPayloadOp { + Connect = 0, + Destroy = 1, + Send = 2, + SessionInfoResponse = 3, + ShardIdentifyResponse = 4, + FetchStatus = 5 +} +type WorkerSendPayload = { + nonce: number; + ok: boolean; + op: WorkerSendPayloadOp.ShardIdentifyResponse; +} | { + nonce: number; + op: WorkerSendPayloadOp.FetchStatus; + shardId: number; +} | { + nonce: number; + op: WorkerSendPayloadOp.SessionInfoResponse; + session: SessionInfo | null; +} | { + op: WorkerSendPayloadOp.Connect; + shardId: number; +} | { + op: WorkerSendPayloadOp.Destroy; + options?: WebSocketShardDestroyOptions; + shardId: number; +} | { + op: WorkerSendPayloadOp.Send; + payload: GatewaySendPayload; + shardId: number; +}; +declare enum WorkerReceivePayloadOp { + Connected = 0, + Destroyed = 1, + Event = 2, + RetrieveSessionInfo = 3, + UpdateSessionInfo = 4, + WaitForIdentify = 5, + FetchStatusResponse = 6, + WorkerReady = 7, + CancelIdentify = 8 +} +type WorkerReceivePayload = { + data: any; + event: WebSocketShardEvents; + op: WorkerReceivePayloadOp.Event; + shardId: number; +} | { + nonce: number; + op: WorkerReceivePayloadOp.CancelIdentify; +} | { + nonce: number; + op: WorkerReceivePayloadOp.FetchStatusResponse; + status: WebSocketShardStatus; +} | { + nonce: number; + op: WorkerReceivePayloadOp.RetrieveSessionInfo; + shardId: number; +} | { + nonce: number; + op: WorkerReceivePayloadOp.WaitForIdentify; + shardId: number; +} | { + op: WorkerReceivePayloadOp.Connected; + shardId: number; +} | { + op: WorkerReceivePayloadOp.Destroyed; + shardId: number; +} | { + op: WorkerReceivePayloadOp.UpdateSessionInfo; + session: SessionInfo | null; + shardId: number; +} | { + op: WorkerReceivePayloadOp.WorkerReady; +}; +/** + * Options for a {@link WorkerShardingStrategy} + */ +interface WorkerShardingStrategyOptions { + /** + * Dictates how many shards should be spawned per worker thread. + */ + shardsPerWorker: number | 'all'; + /** + * Path to the worker file to use. The worker requires quite a bit of setup, it is recommended you leverage the {@link WorkerBootstrapper} class. + */ + workerPath?: string; +} +/** + * Strategy used to spawn threads in worker_threads + */ +declare class WorkerShardingStrategy implements IShardingStrategy { + #private; + private readonly manager; + private readonly options; + private readonly connectPromises; + private readonly destroyPromises; + private readonly fetchStatusPromises; + private readonly waitForIdentifyControllers; + private throttler?; + constructor(manager: WebSocketManager, options: WorkerShardingStrategyOptions); + /** + * {@inheritDoc IShardingStrategy.spawn} + */ + spawn(shardIds: number[]): Promise; + /** + * {@inheritDoc IShardingStrategy.connect} + */ + connect(): Promise; + /** + * {@inheritDoc IShardingStrategy.destroy} + */ + destroy(options?: Omit): Promise; + /** + * {@inheritDoc IShardingStrategy.send} + */ + send(shardId: number, data: GatewaySendPayload): void; + /** + * {@inheritDoc IShardingStrategy.fetchStatus} + */ + fetchStatus(): Promise>; + private setupWorker; + private resolveWorkerPath; + private waitForWorkerReady; + private onMessage; + private ensureThrottler; +} + +/** + * Options for bootstrapping the worker + */ +interface BootstrapOptions { + /** + * Shard events to just arbitrarily forward to the parent thread for the manager to emit + * Note: By default, this will include ALL events + * you most likely want to handle dispatch within the worker itself + */ + forwardEvents?: WebSocketShardEvents[]; + /** + * Function to call when a shard is created for additional setup + */ + shardCallback?(shard: WebSocketShard): Awaitable; +} +/** + * Utility class for bootstrapping a worker thread to be used for sharding + */ +declare class WorkerBootstrapper { + /** + * The data passed to the worker thread + */ + protected readonly data: WorkerData; + /** + * The shards that are managed by this worker + */ + protected readonly shards: Collection; + constructor(); + /** + * Helper method to initiate a shard's connection process + */ + protected connect(shardId: number): Promise; + /** + * Helper method to destroy a shard + */ + protected destroy(shardId: number, options?: WebSocketShardDestroyOptions): Promise; + /** + * Helper method to attach event listeners to the parentPort + */ + protected setupThreadEvents(): void; + /** + * Bootstraps the worker thread with the provided options + */ + bootstrap(options?: Readonly): Promise; +} + +/** + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/ws/#readme | @discordjs/ws} version + * that you are currently using. + */ +declare const version: string; + +export { BootstrapOptions, CloseCodes, CompressionMethod, DefaultDeviceProperty, DefaultWebSocketManagerOptions, Encoding, FetchingStrategyOptions, IContextFetchingStrategy, IIdentifyThrottler, IShardingStrategy, IdentifyState, ImportantGatewayOpcodes, ManagerShardEventsMap, OptionalWebSocketManagerOptions, RequiredWebSocketManagerOptions, SendRateLimitState, SessionInfo, ShardRange, SimpleContextFetchingStrategy, SimpleIdentifyThrottler, SimpleShardingStrategy, WebSocketManager, WebSocketManagerOptions, WebSocketShard, WebSocketShardDestroyOptions, WebSocketShardDestroyRecovery, WebSocketShardEvents, WebSocketShardEventsMap, WebSocketShardStatus, WorkerBootstrapper, WorkerContextFetchingStrategy, WorkerData, WorkerReceivePayload, WorkerReceivePayloadOp, WorkerSendPayload, WorkerSendPayloadOp, WorkerShardingStrategy, WorkerShardingStrategyOptions, getInitialSendRateLimitState, managerToFetchingStrategyOptions, version }; diff --git a/node_modules/@discordjs/ws/dist/index.js b/node_modules/@discordjs/ws/dist/index.js new file mode 100644 index 0000000..3440c07 --- /dev/null +++ b/node_modules/@discordjs/ws/dist/index.js @@ -0,0 +1,1409 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + CloseCodes: () => CloseCodes, + CompressionMethod: () => CompressionMethod, + DefaultDeviceProperty: () => DefaultDeviceProperty, + DefaultWebSocketManagerOptions: () => DefaultWebSocketManagerOptions, + Encoding: () => Encoding, + ImportantGatewayOpcodes: () => ImportantGatewayOpcodes, + SimpleContextFetchingStrategy: () => SimpleContextFetchingStrategy, + SimpleIdentifyThrottler: () => SimpleIdentifyThrottler, + SimpleShardingStrategy: () => SimpleShardingStrategy, + WebSocketManager: () => WebSocketManager, + WebSocketShard: () => WebSocketShard, + WebSocketShardDestroyRecovery: () => WebSocketShardDestroyRecovery, + WebSocketShardEvents: () => WebSocketShardEvents, + WebSocketShardStatus: () => WebSocketShardStatus, + WorkerBootstrapper: () => WorkerBootstrapper, + WorkerContextFetchingStrategy: () => WorkerContextFetchingStrategy, + WorkerReceivePayloadOp: () => WorkerReceivePayloadOp, + WorkerSendPayloadOp: () => WorkerSendPayloadOp, + WorkerShardingStrategy: () => WorkerShardingStrategy, + getInitialSendRateLimitState: () => getInitialSendRateLimitState, + managerToFetchingStrategyOptions: () => managerToFetchingStrategyOptions, + version: () => version +}); +module.exports = __toCommonJS(src_exports); + +// src/strategies/context/IContextFetchingStrategy.ts +async function managerToFetchingStrategyOptions(manager) { + const { + buildIdentifyThrottler, + buildStrategy, + retrieveSessionInfo, + updateSessionInfo, + shardCount, + shardIds, + rest, + ...managerOptions + } = manager.options; + return { + ...managerOptions, + gatewayInformation: await manager.fetchGatewayInformation(), + shardCount: await manager.getShardCount() + }; +} +__name(managerToFetchingStrategyOptions, "managerToFetchingStrategyOptions"); + +// src/strategies/context/SimpleContextFetchingStrategy.ts +var _SimpleContextFetchingStrategy = class { + constructor(manager, options) { + this.manager = manager; + this.options = options; + } + static async ensureThrottler(manager) { + const throttler = _SimpleContextFetchingStrategy.throttlerCache.get(manager); + if (throttler) { + return throttler; + } + const newThrottler = await manager.options.buildIdentifyThrottler(manager); + _SimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler); + return newThrottler; + } + async retrieveSessionInfo(shardId) { + return this.manager.options.retrieveSessionInfo(shardId); + } + updateSessionInfo(shardId, sessionInfo) { + return this.manager.options.updateSessionInfo(shardId, sessionInfo); + } + async waitForIdentify(shardId, signal) { + const throttler = await _SimpleContextFetchingStrategy.ensureThrottler(this.manager); + await throttler.waitForIdentify(shardId, signal); + } +}; +var SimpleContextFetchingStrategy = _SimpleContextFetchingStrategy; +__name(SimpleContextFetchingStrategy, "SimpleContextFetchingStrategy"); +// This strategy assumes every shard is running under the same process - therefore we need a single +// IdentifyThrottler per manager. +__publicField(SimpleContextFetchingStrategy, "throttlerCache", /* @__PURE__ */ new WeakMap()); + +// src/strategies/context/WorkerContextFetchingStrategy.ts +var import_node_worker_threads2 = require("worker_threads"); +var import_collection2 = require("@discordjs/collection"); + +// src/strategies/sharding/WorkerShardingStrategy.ts +var import_node_events = require("events"); +var import_node_path = require("path"); +var import_node_worker_threads = require("worker_threads"); +var import_collection = require("@discordjs/collection"); +var WorkerSendPayloadOp = /* @__PURE__ */ ((WorkerSendPayloadOp2) => { + WorkerSendPayloadOp2[WorkerSendPayloadOp2["Connect"] = 0] = "Connect"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["Destroy"] = 1] = "Destroy"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["Send"] = 2] = "Send"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["SessionInfoResponse"] = 3] = "SessionInfoResponse"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["ShardIdentifyResponse"] = 4] = "ShardIdentifyResponse"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["FetchStatus"] = 5] = "FetchStatus"; + return WorkerSendPayloadOp2; +})(WorkerSendPayloadOp || {}); +var WorkerReceivePayloadOp = /* @__PURE__ */ ((WorkerReceivePayloadOp2) => { + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["Connected"] = 0] = "Connected"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["Destroyed"] = 1] = "Destroyed"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["Event"] = 2] = "Event"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["RetrieveSessionInfo"] = 3] = "RetrieveSessionInfo"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["UpdateSessionInfo"] = 4] = "UpdateSessionInfo"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["WaitForIdentify"] = 5] = "WaitForIdentify"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["FetchStatusResponse"] = 6] = "FetchStatusResponse"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["WorkerReady"] = 7] = "WorkerReady"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["CancelIdentify"] = 8] = "CancelIdentify"; + return WorkerReceivePayloadOp2; +})(WorkerReceivePayloadOp || {}); +var WorkerShardingStrategy = class { + manager; + options; + #workers = []; + #workerByShardId = new import_collection.Collection(); + connectPromises = new import_collection.Collection(); + destroyPromises = new import_collection.Collection(); + fetchStatusPromises = new import_collection.Collection(); + waitForIdentifyControllers = new import_collection.Collection(); + throttler; + constructor(manager, options) { + this.manager = manager; + this.options = options; + } + /** + * {@inheritDoc IShardingStrategy.spawn} + */ + async spawn(shardIds) { + const shardsPerWorker = this.options.shardsPerWorker === "all" ? shardIds.length : this.options.shardsPerWorker; + const strategyOptions = await managerToFetchingStrategyOptions(this.manager); + const loops = Math.ceil(shardIds.length / shardsPerWorker); + const promises = []; + for (let idx = 0; idx < loops; idx++) { + const slice = shardIds.slice(idx * shardsPerWorker, (idx + 1) * shardsPerWorker); + const workerData2 = { + ...strategyOptions, + shardIds: slice + }; + promises.push(this.setupWorker(workerData2)); + } + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.connect} + */ + async connect() { + const promises = []; + for (const [shardId, worker] of this.#workerByShardId.entries()) { + const payload = { + op: 0 /* Connect */, + shardId + }; + const promise = new Promise((resolve2) => this.connectPromises.set(shardId, resolve2)); + worker.postMessage(payload); + promises.push(promise); + } + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.destroy} + */ + async destroy(options = {}) { + const promises = []; + for (const [shardId, worker] of this.#workerByShardId.entries()) { + const payload = { + op: 1 /* Destroy */, + shardId, + options + }; + promises.push( + // eslint-disable-next-line no-promise-executor-return, promise/prefer-await-to-then + new Promise((resolve2) => this.destroyPromises.set(shardId, resolve2)).then(async () => worker.terminate()) + ); + worker.postMessage(payload); + } + this.#workers = []; + this.#workerByShardId.clear(); + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.send} + */ + send(shardId, data) { + const worker = this.#workerByShardId.get(shardId); + if (!worker) { + throw new Error(`No worker found for shard ${shardId}`); + } + const payload = { + op: 2 /* Send */, + shardId, + payload: data + }; + worker.postMessage(payload); + } + /** + * {@inheritDoc IShardingStrategy.fetchStatus} + */ + async fetchStatus() { + const statuses = new import_collection.Collection(); + for (const [shardId, worker] of this.#workerByShardId.entries()) { + const nonce = Math.random(); + const payload = { + op: 5 /* FetchStatus */, + shardId, + nonce + }; + const promise = new Promise((resolve2) => this.fetchStatusPromises.set(nonce, resolve2)); + worker.postMessage(payload); + const status = await promise; + statuses.set(shardId, status); + } + return statuses; + } + async setupWorker(workerData2) { + const worker = new import_node_worker_threads.Worker(this.resolveWorkerPath(), { workerData: workerData2 }); + await (0, import_node_events.once)(worker, "online"); + await this.waitForWorkerReady(worker); + worker.on("error", (err) => { + throw err; + }).on("messageerror", (err) => { + throw err; + }).on("message", async (payload) => this.onMessage(worker, payload)); + this.#workers.push(worker); + for (const shardId of workerData2.shardIds) { + this.#workerByShardId.set(shardId, worker); + } + } + resolveWorkerPath() { + const path = this.options.workerPath; + if (!path) { + return (0, import_node_path.join)(__dirname, "defaultWorker.js"); + } + if ((0, import_node_path.isAbsolute)(path)) { + return path; + } + if (/^\.\.?[/\\]/.test(path)) { + return (0, import_node_path.resolve)(path); + } + try { + return require.resolve(path); + } catch { + return (0, import_node_path.resolve)(path); + } + } + async waitForWorkerReady(worker) { + return new Promise((resolve2) => { + const handler = /* @__PURE__ */ __name((payload) => { + if (payload.op === 7 /* WorkerReady */) { + resolve2(); + worker.off("message", handler); + } + }, "handler"); + worker.on("message", handler); + }); + } + async onMessage(worker, payload) { + switch (payload.op) { + case 0 /* Connected */: { + this.connectPromises.get(payload.shardId)?.(); + this.connectPromises.delete(payload.shardId); + break; + } + case 1 /* Destroyed */: { + this.destroyPromises.get(payload.shardId)?.(); + this.destroyPromises.delete(payload.shardId); + break; + } + case 2 /* Event */: { + this.manager.emit(payload.event, { ...payload.data, shardId: payload.shardId }); + break; + } + case 3 /* RetrieveSessionInfo */: { + const session = await this.manager.options.retrieveSessionInfo(payload.shardId); + const response = { + op: 3 /* SessionInfoResponse */, + nonce: payload.nonce, + session + }; + worker.postMessage(response); + break; + } + case 4 /* UpdateSessionInfo */: { + await this.manager.options.updateSessionInfo(payload.shardId, payload.session); + break; + } + case 5 /* WaitForIdentify */: { + const throttler = await this.ensureThrottler(); + try { + const controller = new AbortController(); + this.waitForIdentifyControllers.set(payload.nonce, controller); + await throttler.waitForIdentify(payload.shardId, controller.signal); + } catch { + return; + } + const response = { + op: 4 /* ShardIdentifyResponse */, + nonce: payload.nonce, + ok: true + }; + worker.postMessage(response); + break; + } + case 6 /* FetchStatusResponse */: { + this.fetchStatusPromises.get(payload.nonce)?.(payload.status); + this.fetchStatusPromises.delete(payload.nonce); + break; + } + case 7 /* WorkerReady */: { + break; + } + case 8 /* CancelIdentify */: { + this.waitForIdentifyControllers.get(payload.nonce)?.abort(); + this.waitForIdentifyControllers.delete(payload.nonce); + const response = { + op: 4 /* ShardIdentifyResponse */, + nonce: payload.nonce, + ok: false + }; + worker.postMessage(response); + break; + } + } + } + async ensureThrottler() { + this.throttler ??= await this.manager.options.buildIdentifyThrottler(this.manager); + return this.throttler; + } +}; +__name(WorkerShardingStrategy, "WorkerShardingStrategy"); + +// src/strategies/context/WorkerContextFetchingStrategy.ts +var WorkerContextFetchingStrategy = class { + constructor(options) { + this.options = options; + if (import_node_worker_threads2.isMainThread) { + throw new Error("Cannot instantiate WorkerContextFetchingStrategy on the main thread"); + } + import_node_worker_threads2.parentPort.on("message", (payload) => { + if (payload.op === 3 /* SessionInfoResponse */) { + this.sessionPromises.get(payload.nonce)?.(payload.session); + this.sessionPromises.delete(payload.nonce); + } + if (payload.op === 4 /* ShardIdentifyResponse */) { + const promise = this.waitForIdentifyPromises.get(payload.nonce); + if (payload.ok) { + promise?.resolve(); + } else { + promise?.reject(); + } + this.waitForIdentifyPromises.delete(payload.nonce); + } + }); + } + sessionPromises = new import_collection2.Collection(); + waitForIdentifyPromises = new import_collection2.Collection(); + async retrieveSessionInfo(shardId) { + const nonce = Math.random(); + const payload = { + op: 3 /* RetrieveSessionInfo */, + shardId, + nonce + }; + const promise = new Promise((resolve2) => this.sessionPromises.set(nonce, resolve2)); + import_node_worker_threads2.parentPort.postMessage(payload); + return promise; + } + updateSessionInfo(shardId, sessionInfo) { + const payload = { + op: 4 /* UpdateSessionInfo */, + shardId, + session: sessionInfo + }; + import_node_worker_threads2.parentPort.postMessage(payload); + } + async waitForIdentify(shardId, signal) { + const nonce = Math.random(); + const payload = { + op: 5 /* WaitForIdentify */, + nonce, + shardId + }; + const promise = new Promise( + (resolve2, reject) => ( + // eslint-disable-next-line no-promise-executor-return + this.waitForIdentifyPromises.set(nonce, { resolve: resolve2, reject }) + ) + ); + import_node_worker_threads2.parentPort.postMessage(payload); + const listener = /* @__PURE__ */ __name(() => { + const payload2 = { + op: 8 /* CancelIdentify */, + nonce + }; + import_node_worker_threads2.parentPort.postMessage(payload2); + }, "listener"); + signal.addEventListener("abort", listener); + try { + await promise; + } finally { + signal.removeEventListener("abort", listener); + } + } +}; +__name(WorkerContextFetchingStrategy, "WorkerContextFetchingStrategy"); + +// src/strategies/sharding/SimpleShardingStrategy.ts +var import_collection6 = require("@discordjs/collection"); + +// src/ws/WebSocketShard.ts +var import_node_buffer = require("buffer"); +var import_node_events2 = require("events"); +var import_node_timers = require("timers"); +var import_promises2 = require("timers/promises"); +var import_node_url = require("url"); +var import_node_util = require("util"); +var import_node_zlib = require("zlib"); +var import_collection5 = require("@discordjs/collection"); +var import_util2 = require("@discordjs/util"); +var import_async_queue2 = require("@sapphire/async-queue"); +var import_async_event_emitter = require("@vladfrangu/async_event_emitter"); +var import_v102 = require("discord-api-types/v10"); +var import_ws = require("ws"); + +// src/utils/constants.ts +var import_node_process = __toESM(require("process")); +var import_collection4 = require("@discordjs/collection"); +var import_util = require("@discordjs/util"); +var import_v10 = require("discord-api-types/v10"); + +// src/throttling/SimpleIdentifyThrottler.ts +var import_promises = require("timers/promises"); +var import_collection3 = require("@discordjs/collection"); +var import_async_queue = require("@sapphire/async-queue"); +var SimpleIdentifyThrottler = class { + constructor(maxConcurrency) { + this.maxConcurrency = maxConcurrency; + } + states = new import_collection3.Collection(); + /** + * {@inheritDoc IIdentifyThrottler.waitForIdentify} + */ + async waitForIdentify(shardId, signal) { + const key = shardId % this.maxConcurrency; + const state = this.states.ensure(key, () => { + return { + queue: new import_async_queue.AsyncQueue(), + resetsAt: Number.POSITIVE_INFINITY + }; + }); + await state.queue.wait({ signal }); + try { + const diff = state.resetsAt - Date.now(); + if (diff <= 5e3) { + const time = diff + Math.random() * 1500; + await (0, import_promises.setTimeout)(time); + } + state.resetsAt = Date.now() + 5e3; + } finally { + state.queue.shift(); + } + } +}; +__name(SimpleIdentifyThrottler, "SimpleIdentifyThrottler"); + +// src/utils/constants.ts +var Encoding = /* @__PURE__ */ ((Encoding2) => { + Encoding2["JSON"] = "json"; + return Encoding2; +})(Encoding || {}); +var CompressionMethod = /* @__PURE__ */ ((CompressionMethod2) => { + CompressionMethod2["ZlibStream"] = "zlib-stream"; + return CompressionMethod2; +})(CompressionMethod || {}); +var DefaultDeviceProperty = `@discordjs/ws 0.8.3`; +var getDefaultSessionStore = (0, import_util.lazy)(() => new import_collection4.Collection()); +var DefaultWebSocketManagerOptions = { + async buildIdentifyThrottler(manager) { + const info = await manager.fetchGatewayInformation(); + return new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency); + }, + buildStrategy: (manager) => new SimpleShardingStrategy(manager), + shardCount: null, + shardIds: null, + largeThreshold: null, + initialPresence: null, + identifyProperties: { + browser: DefaultDeviceProperty, + device: DefaultDeviceProperty, + os: import_node_process.default.platform + }, + version: import_v10.APIVersion, + encoding: "json" /* JSON */, + compression: null, + retrieveSessionInfo(shardId) { + const store = getDefaultSessionStore(); + return store.get(shardId) ?? null; + }, + updateSessionInfo(shardId, info) { + const store = getDefaultSessionStore(); + if (info) { + store.set(shardId, info); + } else { + store.delete(shardId); + } + }, + handshakeTimeout: 3e4, + helloTimeout: 6e4, + readyTimeout: 15e3 +}; +var ImportantGatewayOpcodes = /* @__PURE__ */ new Set([ + import_v10.GatewayOpcodes.Heartbeat, + import_v10.GatewayOpcodes.Identify, + import_v10.GatewayOpcodes.Resume +]); +function getInitialSendRateLimitState() { + return { + remaining: 120, + resetAt: Date.now() + 6e4 + }; +} +__name(getInitialSendRateLimitState, "getInitialSendRateLimitState"); + +// src/ws/WebSocketShard.ts +var getZlibSync = (0, import_util2.lazy)(async () => import("zlib-sync").then((mod) => mod.default).catch(() => null)); +var WebSocketShardEvents = /* @__PURE__ */ ((WebSocketShardEvents2) => { + WebSocketShardEvents2["Closed"] = "closed"; + WebSocketShardEvents2["Debug"] = "debug"; + WebSocketShardEvents2["Dispatch"] = "dispatch"; + WebSocketShardEvents2["Error"] = "error"; + WebSocketShardEvents2["HeartbeatComplete"] = "heartbeat"; + WebSocketShardEvents2["Hello"] = "hello"; + WebSocketShardEvents2["Ready"] = "ready"; + WebSocketShardEvents2["Resumed"] = "resumed"; + return WebSocketShardEvents2; +})(WebSocketShardEvents || {}); +var WebSocketShardStatus = /* @__PURE__ */ ((WebSocketShardStatus2) => { + WebSocketShardStatus2[WebSocketShardStatus2["Idle"] = 0] = "Idle"; + WebSocketShardStatus2[WebSocketShardStatus2["Connecting"] = 1] = "Connecting"; + WebSocketShardStatus2[WebSocketShardStatus2["Resuming"] = 2] = "Resuming"; + WebSocketShardStatus2[WebSocketShardStatus2["Ready"] = 3] = "Ready"; + return WebSocketShardStatus2; +})(WebSocketShardStatus || {}); +var WebSocketShardDestroyRecovery = /* @__PURE__ */ ((WebSocketShardDestroyRecovery2) => { + WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Reconnect"] = 0] = "Reconnect"; + WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Resume"] = 1] = "Resume"; + return WebSocketShardDestroyRecovery2; +})(WebSocketShardDestroyRecovery || {}); +var CloseCodes = /* @__PURE__ */ ((CloseCodes2) => { + CloseCodes2[CloseCodes2["Normal"] = 1e3] = "Normal"; + CloseCodes2[CloseCodes2["Resuming"] = 4200] = "Resuming"; + return CloseCodes2; +})(CloseCodes || {}); +var WebSocketShard = class extends import_async_event_emitter.AsyncEventEmitter { + connection = null; + useIdentifyCompress = false; + inflate = null; + textDecoder = new import_node_util.TextDecoder(); + replayedEvents = 0; + isAck = true; + sendRateLimitState = getInitialSendRateLimitState(); + initialHeartbeatTimeoutController = null; + heartbeatInterval = null; + lastHeartbeatAt = -1; + // Indicates whether the shard has already resolved its original connect() call + initialConnectResolved = false; + // Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET) + failedToConnectDueToNetworkError = false; + sendQueue = new import_async_queue2.AsyncQueue(); + timeoutAbortControllers = new import_collection5.Collection(); + strategy; + id; + #status = 0 /* Idle */; + get status() { + return this.#status; + } + constructor(strategy, id) { + super(); + this.strategy = strategy; + this.id = id; + } + async connect() { + const promise = this.initialConnectResolved ? Promise.resolve() : (0, import_node_events2.once)(this, "ready" /* Ready */); + void this.internalConnect(); + await promise; + this.initialConnectResolved = true; + } + async internalConnect() { + if (this.#status !== 0 /* Idle */) { + throw new Error("Tried to connect a shard that wasn't idle"); + } + const { version: version2, encoding, compression } = this.strategy.options; + const params = new import_node_url.URLSearchParams({ v: version2, encoding }); + if (compression) { + const zlib = await getZlibSync(); + if (zlib) { + params.append("compress", compression); + this.inflate = new zlib.Inflate({ + chunkSize: 65535, + to: "string" + }); + } else if (!this.useIdentifyCompress) { + this.useIdentifyCompress = true; + console.warn( + "WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress" + ); + } + } + const session = await this.strategy.retrieveSessionInfo(this.id); + const url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`; + this.debug([`Connecting to ${url}`]); + const connection = new import_ws.WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? void 0 }).on("message", this.onMessage.bind(this)).on("error", this.onError.bind(this)).on("close", this.onClose.bind(this)); + connection.binaryType = "arraybuffer"; + this.connection = connection; + this.#status = 1 /* Connecting */; + this.sendRateLimitState = getInitialSendRateLimitState(); + const { ok } = await this.waitForEvent("hello" /* Hello */, this.strategy.options.helloTimeout); + if (!ok) { + return; + } + if (session?.shardCount === this.strategy.options.shardCount) { + await this.resume(session); + } else { + await this.identify(); + } + } + async destroy(options = {}) { + if (this.#status === 0 /* Idle */) { + this.debug(["Tried to destroy a shard that was idle"]); + return; + } + if (!options.code) { + options.code = options.recover === 1 /* Resume */ ? 4200 /* Resuming */ : 1e3 /* Normal */; + } + this.debug([ + "Destroying shard", + `Reason: ${options.reason ?? "none"}`, + `Code: ${options.code}`, + `Recover: ${options.recover === void 0 ? "none" : WebSocketShardDestroyRecovery[options.recover]}` + ]); + this.isAck = true; + if (this.heartbeatInterval) { + (0, import_node_timers.clearInterval)(this.heartbeatInterval); + } + if (this.initialHeartbeatTimeoutController) { + this.initialHeartbeatTimeoutController.abort(); + this.initialHeartbeatTimeoutController = null; + } + this.lastHeartbeatAt = -1; + for (const controller of this.timeoutAbortControllers.values()) { + controller.abort(); + } + this.timeoutAbortControllers.clear(); + this.failedToConnectDueToNetworkError = false; + if (options.recover !== 1 /* Resume */) { + await this.strategy.updateSessionInfo(this.id, null); + } + if (this.connection) { + this.connection.removeAllListeners("message"); + this.connection.removeAllListeners("close"); + const shouldClose = this.connection.readyState === import_ws.WebSocket.OPEN; + this.debug([ + "Connection status during destroy", + `Needs closing: ${shouldClose}`, + `Ready state: ${this.connection.readyState}` + ]); + if (shouldClose) { + this.connection.close(options.code, options.reason); + await (0, import_node_events2.once)(this.connection, "close"); + this.emit("closed" /* Closed */, { code: options.code }); + } + this.connection.removeAllListeners("error"); + } else { + this.debug(["Destroying a shard that has no connection; please open an issue on GitHub"]); + } + this.#status = 0 /* Idle */; + if (options.recover !== void 0) { + await (0, import_promises2.setTimeout)(500); + return this.internalConnect(); + } + } + async waitForEvent(event, timeoutDuration) { + this.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : "indefinitely"}`]); + const timeoutController = new AbortController(); + const timeout = timeoutDuration ? (0, import_node_timers.setTimeout)(() => timeoutController.abort(), timeoutDuration).unref() : null; + this.timeoutAbortControllers.set(event, timeoutController); + const closeController = new AbortController(); + try { + const closed = await Promise.race([ + (0, import_node_events2.once)(this, event, { signal: timeoutController.signal }).then(() => false), + (0, import_node_events2.once)(this, "closed" /* Closed */, { signal: closeController.signal }).then(() => true) + ]); + return { ok: !closed }; + } catch { + void this.destroy({ + code: 1e3 /* Normal */, + reason: "Something timed out or went wrong while waiting for an event", + recover: 0 /* Reconnect */ + }); + return { ok: false }; + } finally { + if (timeout) { + (0, import_node_timers.clearTimeout)(timeout); + } + this.timeoutAbortControllers.delete(event); + if (!closeController.signal.aborted) { + closeController.abort(); + } + } + } + async send(payload) { + if (!this.connection) { + throw new Error("WebSocketShard wasn't connected"); + } + if (this.#status !== 3 /* Ready */ && !ImportantGatewayOpcodes.has(payload.op)) { + this.debug(["Tried to send a non-crucial payload before the shard was ready, waiting"]); + try { + await (0, import_node_events2.once)(this, "ready" /* Ready */); + } catch { + return this.send(payload); + } + } + await this.sendQueue.wait(); + if (--this.sendRateLimitState.remaining <= 0) { + const now = Date.now(); + if (this.sendRateLimitState.resetAt > now) { + const sleepFor = this.sendRateLimitState.resetAt - now; + this.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]); + const controller = new AbortController(); + const interrupted = await Promise.race([ + (0, import_promises2.setTimeout)(sleepFor).then(() => false), + (0, import_node_events2.once)(this, "closed" /* Closed */, { signal: controller.signal }).then(() => true) + ]); + if (interrupted) { + this.debug(["Connection closed while waiting for the send rate limit to reset, re-queueing payload"]); + this.sendQueue.shift(); + return this.send(payload); + } + controller.abort(); + } + this.sendRateLimitState = getInitialSendRateLimitState(); + } + this.sendQueue.shift(); + this.connection.send(JSON.stringify(payload)); + } + async identify() { + this.debug(["Waiting for identify throttle"]); + const controller = new AbortController(); + const closeHandler = /* @__PURE__ */ __name(() => { + controller.abort(); + }, "closeHandler"); + this.on("closed" /* Closed */, closeHandler); + try { + await this.strategy.waitForIdentify(this.id, controller.signal); + } catch { + this.debug(["Was waiting for an identify, but the shard closed in the meantime"]); + return; + } finally { + this.off("closed" /* Closed */, closeHandler); + } + this.debug([ + "Identifying", + `shard id: ${this.id.toString()}`, + `shard count: ${this.strategy.options.shardCount}`, + `intents: ${this.strategy.options.intents}`, + `compression: ${this.inflate ? "zlib-stream" : this.useIdentifyCompress ? "identify" : "none"}` + ]); + const d = { + token: this.strategy.options.token, + properties: this.strategy.options.identifyProperties, + intents: this.strategy.options.intents, + compress: this.useIdentifyCompress, + shard: [this.id, this.strategy.options.shardCount] + }; + if (this.strategy.options.largeThreshold) { + d.large_threshold = this.strategy.options.largeThreshold; + } + if (this.strategy.options.initialPresence) { + d.presence = this.strategy.options.initialPresence; + } + await this.send({ + op: import_v102.GatewayOpcodes.Identify, + d + }); + await this.waitForEvent("ready" /* Ready */, this.strategy.options.readyTimeout); + } + async resume(session) { + this.debug([ + "Resuming session", + `resume url: ${session.resumeURL}`, + `sequence: ${session.sequence}`, + `shard id: ${this.id.toString()}` + ]); + this.#status = 2 /* Resuming */; + this.replayedEvents = 0; + return this.send({ + op: import_v102.GatewayOpcodes.Resume, + d: { + token: this.strategy.options.token, + seq: session.sequence, + session_id: session.sessionId + } + }); + } + async heartbeat(requested = false) { + if (!this.isAck && !requested) { + return this.destroy({ reason: "Zombie connection", recover: 1 /* Resume */ }); + } + const session = await this.strategy.retrieveSessionInfo(this.id); + await this.send({ + op: import_v102.GatewayOpcodes.Heartbeat, + d: session?.sequence ?? null + }); + this.lastHeartbeatAt = Date.now(); + this.isAck = false; + } + async unpackMessage(data, isBinary) { + const decompressable = new Uint8Array(data); + if (!isBinary) { + return JSON.parse(this.textDecoder.decode(decompressable)); + } + if (this.useIdentifyCompress) { + return new Promise((resolve2, reject) => { + (0, import_node_zlib.inflate)(decompressable, { chunkSize: 65535 }, (err, result) => { + if (err) { + reject(err); + return; + } + resolve2(JSON.parse(this.textDecoder.decode(result))); + }); + }); + } + if (this.inflate) { + const l = decompressable.length; + const flush = l >= 4 && decompressable[l - 4] === 0 && decompressable[l - 3] === 0 && decompressable[l - 2] === 255 && decompressable[l - 1] === 255; + const zlib = await getZlibSync(); + this.inflate.push(import_node_buffer.Buffer.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH); + if (this.inflate.err) { + this.emit("error" /* Error */, { + error: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ""}`) + }); + } + if (!flush) { + return null; + } + const { result } = this.inflate; + if (!result) { + return null; + } + return JSON.parse(typeof result === "string" ? result : this.textDecoder.decode(result)); + } + this.debug([ + "Received a message we were unable to decompress", + `isBinary: ${isBinary.toString()}`, + `useIdentifyCompress: ${this.useIdentifyCompress.toString()}`, + `inflate: ${Boolean(this.inflate).toString()}` + ]); + return null; + } + async onMessage(data, isBinary) { + const payload = await this.unpackMessage(data, isBinary); + if (!payload) { + return; + } + switch (payload.op) { + case import_v102.GatewayOpcodes.Dispatch: { + if (this.#status === 2 /* Resuming */) { + this.replayedEvents++; + } + switch (payload.t) { + case import_v102.GatewayDispatchEvents.Ready: { + this.#status = 3 /* Ready */; + const session2 = { + sequence: payload.s, + sessionId: payload.d.session_id, + shardId: this.id, + shardCount: this.strategy.options.shardCount, + resumeURL: payload.d.resume_gateway_url + }; + await this.strategy.updateSessionInfo(this.id, session2); + this.emit("ready" /* Ready */, { data: payload.d }); + break; + } + case import_v102.GatewayDispatchEvents.Resumed: { + this.#status = 3 /* Ready */; + this.debug([`Resumed and replayed ${this.replayedEvents} events`]); + this.emit("resumed" /* Resumed */); + break; + } + default: { + break; + } + } + const session = await this.strategy.retrieveSessionInfo(this.id); + if (session) { + if (payload.s > session.sequence) { + await this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s }); + } + } else { + this.debug([ + `Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect` + ]); + } + this.emit("dispatch" /* Dispatch */, { data: payload }); + break; + } + case import_v102.GatewayOpcodes.Heartbeat: { + await this.heartbeat(true); + break; + } + case import_v102.GatewayOpcodes.Reconnect: { + await this.destroy({ + reason: "Told to reconnect by Discord", + recover: 1 /* Resume */ + }); + break; + } + case import_v102.GatewayOpcodes.InvalidSession: { + this.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]); + const session = await this.strategy.retrieveSessionInfo(this.id); + if (payload.d && session) { + await this.resume(session); + } else { + await this.destroy({ + reason: "Invalid session", + recover: 0 /* Reconnect */ + }); + } + break; + } + case import_v102.GatewayOpcodes.Hello: { + this.emit("hello" /* Hello */); + const jitter = Math.random(); + const firstWait = Math.floor(payload.d.heartbeat_interval * jitter); + this.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]); + try { + const controller = new AbortController(); + this.initialHeartbeatTimeoutController = controller; + await (0, import_promises2.setTimeout)(firstWait, void 0, { signal: controller.signal }); + } catch { + this.debug(["Cancelled initial heartbeat due to #destroy being called"]); + return; + } finally { + this.initialHeartbeatTimeoutController = null; + } + await this.heartbeat(); + this.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]); + this.heartbeatInterval = (0, import_node_timers.setInterval)(() => void this.heartbeat(), payload.d.heartbeat_interval); + break; + } + case import_v102.GatewayOpcodes.HeartbeatAck: { + this.isAck = true; + const ackAt = Date.now(); + this.emit("heartbeat" /* HeartbeatComplete */, { + ackAt, + heartbeatAt: this.lastHeartbeatAt, + latency: ackAt - this.lastHeartbeatAt + }); + break; + } + } + } + onError(error) { + if ("code" in error && ["ECONNRESET", "ECONNREFUSED"].includes(error.code)) { + this.debug(["Failed to connect to the gateway URL specified due to a network error"]); + this.failedToConnectDueToNetworkError = true; + return; + } + this.emit("error" /* Error */, { error }); + } + async onClose(code) { + this.emit("closed" /* Closed */, { code }); + switch (code) { + case 1e3 /* Normal */: { + return this.destroy({ + code, + reason: "Got disconnected by Discord", + recover: 0 /* Reconnect */ + }); + } + case 4200 /* Resuming */: { + break; + } + case import_v102.GatewayCloseCodes.UnknownError: { + this.debug([`An unknown error occurred: ${code}`]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case import_v102.GatewayCloseCodes.UnknownOpcode: { + this.debug(["An invalid opcode was sent to Discord."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case import_v102.GatewayCloseCodes.DecodeError: { + this.debug(["An invalid payload was sent to Discord."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case import_v102.GatewayCloseCodes.NotAuthenticated: { + this.debug(["A request was somehow sent before the identify/resume payload."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case import_v102.GatewayCloseCodes.AuthenticationFailed: { + throw new Error("Authentication failed"); + } + case import_v102.GatewayCloseCodes.AlreadyAuthenticated: { + this.debug(["More than one auth payload was sent."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case import_v102.GatewayCloseCodes.InvalidSeq: { + this.debug(["An invalid sequence was sent."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case import_v102.GatewayCloseCodes.RateLimited: { + this.debug(["The WebSocket rate limit has been hit, this should never happen"]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case import_v102.GatewayCloseCodes.SessionTimedOut: { + this.debug(["Session timed out."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case import_v102.GatewayCloseCodes.InvalidShard: { + throw new Error("Invalid shard"); + } + case import_v102.GatewayCloseCodes.ShardingRequired: { + throw new Error("Sharding is required"); + } + case import_v102.GatewayCloseCodes.InvalidAPIVersion: { + throw new Error("Used an invalid API version"); + } + case import_v102.GatewayCloseCodes.InvalidIntents: { + throw new Error("Used invalid intents"); + } + case import_v102.GatewayCloseCodes.DisallowedIntents: { + throw new Error("Used disallowed intents"); + } + default: { + this.debug([ + `The gateway closed with an unexpected code ${code}, attempting to ${this.failedToConnectDueToNetworkError ? "reconnect" : "resume"}.` + ]); + return this.destroy({ + code, + recover: this.failedToConnectDueToNetworkError ? 0 /* Reconnect */ : 1 /* Resume */ + }); + } + } + } + debug(messages) { + const message = `${messages[0]}${messages.length > 1 ? ` +${messages.slice(1).map((m) => ` ${m}`).join("\n")}` : ""}`; + this.emit("debug" /* Debug */, { message }); + } +}; +__name(WebSocketShard, "WebSocketShard"); + +// src/strategies/sharding/SimpleShardingStrategy.ts +var SimpleShardingStrategy = class { + manager; + shards = new import_collection6.Collection(); + constructor(manager) { + this.manager = manager; + } + /** + * {@inheritDoc IShardingStrategy.spawn} + */ + async spawn(shardIds) { + const strategyOptions = await managerToFetchingStrategyOptions(this.manager); + for (const shardId of shardIds) { + const strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions); + const shard = new WebSocketShard(strategy, shardId); + for (const event of Object.values(WebSocketShardEvents)) { + shard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId })); + } + this.shards.set(shardId, shard); + } + } + /** + * {@inheritDoc IShardingStrategy.connect} + */ + async connect() { + const promises = []; + for (const shard of this.shards.values()) { + promises.push(shard.connect()); + } + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.destroy} + */ + async destroy(options) { + const promises = []; + for (const shard of this.shards.values()) { + promises.push(shard.destroy(options)); + } + await Promise.all(promises); + this.shards.clear(); + } + /** + * {@inheritDoc IShardingStrategy.send} + */ + async send(shardId, payload) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} not found`); + } + return shard.send(payload); + } + /** + * {@inheritDoc IShardingStrategy.fetchStatus} + */ + async fetchStatus() { + return this.shards.mapValues((shard) => shard.status); + } +}; +__name(SimpleShardingStrategy, "SimpleShardingStrategy"); + +// src/utils/WorkerBootstrapper.ts +var import_node_worker_threads3 = require("worker_threads"); +var import_collection7 = require("@discordjs/collection"); +var WorkerBootstrapper = class { + /** + * The data passed to the worker thread + */ + data = import_node_worker_threads3.workerData; + /** + * The shards that are managed by this worker + */ + shards = new import_collection7.Collection(); + constructor() { + if (import_node_worker_threads3.isMainThread) { + throw new Error("Expected WorkerBootstrap to not be used within the main thread"); + } + } + /** + * Helper method to initiate a shard's connection process + */ + async connect(shardId) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} does not exist`); + } + await shard.connect(); + } + /** + * Helper method to destroy a shard + */ + async destroy(shardId, options) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} does not exist`); + } + await shard.destroy(options); + } + /** + * Helper method to attach event listeners to the parentPort + */ + setupThreadEvents() { + import_node_worker_threads3.parentPort.on("messageerror", (err) => { + throw err; + }).on("message", async (payload) => { + switch (payload.op) { + case 0 /* Connect */: { + await this.connect(payload.shardId); + const response = { + op: 0 /* Connected */, + shardId: payload.shardId + }; + import_node_worker_threads3.parentPort.postMessage(response); + break; + } + case 1 /* Destroy */: { + await this.destroy(payload.shardId, payload.options); + const response = { + op: 1 /* Destroyed */, + shardId: payload.shardId + }; + import_node_worker_threads3.parentPort.postMessage(response); + break; + } + case 2 /* Send */: { + const shard = this.shards.get(payload.shardId); + if (!shard) { + throw new RangeError(`Shard ${payload.shardId} does not exist`); + } + await shard.send(payload.payload); + break; + } + case 3 /* SessionInfoResponse */: { + break; + } + case 4 /* ShardIdentifyResponse */: { + break; + } + case 5 /* FetchStatus */: { + const shard = this.shards.get(payload.shardId); + if (!shard) { + throw new Error(`Shard ${payload.shardId} does not exist`); + } + const response = { + op: 6 /* FetchStatusResponse */, + status: shard.status, + nonce: payload.nonce + }; + import_node_worker_threads3.parentPort.postMessage(response); + break; + } + } + }); + } + /** + * Bootstraps the worker thread with the provided options + */ + async bootstrap(options = {}) { + for (const shardId of this.data.shardIds) { + const shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId); + for (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) { + shard.on(event, (data) => { + const payload = { + op: 2 /* Event */, + event, + data, + shardId + }; + import_node_worker_threads3.parentPort.postMessage(payload); + }); + } + await options.shardCallback?.(shard); + this.shards.set(shardId, shard); + } + this.setupThreadEvents(); + const message = { + op: 7 /* WorkerReady */ + }; + import_node_worker_threads3.parentPort.postMessage(message); + } +}; +__name(WorkerBootstrapper, "WorkerBootstrapper"); + +// src/ws/WebSocketManager.ts +var import_util3 = require("@discordjs/util"); +var import_async_event_emitter2 = require("@vladfrangu/async_event_emitter"); +var import_v103 = require("discord-api-types/v10"); +var WebSocketManager = class extends import_async_event_emitter2.AsyncEventEmitter { + /** + * The options being used by this manager + */ + options; + /** + * Internal cache for a GET /gateway/bot result + */ + gatewayInformation = null; + /** + * Internal cache for the shard ids + */ + shardIds = null; + /** + * Strategy used to manage shards + * + * @defaultValue `SimpleShardingStrategy` + */ + strategy; + constructor(options) { + super(); + this.options = { ...DefaultWebSocketManagerOptions, ...options }; + this.strategy = this.options.buildStrategy(this); + } + /** + * Fetches the gateway information from Discord - or returns it from cache if available + * + * @param force - Whether to ignore the cache and force a fresh fetch + */ + async fetchGatewayInformation(force = false) { + if (this.gatewayInformation) { + if (this.gatewayInformation.expiresAt <= Date.now()) { + this.gatewayInformation = null; + } else if (!force) { + return this.gatewayInformation.data; + } + } + const data = await this.options.rest.get(import_v103.Routes.gatewayBot()); + this.gatewayInformation = { data, expiresAt: Date.now() + data.session_start_limit.reset_after }; + return this.gatewayInformation.data; + } + /** + * Updates your total shard count on-the-fly, spawning shards as needed + * + * @param shardCount - The new shard count to use + */ + async updateShardCount(shardCount) { + await this.strategy.destroy({ reason: "User is adjusting their shards" }); + this.options.shardCount = shardCount; + const shardIds = await this.getShardIds(true); + await this.strategy.spawn(shardIds); + return this; + } + /** + * Yields the total number of shards across for your bot, accounting for Discord recommendations + */ + async getShardCount() { + if (this.options.shardCount) { + return this.options.shardCount; + } + const shardIds = await this.getShardIds(); + return Math.max(...shardIds) + 1; + } + /** + * Yields the ids of the shards this manager should manage + */ + async getShardIds(force = false) { + if (this.shardIds && !force) { + return this.shardIds; + } + let shardIds; + if (this.options.shardIds) { + if (Array.isArray(this.options.shardIds)) { + shardIds = this.options.shardIds; + } else { + const { start, end } = this.options.shardIds; + shardIds = [...(0, import_util3.range)({ start, end: end + 1 })]; + } + } else { + const data = await this.fetchGatewayInformation(); + shardIds = [...(0, import_util3.range)(this.options.shardCount ?? data.shards)]; + } + this.shardIds = shardIds; + return shardIds; + } + async connect() { + const shardCount = await this.getShardCount(); + const data = await this.fetchGatewayInformation(); + if (data.session_start_limit.remaining < shardCount) { + throw new Error( + `Not enough sessions remaining to spawn ${shardCount} shards; only ${data.session_start_limit.remaining} remaining; resets at ${new Date(Date.now() + data.session_start_limit.reset_after).toISOString()}` + ); + } + await this.updateShardCount(shardCount); + await this.strategy.connect(); + } + destroy(options) { + return this.strategy.destroy(options); + } + send(shardId, payload) { + return this.strategy.send(shardId, payload); + } + fetchStatus() { + return this.strategy.fetchStatus(); + } +}; +__name(WebSocketManager, "WebSocketManager"); + +// src/index.ts +var version = "0.8.3"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + CloseCodes, + CompressionMethod, + DefaultDeviceProperty, + DefaultWebSocketManagerOptions, + Encoding, + ImportantGatewayOpcodes, + SimpleContextFetchingStrategy, + SimpleIdentifyThrottler, + SimpleShardingStrategy, + WebSocketManager, + WebSocketShard, + WebSocketShardDestroyRecovery, + WebSocketShardEvents, + WebSocketShardStatus, + WorkerBootstrapper, + WorkerContextFetchingStrategy, + WorkerReceivePayloadOp, + WorkerSendPayloadOp, + WorkerShardingStrategy, + getInitialSendRateLimitState, + managerToFetchingStrategyOptions, + version +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/ws/dist/index.js.map b/node_modules/@discordjs/ws/dist/index.js.map new file mode 100644 index 0000000..c141a4a --- /dev/null +++ b/node_modules/@discordjs/ws/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/strategies/context/IContextFetchingStrategy.ts","../src/strategies/context/SimpleContextFetchingStrategy.ts","../src/strategies/context/WorkerContextFetchingStrategy.ts","../src/strategies/sharding/WorkerShardingStrategy.ts","../src/strategies/sharding/SimpleShardingStrategy.ts","../src/ws/WebSocketShard.ts","../src/utils/constants.ts","../src/throttling/SimpleIdentifyThrottler.ts","../src/utils/WorkerBootstrapper.ts","../src/ws/WebSocketManager.ts"],"sourcesContent":["export * from './strategies/context/IContextFetchingStrategy.js';\nexport * from './strategies/context/SimpleContextFetchingStrategy.js';\nexport * from './strategies/context/WorkerContextFetchingStrategy.js';\n\nexport * from './strategies/sharding/IShardingStrategy.js';\nexport * from './strategies/sharding/SimpleShardingStrategy.js';\nexport * from './strategies/sharding/WorkerShardingStrategy.js';\n\nexport * from './throttling/IIdentifyThrottler.js';\nexport * from './throttling/SimpleIdentifyThrottler.js';\n\nexport * from './utils/constants.js';\nexport * from './utils/WorkerBootstrapper.js';\n\nexport * from './ws/WebSocketManager.js';\nexport * from './ws/WebSocketShard.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/ws/#readme | @discordjs/ws} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '0.8.3' as string;\n","import type { Awaitable } from '@discordjs/util';\nimport type { APIGatewayBotInfo } from 'discord-api-types/v10';\nimport type { SessionInfo, WebSocketManager, WebSocketManagerOptions } from '../../ws/WebSocketManager.js';\n\nexport interface FetchingStrategyOptions\n\textends Omit<\n\t\tWebSocketManagerOptions,\n\t\t| 'buildIdentifyThrottler'\n\t\t| 'buildStrategy'\n\t\t| 'rest'\n\t\t| 'retrieveSessionInfo'\n\t\t| 'shardCount'\n\t\t| 'shardIds'\n\t\t| 'updateSessionInfo'\n\t> {\n\treadonly gatewayInformation: APIGatewayBotInfo;\n\treadonly shardCount: number;\n}\n\n/**\n * Strategies responsible solely for making manager information accessible\n */\nexport interface IContextFetchingStrategy {\n\treadonly options: FetchingStrategyOptions;\n\tretrieveSessionInfo(shardId: number): Awaitable;\n\tupdateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable;\n\t/**\n\t * Resolves once the given shard should be allowed to identify, or rejects if the operation was aborted\n\t */\n\twaitForIdentify(shardId: number, signal: AbortSignal): Promise;\n}\n\nexport async function managerToFetchingStrategyOptions(manager: WebSocketManager): Promise {\n\t/* eslint-disable @typescript-eslint/unbound-method */\n\tconst {\n\t\tbuildIdentifyThrottler,\n\t\tbuildStrategy,\n\t\tretrieveSessionInfo,\n\t\tupdateSessionInfo,\n\t\tshardCount,\n\t\tshardIds,\n\t\trest,\n\t\t...managerOptions\n\t} = manager.options;\n\t/* eslint-enable @typescript-eslint/unbound-method */\n\n\treturn {\n\t\t...managerOptions,\n\t\tgatewayInformation: await manager.fetchGatewayInformation(),\n\t\tshardCount: await manager.getShardCount(),\n\t};\n}\n","import type { IIdentifyThrottler } from '../../throttling/IIdentifyThrottler.js';\nimport type { SessionInfo, WebSocketManager } from '../../ws/WebSocketManager.js';\nimport type { FetchingStrategyOptions, IContextFetchingStrategy } from './IContextFetchingStrategy.js';\n\nexport class SimpleContextFetchingStrategy implements IContextFetchingStrategy {\n\t// This strategy assumes every shard is running under the same process - therefore we need a single\n\t// IdentifyThrottler per manager.\n\tprivate static throttlerCache = new WeakMap();\n\n\tprivate static async ensureThrottler(manager: WebSocketManager): Promise {\n\t\tconst throttler = SimpleContextFetchingStrategy.throttlerCache.get(manager);\n\t\tif (throttler) {\n\t\t\treturn throttler;\n\t\t}\n\n\t\tconst newThrottler = await manager.options.buildIdentifyThrottler(manager);\n\t\tSimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler);\n\n\t\treturn newThrottler;\n\t}\n\n\tpublic constructor(private readonly manager: WebSocketManager, public readonly options: FetchingStrategyOptions) {}\n\n\tpublic async retrieveSessionInfo(shardId: number): Promise {\n\t\treturn this.manager.options.retrieveSessionInfo(shardId);\n\t}\n\n\tpublic updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null) {\n\t\treturn this.manager.options.updateSessionInfo(shardId, sessionInfo);\n\t}\n\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst throttler = await SimpleContextFetchingStrategy.ensureThrottler(this.manager);\n\t\tawait throttler.waitForIdentify(shardId, signal);\n\t}\n}\n","import { isMainThread, parentPort } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { SessionInfo } from '../../ws/WebSocketManager.js';\nimport {\n\tWorkerReceivePayloadOp,\n\tWorkerSendPayloadOp,\n\ttype WorkerReceivePayload,\n\ttype WorkerSendPayload,\n} from '../sharding/WorkerShardingStrategy.js';\nimport type { FetchingStrategyOptions, IContextFetchingStrategy } from './IContextFetchingStrategy.js';\n\n// Because the global types are incomplete for whatever reason\ninterface PolyFillAbortSignal {\n\treadonly aborted: boolean;\n\taddEventListener(type: 'abort', listener: () => void): void;\n\tremoveEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport class WorkerContextFetchingStrategy implements IContextFetchingStrategy {\n\tprivate readonly sessionPromises = new Collection void>();\n\n\tprivate readonly waitForIdentifyPromises = new Collection();\n\n\tpublic constructor(public readonly options: FetchingStrategyOptions) {\n\t\tif (isMainThread) {\n\t\t\tthrow new Error('Cannot instantiate WorkerContextFetchingStrategy on the main thread');\n\t\t}\n\n\t\tparentPort!.on('message', (payload: WorkerSendPayload) => {\n\t\t\tif (payload.op === WorkerSendPayloadOp.SessionInfoResponse) {\n\t\t\t\tthis.sessionPromises.get(payload.nonce)?.(payload.session);\n\t\t\t\tthis.sessionPromises.delete(payload.nonce);\n\t\t\t}\n\n\t\t\tif (payload.op === WorkerSendPayloadOp.ShardIdentifyResponse) {\n\t\t\t\tconst promise = this.waitForIdentifyPromises.get(payload.nonce);\n\t\t\t\tif (payload.ok) {\n\t\t\t\t\tpromise?.resolve();\n\t\t\t\t} else {\n\t\t\t\t\tpromise?.reject();\n\t\t\t\t}\n\n\t\t\t\tthis.waitForIdentifyPromises.delete(payload.nonce);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async retrieveSessionInfo(shardId: number): Promise {\n\t\tconst nonce = Math.random();\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.RetrieveSessionInfo,\n\t\t\tshardId,\n\t\t\tnonce,\n\t\t};\n\t\t// eslint-disable-next-line no-promise-executor-return\n\t\tconst promise = new Promise((resolve) => this.sessionPromises.set(nonce, resolve));\n\t\tparentPort!.postMessage(payload);\n\t\treturn promise;\n\t}\n\n\tpublic updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null) {\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.UpdateSessionInfo,\n\t\t\tshardId,\n\t\t\tsession: sessionInfo,\n\t\t};\n\t\tparentPort!.postMessage(payload);\n\t}\n\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst nonce = Math.random();\n\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.WaitForIdentify,\n\t\t\tnonce,\n\t\t\tshardId,\n\t\t};\n\t\tconst promise = new Promise((resolve, reject) =>\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tthis.waitForIdentifyPromises.set(nonce, { resolve, reject }),\n\t\t);\n\n\t\tparentPort!.postMessage(payload);\n\n\t\tconst listener = () => {\n\t\t\tconst payload: WorkerReceivePayload = {\n\t\t\t\top: WorkerReceivePayloadOp.CancelIdentify,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\tparentPort!.postMessage(payload);\n\t\t};\n\n\t\t(signal as unknown as PolyFillAbortSignal).addEventListener('abort', listener);\n\n\t\ttry {\n\t\t\tawait promise;\n\t\t} finally {\n\t\t\t(signal as unknown as PolyFillAbortSignal).removeEventListener('abort', listener);\n\t\t}\n\t}\n}\n","import { once } from 'node:events';\nimport { join, isAbsolute, resolve } from 'node:path';\nimport { Worker } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { GatewaySendPayload } from 'discord-api-types/v10';\nimport type { IIdentifyThrottler } from '../../throttling/IIdentifyThrottler.js';\nimport type { SessionInfo, WebSocketManager } from '../../ws/WebSocketManager.js';\nimport type {\n\tWebSocketShardDestroyOptions,\n\tWebSocketShardEvents,\n\tWebSocketShardStatus,\n} from '../../ws/WebSocketShard.js';\nimport { managerToFetchingStrategyOptions, type FetchingStrategyOptions } from '../context/IContextFetchingStrategy.js';\nimport type { IShardingStrategy } from './IShardingStrategy.js';\n\nexport interface WorkerData extends FetchingStrategyOptions {\n\tshardIds: number[];\n}\n\nexport enum WorkerSendPayloadOp {\n\tConnect,\n\tDestroy,\n\tSend,\n\tSessionInfoResponse,\n\tShardIdentifyResponse,\n\tFetchStatus,\n}\n\nexport type WorkerSendPayload =\n\t| { nonce: number; ok: boolean; op: WorkerSendPayloadOp.ShardIdentifyResponse }\n\t| { nonce: number; op: WorkerSendPayloadOp.FetchStatus; shardId: number }\n\t| { nonce: number; op: WorkerSendPayloadOp.SessionInfoResponse; session: SessionInfo | null }\n\t| { op: WorkerSendPayloadOp.Connect; shardId: number }\n\t| { op: WorkerSendPayloadOp.Destroy; options?: WebSocketShardDestroyOptions; shardId: number }\n\t| { op: WorkerSendPayloadOp.Send; payload: GatewaySendPayload; shardId: number };\n\nexport enum WorkerReceivePayloadOp {\n\tConnected,\n\tDestroyed,\n\tEvent,\n\tRetrieveSessionInfo,\n\tUpdateSessionInfo,\n\tWaitForIdentify,\n\tFetchStatusResponse,\n\tWorkerReady,\n\tCancelIdentify,\n}\n\nexport type WorkerReceivePayload =\n\t// Can't seem to get a type-safe union based off of the event, so I'm sadly leaving data as any for now\n\t| { data: any; event: WebSocketShardEvents; op: WorkerReceivePayloadOp.Event; shardId: number }\n\t| { nonce: number; op: WorkerReceivePayloadOp.CancelIdentify }\n\t| { nonce: number; op: WorkerReceivePayloadOp.FetchStatusResponse; status: WebSocketShardStatus }\n\t| { nonce: number; op: WorkerReceivePayloadOp.RetrieveSessionInfo; shardId: number }\n\t| { nonce: number; op: WorkerReceivePayloadOp.WaitForIdentify; shardId: number }\n\t| { op: WorkerReceivePayloadOp.Connected; shardId: number }\n\t| { op: WorkerReceivePayloadOp.Destroyed; shardId: number }\n\t| { op: WorkerReceivePayloadOp.UpdateSessionInfo; session: SessionInfo | null; shardId: number }\n\t| { op: WorkerReceivePayloadOp.WorkerReady };\n\n/**\n * Options for a {@link WorkerShardingStrategy}\n */\nexport interface WorkerShardingStrategyOptions {\n\t/**\n\t * Dictates how many shards should be spawned per worker thread.\n\t */\n\tshardsPerWorker: number | 'all';\n\t/**\n\t * Path to the worker file to use. The worker requires quite a bit of setup, it is recommended you leverage the {@link WorkerBootstrapper} class.\n\t */\n\tworkerPath?: string;\n}\n\n/**\n * Strategy used to spawn threads in worker_threads\n */\nexport class WorkerShardingStrategy implements IShardingStrategy {\n\tprivate readonly manager: WebSocketManager;\n\n\tprivate readonly options: WorkerShardingStrategyOptions;\n\n\t#workers: Worker[] = [];\n\n\treadonly #workerByShardId = new Collection();\n\n\tprivate readonly connectPromises = new Collection void>();\n\n\tprivate readonly destroyPromises = new Collection void>();\n\n\tprivate readonly fetchStatusPromises = new Collection void>();\n\n\tprivate readonly waitForIdentifyControllers = new Collection();\n\n\tprivate throttler?: IIdentifyThrottler;\n\n\tpublic constructor(manager: WebSocketManager, options: WorkerShardingStrategyOptions) {\n\t\tthis.manager = manager;\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.spawn}\n\t */\n\tpublic async spawn(shardIds: number[]) {\n\t\tconst shardsPerWorker = this.options.shardsPerWorker === 'all' ? shardIds.length : this.options.shardsPerWorker;\n\t\tconst strategyOptions = await managerToFetchingStrategyOptions(this.manager);\n\n\t\tconst loops = Math.ceil(shardIds.length / shardsPerWorker);\n\t\tconst promises: Promise[] = [];\n\n\t\tfor (let idx = 0; idx < loops; idx++) {\n\t\t\tconst slice = shardIds.slice(idx * shardsPerWorker, (idx + 1) * shardsPerWorker);\n\t\t\tconst workerData: WorkerData = {\n\t\t\t\t...strategyOptions,\n\t\t\t\tshardIds: slice,\n\t\t\t};\n\n\t\t\tpromises.push(this.setupWorker(workerData));\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.connect}\n\t */\n\tpublic async connect() {\n\t\tconst promises = [];\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.Connect,\n\t\t\t\tshardId,\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tconst promise = new Promise((resolve) => this.connectPromises.set(shardId, resolve));\n\t\t\tworker.postMessage(payload);\n\t\t\tpromises.push(promise);\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.destroy}\n\t */\n\tpublic async destroy(options: Omit = {}) {\n\t\tconst promises = [];\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.Destroy,\n\t\t\t\tshardId,\n\t\t\t\toptions,\n\t\t\t};\n\n\t\t\tpromises.push(\n\t\t\t\t// eslint-disable-next-line no-promise-executor-return, promise/prefer-await-to-then\n\t\t\t\tnew Promise((resolve) => this.destroyPromises.set(shardId, resolve)).then(async () => worker.terminate()),\n\t\t\t);\n\t\t\tworker.postMessage(payload);\n\t\t}\n\n\t\tthis.#workers = [];\n\t\tthis.#workerByShardId.clear();\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.send}\n\t */\n\tpublic send(shardId: number, data: GatewaySendPayload) {\n\t\tconst worker = this.#workerByShardId.get(shardId);\n\t\tif (!worker) {\n\t\t\tthrow new Error(`No worker found for shard ${shardId}`);\n\t\t}\n\n\t\tconst payload: WorkerSendPayload = {\n\t\t\top: WorkerSendPayloadOp.Send,\n\t\t\tshardId,\n\t\t\tpayload: data,\n\t\t};\n\t\tworker.postMessage(payload);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.fetchStatus}\n\t */\n\tpublic async fetchStatus() {\n\t\tconst statuses = new Collection();\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst nonce = Math.random();\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.FetchStatus,\n\t\t\t\tshardId,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tconst promise = new Promise((resolve) => this.fetchStatusPromises.set(nonce, resolve));\n\t\t\tworker.postMessage(payload);\n\n\t\t\tconst status = await promise;\n\t\t\tstatuses.set(shardId, status);\n\t\t}\n\n\t\treturn statuses;\n\t}\n\n\tprivate async setupWorker(workerData: WorkerData) {\n\t\tconst worker = new Worker(this.resolveWorkerPath(), { workerData });\n\n\t\tawait once(worker, 'online');\n\t\t// We do this in case the user has any potentially long running code in their worker\n\t\tawait this.waitForWorkerReady(worker);\n\n\t\tworker\n\t\t\t.on('error', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('messageerror', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('message', async (payload: WorkerReceivePayload) => this.onMessage(worker, payload));\n\n\t\tthis.#workers.push(worker);\n\t\tfor (const shardId of workerData.shardIds) {\n\t\t\tthis.#workerByShardId.set(shardId, worker);\n\t\t}\n\t}\n\n\tprivate resolveWorkerPath(): string {\n\t\tconst path = this.options.workerPath;\n\n\t\tif (!path) {\n\t\t\treturn join(__dirname, 'defaultWorker.js');\n\t\t}\n\n\t\tif (isAbsolute(path)) {\n\t\t\treturn path;\n\t\t}\n\n\t\tif (/^\\.\\.?[/\\\\]/.test(path)) {\n\t\t\treturn resolve(path);\n\t\t}\n\n\t\ttry {\n\t\t\treturn require.resolve(path);\n\t\t} catch {\n\t\t\treturn resolve(path);\n\t\t}\n\t}\n\n\tprivate async waitForWorkerReady(worker: Worker): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst handler = (payload: WorkerReceivePayload) => {\n\t\t\t\tif (payload.op === WorkerReceivePayloadOp.WorkerReady) {\n\t\t\t\t\tresolve();\n\t\t\t\t\tworker.off('message', handler);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tworker.on('message', handler);\n\t\t});\n\t}\n\n\tprivate async onMessage(worker: Worker, payload: WorkerReceivePayload) {\n\t\tswitch (payload.op) {\n\t\t\tcase WorkerReceivePayloadOp.Connected: {\n\t\t\t\tthis.connectPromises.get(payload.shardId)?.();\n\t\t\t\tthis.connectPromises.delete(payload.shardId);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.Destroyed: {\n\t\t\t\tthis.destroyPromises.get(payload.shardId)?.();\n\t\t\t\tthis.destroyPromises.delete(payload.shardId);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.Event: {\n\t\t\t\tthis.manager.emit(payload.event, { ...payload.data, shardId: payload.shardId });\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.RetrieveSessionInfo: {\n\t\t\t\tconst session = await this.manager.options.retrieveSessionInfo(payload.shardId);\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.SessionInfoResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tsession,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.UpdateSessionInfo: {\n\t\t\t\tawait this.manager.options.updateSessionInfo(payload.shardId, payload.session);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.WaitForIdentify: {\n\t\t\t\tconst throttler = await this.ensureThrottler();\n\n\t\t\t\t// If this rejects it means we aborted, in which case we reply elsewhere.\n\t\t\t\ttry {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\tthis.waitForIdentifyControllers.set(payload.nonce, controller);\n\t\t\t\t\tawait throttler.waitForIdentify(payload.shardId, controller.signal);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.ShardIdentifyResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tok: true,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.FetchStatusResponse: {\n\t\t\t\tthis.fetchStatusPromises.get(payload.nonce)?.(payload.status);\n\t\t\t\tthis.fetchStatusPromises.delete(payload.nonce);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.WorkerReady: {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.CancelIdentify: {\n\t\t\t\tthis.waitForIdentifyControllers.get(payload.nonce)?.abort();\n\t\t\t\tthis.waitForIdentifyControllers.delete(payload.nonce);\n\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.ShardIdentifyResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tok: false,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async ensureThrottler(): Promise {\n\t\tthis.throttler ??= await this.manager.options.buildIdentifyThrottler(this.manager);\n\t\treturn this.throttler;\n\t}\n}\n","import { Collection } from '@discordjs/collection';\nimport type { GatewaySendPayload } from 'discord-api-types/v10';\nimport type { WebSocketManager } from '../../ws/WebSocketManager.js';\nimport { WebSocketShard, WebSocketShardEvents, type WebSocketShardDestroyOptions } from '../../ws/WebSocketShard.js';\nimport { managerToFetchingStrategyOptions } from '../context/IContextFetchingStrategy.js';\nimport { SimpleContextFetchingStrategy } from '../context/SimpleContextFetchingStrategy.js';\nimport type { IShardingStrategy } from './IShardingStrategy.js';\n\n/**\n * Simple strategy that just spawns shards in the current process\n */\nexport class SimpleShardingStrategy implements IShardingStrategy {\n\tprivate readonly manager: WebSocketManager;\n\n\tprivate readonly shards = new Collection();\n\n\tpublic constructor(manager: WebSocketManager) {\n\t\tthis.manager = manager;\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.spawn}\n\t */\n\tpublic async spawn(shardIds: number[]) {\n\t\tconst strategyOptions = await managerToFetchingStrategyOptions(this.manager);\n\n\t\tfor (const shardId of shardIds) {\n\t\t\tconst strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions);\n\t\t\tconst shard = new WebSocketShard(strategy, shardId);\n\t\t\tfor (const event of Object.values(WebSocketShardEvents)) {\n\t\t\t\t// @ts-expect-error: Intentional\n\t\t\t\tshard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId }));\n\t\t\t}\n\n\t\t\tthis.shards.set(shardId, shard);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.connect}\n\t */\n\tpublic async connect() {\n\t\tconst promises = [];\n\n\t\tfor (const shard of this.shards.values()) {\n\t\t\tpromises.push(shard.connect());\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.destroy}\n\t */\n\tpublic async destroy(options?: Omit) {\n\t\tconst promises = [];\n\n\t\tfor (const shard of this.shards.values()) {\n\t\t\tpromises.push(shard.destroy(options));\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t\tthis.shards.clear();\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.send}\n\t */\n\tpublic async send(shardId: number, payload: GatewaySendPayload) {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} not found`);\n\t\t}\n\n\t\treturn shard.send(payload);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.fetchStatus}\n\t */\n\tpublic async fetchStatus() {\n\t\treturn this.shards.mapValues((shard) => shard.status);\n\t}\n}\n","/* eslint-disable id-length */\nimport { Buffer } from 'node:buffer';\nimport { once } from 'node:events';\nimport { clearInterval, clearTimeout, setInterval, setTimeout } from 'node:timers';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { URLSearchParams } from 'node:url';\nimport { TextDecoder } from 'node:util';\nimport { inflate } from 'node:zlib';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\nimport {\n\tGatewayCloseCodes,\n\tGatewayDispatchEvents,\n\tGatewayOpcodes,\n\ttype GatewayDispatchPayload,\n\ttype GatewayIdentifyData,\n\ttype GatewayReadyDispatchData,\n\ttype GatewayReceivePayload,\n\ttype GatewaySendPayload,\n} from 'discord-api-types/v10';\nimport { WebSocket, type RawData } from 'ws';\nimport type { Inflate } from 'zlib-sync';\nimport type { IContextFetchingStrategy } from '../strategies/context/IContextFetchingStrategy.js';\nimport { ImportantGatewayOpcodes, getInitialSendRateLimitState } from '../utils/constants.js';\nimport type { SessionInfo } from './WebSocketManager.js';\n\n// eslint-disable-next-line promise/prefer-await-to-then\nconst getZlibSync = lazy(async () => import('zlib-sync').then((mod) => mod.default).catch(() => null));\n\nexport enum WebSocketShardEvents {\n\tClosed = 'closed',\n\tDebug = 'debug',\n\tDispatch = 'dispatch',\n\tError = 'error',\n\tHeartbeatComplete = 'heartbeat',\n\tHello = 'hello',\n\tReady = 'ready',\n\tResumed = 'resumed',\n}\n\nexport enum WebSocketShardStatus {\n\tIdle,\n\tConnecting,\n\tResuming,\n\tReady,\n}\n\nexport enum WebSocketShardDestroyRecovery {\n\tReconnect,\n\tResume,\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport type WebSocketShardEventsMap = {\n\t[WebSocketShardEvents.Closed]: [{ code: number }];\n\t[WebSocketShardEvents.Debug]: [payload: { message: string }];\n\t[WebSocketShardEvents.Dispatch]: [payload: { data: GatewayDispatchPayload }];\n\t[WebSocketShardEvents.Error]: [payload: { error: Error }];\n\t[WebSocketShardEvents.Hello]: [];\n\t[WebSocketShardEvents.Ready]: [payload: { data: GatewayReadyDispatchData }];\n\t[WebSocketShardEvents.Resumed]: [];\n\t[WebSocketShardEvents.HeartbeatComplete]: [payload: { ackAt: number; heartbeatAt: number; latency: number }];\n};\n\nexport interface WebSocketShardDestroyOptions {\n\tcode?: number;\n\treason?: string;\n\trecover?: WebSocketShardDestroyRecovery;\n}\n\nexport enum CloseCodes {\n\tNormal = 1_000,\n\tResuming = 4_200,\n}\n\nexport interface SendRateLimitState {\n\tremaining: number;\n\tresetAt: number;\n}\n\nexport class WebSocketShard extends AsyncEventEmitter {\n\tprivate connection: WebSocket | null = null;\n\n\tprivate useIdentifyCompress = false;\n\n\tprivate inflate: Inflate | null = null;\n\n\tprivate readonly textDecoder = new TextDecoder();\n\n\tprivate replayedEvents = 0;\n\n\tprivate isAck = true;\n\n\tprivate sendRateLimitState: SendRateLimitState = getInitialSendRateLimitState();\n\n\tprivate initialHeartbeatTimeoutController: AbortController | null = null;\n\n\tprivate heartbeatInterval: NodeJS.Timer | null = null;\n\n\tprivate lastHeartbeatAt = -1;\n\n\t// Indicates whether the shard has already resolved its original connect() call\n\tprivate initialConnectResolved = false;\n\n\t// Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET)\n\tprivate failedToConnectDueToNetworkError = false;\n\n\tprivate readonly sendQueue = new AsyncQueue();\n\n\tprivate readonly timeoutAbortControllers = new Collection();\n\n\tprivate readonly strategy: IContextFetchingStrategy;\n\n\tpublic readonly id: number;\n\n\t#status: WebSocketShardStatus = WebSocketShardStatus.Idle;\n\n\tpublic get status(): WebSocketShardStatus {\n\t\treturn this.#status;\n\t}\n\n\tpublic constructor(strategy: IContextFetchingStrategy, id: number) {\n\t\tsuper();\n\t\tthis.strategy = strategy;\n\t\tthis.id = id;\n\t}\n\n\tpublic async connect() {\n\t\tconst promise = this.initialConnectResolved ? Promise.resolve() : once(this, WebSocketShardEvents.Ready);\n\t\tvoid this.internalConnect();\n\n\t\tawait promise;\n\t\tthis.initialConnectResolved = true;\n\t}\n\n\tprivate async internalConnect() {\n\t\tif (this.#status !== WebSocketShardStatus.Idle) {\n\t\t\tthrow new Error(\"Tried to connect a shard that wasn't idle\");\n\t\t}\n\n\t\tconst { version, encoding, compression } = this.strategy.options;\n\t\tconst params = new URLSearchParams({ v: version, encoding });\n\t\tif (compression) {\n\t\t\tconst zlib = await getZlibSync();\n\t\t\tif (zlib) {\n\t\t\t\tparams.append('compress', compression);\n\t\t\t\tthis.inflate = new zlib.Inflate({\n\t\t\t\t\tchunkSize: 65_535,\n\t\t\t\t\tto: 'string',\n\t\t\t\t});\n\t\t\t} else if (!this.useIdentifyCompress) {\n\t\t\t\tthis.useIdentifyCompress = true;\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\n\t\tconst url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`;\n\t\tthis.debug([`Connecting to ${url}`]);\n\t\tconst connection = new WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? undefined })\n\t\t\t.on('message', this.onMessage.bind(this))\n\t\t\t.on('error', this.onError.bind(this))\n\t\t\t.on('close', this.onClose.bind(this));\n\n\t\tconnection.binaryType = 'arraybuffer';\n\t\tthis.connection = connection;\n\n\t\tthis.#status = WebSocketShardStatus.Connecting;\n\n\t\tthis.sendRateLimitState = getInitialSendRateLimitState();\n\n\t\tconst { ok } = await this.waitForEvent(WebSocketShardEvents.Hello, this.strategy.options.helloTimeout);\n\t\tif (!ok) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (session?.shardCount === this.strategy.options.shardCount) {\n\t\t\tawait this.resume(session);\n\t\t} else {\n\t\t\tawait this.identify();\n\t\t}\n\t}\n\n\tpublic async destroy(options: WebSocketShardDestroyOptions = {}) {\n\t\tif (this.#status === WebSocketShardStatus.Idle) {\n\t\t\tthis.debug(['Tried to destroy a shard that was idle']);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!options.code) {\n\t\t\toptions.code = options.recover === WebSocketShardDestroyRecovery.Resume ? CloseCodes.Resuming : CloseCodes.Normal;\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Destroying shard',\n\t\t\t`Reason: ${options.reason ?? 'none'}`,\n\t\t\t`Code: ${options.code}`,\n\t\t\t`Recover: ${options.recover === undefined ? 'none' : WebSocketShardDestroyRecovery[options.recover]!}`,\n\t\t]);\n\n\t\t// Reset state\n\t\tthis.isAck = true;\n\t\tif (this.heartbeatInterval) {\n\t\t\tclearInterval(this.heartbeatInterval);\n\t\t}\n\n\t\tif (this.initialHeartbeatTimeoutController) {\n\t\t\tthis.initialHeartbeatTimeoutController.abort();\n\t\t\tthis.initialHeartbeatTimeoutController = null;\n\t\t}\n\n\t\tthis.lastHeartbeatAt = -1;\n\n\t\tfor (const controller of this.timeoutAbortControllers.values()) {\n\t\t\tcontroller.abort();\n\t\t}\n\n\t\tthis.timeoutAbortControllers.clear();\n\n\t\tthis.failedToConnectDueToNetworkError = false;\n\n\t\t// Clear session state if applicable\n\t\tif (options.recover !== WebSocketShardDestroyRecovery.Resume) {\n\t\t\tawait this.strategy.updateSessionInfo(this.id, null);\n\t\t}\n\n\t\tif (this.connection) {\n\t\t\t// No longer need to listen to messages\n\t\t\tthis.connection.removeAllListeners('message');\n\t\t\t// Prevent a reconnection loop by unbinding the main close event\n\t\t\tthis.connection.removeAllListeners('close');\n\n\t\t\tconst shouldClose = this.connection.readyState === WebSocket.OPEN;\n\n\t\t\tthis.debug([\n\t\t\t\t'Connection status during destroy',\n\t\t\t\t`Needs closing: ${shouldClose}`,\n\t\t\t\t`Ready state: ${this.connection.readyState}`,\n\t\t\t]);\n\n\t\t\tif (shouldClose) {\n\t\t\t\tthis.connection.close(options.code, options.reason);\n\t\t\t\tawait once(this.connection, 'close');\n\t\t\t\tthis.emit(WebSocketShardEvents.Closed, { code: options.code });\n\t\t\t}\n\n\t\t\t// Lastly, remove the error event.\n\t\t\t// Doing this earlier would cause a hard crash in case an error event fired on our `close` call\n\t\t\tthis.connection.removeAllListeners('error');\n\t\t} else {\n\t\t\tthis.debug(['Destroying a shard that has no connection; please open an issue on GitHub']);\n\t\t}\n\n\t\tthis.#status = WebSocketShardStatus.Idle;\n\n\t\tif (options.recover !== undefined) {\n\t\t\t// There's cases (like no internet connection) where we immediately fail to connect,\n\t\t\t// causing a very fast and draining reconnection loop.\n\t\t\tawait sleep(500);\n\t\t\treturn this.internalConnect();\n\t\t}\n\t}\n\n\tprivate async waitForEvent(event: WebSocketShardEvents, timeoutDuration?: number | null): Promise<{ ok: boolean }> {\n\t\tthis.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : 'indefinitely'}`]);\n\t\tconst timeoutController = new AbortController();\n\t\tconst timeout = timeoutDuration ? setTimeout(() => timeoutController.abort(), timeoutDuration).unref() : null;\n\n\t\tthis.timeoutAbortControllers.set(event, timeoutController);\n\n\t\tconst closeController = new AbortController();\n\n\t\ttry {\n\t\t\t// If the first promise resolves, all is well. If the 2nd promise resolves,\n\t\t\t// the shard has meanwhile closed. In that case, a destroy is already ongoing, so we just need to\n\t\t\t// return false. Meanwhile, if something rejects (error event) or the first controller is aborted,\n\t\t\t// we enter the catch block and trigger a destroy there.\n\t\t\tconst closed = await Promise.race([\n\t\t\t\tonce(this, event, { signal: timeoutController.signal }).then(() => false),\n\t\t\t\tonce(this, WebSocketShardEvents.Closed, { signal: closeController.signal }).then(() => true),\n\t\t\t]);\n\n\t\t\treturn { ok: !closed };\n\t\t} catch {\n\t\t\t// If we're here because of other reasons, we need to destroy the shard\n\t\t\tvoid this.destroy({\n\t\t\t\tcode: CloseCodes.Normal,\n\t\t\t\treason: 'Something timed out or went wrong while waiting for an event',\n\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t});\n\n\t\t\treturn { ok: false };\n\t\t} finally {\n\t\t\tif (timeout) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t}\n\n\t\t\tthis.timeoutAbortControllers.delete(event);\n\n\t\t\t// Clean up the close listener to not leak memory\n\t\t\tif (!closeController.signal.aborted) {\n\t\t\t\tcloseController.abort();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async send(payload: GatewaySendPayload): Promise {\n\t\tif (!this.connection) {\n\t\t\tthrow new Error(\"WebSocketShard wasn't connected\");\n\t\t}\n\n\t\tif (this.#status !== WebSocketShardStatus.Ready && !ImportantGatewayOpcodes.has(payload.op)) {\n\t\t\tthis.debug(['Tried to send a non-crucial payload before the shard was ready, waiting']);\n\t\t\t// This will throw if the shard throws an error event in the meantime, just requeue the payload\n\t\t\ttry {\n\t\t\t\tawait once(this, WebSocketShardEvents.Ready);\n\t\t\t} catch {\n\t\t\t\treturn this.send(payload);\n\t\t\t}\n\t\t}\n\n\t\tawait this.sendQueue.wait();\n\n\t\tif (--this.sendRateLimitState.remaining <= 0) {\n\t\t\tconst now = Date.now();\n\n\t\t\tif (this.sendRateLimitState.resetAt > now) {\n\t\t\t\tconst sleepFor = this.sendRateLimitState.resetAt - now;\n\n\t\t\t\tthis.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]);\n\t\t\t\tconst controller = new AbortController();\n\n\t\t\t\t// Sleep for the remaining time, but if the connection closes in the meantime, we shouldn't wait the remainder to avoid blocking the new conn\n\t\t\t\tconst interrupted = await Promise.race([\n\t\t\t\t\tsleep(sleepFor).then(() => false),\n\t\t\t\t\tonce(this, WebSocketShardEvents.Closed, { signal: controller.signal }).then(() => true),\n\t\t\t\t]);\n\n\t\t\t\tif (interrupted) {\n\t\t\t\t\tthis.debug(['Connection closed while waiting for the send rate limit to reset, re-queueing payload']);\n\t\t\t\t\tthis.sendQueue.shift();\n\t\t\t\t\treturn this.send(payload);\n\t\t\t\t}\n\n\t\t\t\t// This is so the listener from the `once` call is removed\n\t\t\t\tcontroller.abort();\n\t\t\t}\n\n\t\t\tthis.sendRateLimitState = getInitialSendRateLimitState();\n\t\t}\n\n\t\tthis.sendQueue.shift();\n\t\tthis.connection.send(JSON.stringify(payload));\n\t}\n\n\tprivate async identify() {\n\t\tthis.debug(['Waiting for identify throttle']);\n\n\t\tconst controller = new AbortController();\n\t\tconst closeHandler = () => {\n\t\t\tcontroller.abort();\n\t\t};\n\n\t\tthis.on(WebSocketShardEvents.Closed, closeHandler);\n\n\t\ttry {\n\t\t\tawait this.strategy.waitForIdentify(this.id, controller.signal);\n\t\t} catch {\n\t\t\tthis.debug(['Was waiting for an identify, but the shard closed in the meantime']);\n\t\t\treturn;\n\t\t} finally {\n\t\t\tthis.off(WebSocketShardEvents.Closed, closeHandler);\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Identifying',\n\t\t\t`shard id: ${this.id.toString()}`,\n\t\t\t`shard count: ${this.strategy.options.shardCount}`,\n\t\t\t`intents: ${this.strategy.options.intents}`,\n\t\t\t`compression: ${this.inflate ? 'zlib-stream' : this.useIdentifyCompress ? 'identify' : 'none'}`,\n\t\t]);\n\n\t\tconst d: GatewayIdentifyData = {\n\t\t\ttoken: this.strategy.options.token,\n\t\t\tproperties: this.strategy.options.identifyProperties,\n\t\t\tintents: this.strategy.options.intents,\n\t\t\tcompress: this.useIdentifyCompress,\n\t\t\tshard: [this.id, this.strategy.options.shardCount],\n\t\t};\n\n\t\tif (this.strategy.options.largeThreshold) {\n\t\t\td.large_threshold = this.strategy.options.largeThreshold;\n\t\t}\n\n\t\tif (this.strategy.options.initialPresence) {\n\t\t\td.presence = this.strategy.options.initialPresence;\n\t\t}\n\n\t\tawait this.send({\n\t\t\top: GatewayOpcodes.Identify,\n\t\t\td,\n\t\t});\n\n\t\tawait this.waitForEvent(WebSocketShardEvents.Ready, this.strategy.options.readyTimeout);\n\t}\n\n\tprivate async resume(session: SessionInfo) {\n\t\tthis.debug([\n\t\t\t'Resuming session',\n\t\t\t`resume url: ${session.resumeURL}`,\n\t\t\t`sequence: ${session.sequence}`,\n\t\t\t`shard id: ${this.id.toString()}`,\n\t\t]);\n\n\t\tthis.#status = WebSocketShardStatus.Resuming;\n\t\tthis.replayedEvents = 0;\n\t\treturn this.send({\n\t\t\top: GatewayOpcodes.Resume,\n\t\t\td: {\n\t\t\t\ttoken: this.strategy.options.token,\n\t\t\t\tseq: session.sequence,\n\t\t\t\tsession_id: session.sessionId,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async heartbeat(requested = false) {\n\t\tif (!this.isAck && !requested) {\n\t\t\treturn this.destroy({ reason: 'Zombie connection', recover: WebSocketShardDestroyRecovery.Resume });\n\t\t}\n\n\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\n\t\tawait this.send({\n\t\t\top: GatewayOpcodes.Heartbeat,\n\t\t\td: session?.sequence ?? null,\n\t\t});\n\n\t\tthis.lastHeartbeatAt = Date.now();\n\t\tthis.isAck = false;\n\t}\n\n\tprivate async unpackMessage(data: ArrayBuffer | Buffer, isBinary: boolean): Promise {\n\t\tconst decompressable = new Uint8Array(data);\n\n\t\t// Deal with no compression\n\t\tif (!isBinary) {\n\t\t\treturn JSON.parse(this.textDecoder.decode(decompressable)) as GatewayReceivePayload;\n\t\t}\n\n\t\t// Deal with identify compress\n\t\tif (this.useIdentifyCompress) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tinflate(decompressable, { chunkSize: 65_535 }, (err, result) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(JSON.parse(this.textDecoder.decode(result)) as GatewayReceivePayload);\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\t// Deal with gw wide zlib-stream compression\n\t\tif (this.inflate) {\n\t\t\tconst l = decompressable.length;\n\t\t\tconst flush =\n\t\t\t\tl >= 4 &&\n\t\t\t\tdecompressable[l - 4] === 0x00 &&\n\t\t\t\tdecompressable[l - 3] === 0x00 &&\n\t\t\t\tdecompressable[l - 2] === 0xff &&\n\t\t\t\tdecompressable[l - 1] === 0xff;\n\n\t\t\tconst zlib = (await getZlibSync())!;\n\t\t\tthis.inflate.push(Buffer.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH);\n\n\t\t\tif (this.inflate.err) {\n\t\t\t\tthis.emit(WebSocketShardEvents.Error, {\n\t\t\t\t\terror: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ''}`),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!flush) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst { result } = this.inflate;\n\t\t\tif (!result) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn JSON.parse(typeof result === 'string' ? result : this.textDecoder.decode(result)) as GatewayReceivePayload;\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Received a message we were unable to decompress',\n\t\t\t`isBinary: ${isBinary.toString()}`,\n\t\t\t`useIdentifyCompress: ${this.useIdentifyCompress.toString()}`,\n\t\t\t`inflate: ${Boolean(this.inflate).toString()}`,\n\t\t]);\n\n\t\treturn null;\n\t}\n\n\tprivate async onMessage(data: RawData, isBinary: boolean) {\n\t\tconst payload = await this.unpackMessage(data as ArrayBuffer | Buffer, isBinary);\n\t\tif (!payload) {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (payload.op) {\n\t\t\tcase GatewayOpcodes.Dispatch: {\n\t\t\t\tif (this.#status === WebSocketShardStatus.Resuming) {\n\t\t\t\t\tthis.replayedEvents++;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line sonarjs/no-nested-switch\n\t\t\t\tswitch (payload.t) {\n\t\t\t\t\tcase GatewayDispatchEvents.Ready: {\n\t\t\t\t\t\tthis.#status = WebSocketShardStatus.Ready;\n\n\t\t\t\t\t\tconst session = {\n\t\t\t\t\t\t\tsequence: payload.s,\n\t\t\t\t\t\t\tsessionId: payload.d.session_id,\n\t\t\t\t\t\t\tshardId: this.id,\n\t\t\t\t\t\t\tshardCount: this.strategy.options.shardCount,\n\t\t\t\t\t\t\tresumeURL: payload.d.resume_gateway_url,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tawait this.strategy.updateSessionInfo(this.id, session);\n\n\t\t\t\t\t\tthis.emit(WebSocketShardEvents.Ready, { data: payload.d });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase GatewayDispatchEvents.Resumed: {\n\t\t\t\t\t\tthis.#status = WebSocketShardStatus.Ready;\n\t\t\t\t\t\tthis.debug([`Resumed and replayed ${this.replayedEvents} events`]);\n\t\t\t\t\t\tthis.emit(WebSocketShardEvents.Resumed);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\t\t\t\tif (session) {\n\t\t\t\t\tif (payload.s > session.sequence) {\n\t\t\t\t\t\tawait this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s });\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.debug([\n\t\t\t\t\t\t`Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect`,\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tthis.emit(WebSocketShardEvents.Dispatch, { data: payload });\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Heartbeat: {\n\t\t\t\tawait this.heartbeat(true);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Reconnect: {\n\t\t\t\tawait this.destroy({\n\t\t\t\t\treason: 'Told to reconnect by Discord',\n\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Resume,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.InvalidSession: {\n\t\t\t\tthis.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]);\n\t\t\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\t\t\t\tif (payload.d && session) {\n\t\t\t\t\tawait this.resume(session);\n\t\t\t\t} else {\n\t\t\t\t\tawait this.destroy({\n\t\t\t\t\t\treason: 'Invalid session',\n\t\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Hello: {\n\t\t\t\tthis.emit(WebSocketShardEvents.Hello);\n\t\t\t\tconst jitter = Math.random();\n\t\t\t\tconst firstWait = Math.floor(payload.d.heartbeat_interval * jitter);\n\t\t\t\tthis.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\tthis.initialHeartbeatTimeoutController = controller;\n\t\t\t\t\tawait sleep(firstWait, undefined, { signal: controller.signal });\n\t\t\t\t} catch {\n\t\t\t\t\tthis.debug(['Cancelled initial heartbeat due to #destroy being called']);\n\t\t\t\t\treturn;\n\t\t\t\t} finally {\n\t\t\t\t\tthis.initialHeartbeatTimeoutController = null;\n\t\t\t\t}\n\n\t\t\t\tawait this.heartbeat();\n\n\t\t\t\tthis.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]);\n\t\t\t\tthis.heartbeatInterval = setInterval(() => void this.heartbeat(), payload.d.heartbeat_interval);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.HeartbeatAck: {\n\t\t\t\tthis.isAck = true;\n\n\t\t\t\tconst ackAt = Date.now();\n\t\t\t\tthis.emit(WebSocketShardEvents.HeartbeatComplete, {\n\t\t\t\t\tackAt,\n\t\t\t\t\theartbeatAt: this.lastHeartbeatAt,\n\t\t\t\t\tlatency: ackAt - this.lastHeartbeatAt,\n\t\t\t\t});\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate onError(error: Error) {\n\t\tif ('code' in error && ['ECONNRESET', 'ECONNREFUSED'].includes(error.code as string)) {\n\t\t\tthis.debug(['Failed to connect to the gateway URL specified due to a network error']);\n\t\t\tthis.failedToConnectDueToNetworkError = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.emit(WebSocketShardEvents.Error, { error });\n\t}\n\n\tprivate async onClose(code: number) {\n\t\tthis.emit(WebSocketShardEvents.Closed, { code });\n\n\t\tswitch (code) {\n\t\t\tcase CloseCodes.Normal: {\n\t\t\t\treturn this.destroy({\n\t\t\t\t\tcode,\n\t\t\t\t\treason: 'Got disconnected by Discord',\n\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase CloseCodes.Resuming: {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.UnknownError: {\n\t\t\t\tthis.debug([`An unknown error occurred: ${code}`]);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.UnknownOpcode: {\n\t\t\t\tthis.debug(['An invalid opcode was sent to Discord.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.DecodeError: {\n\t\t\t\tthis.debug(['An invalid payload was sent to Discord.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.NotAuthenticated: {\n\t\t\t\tthis.debug(['A request was somehow sent before the identify/resume payload.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.AuthenticationFailed: {\n\t\t\t\tthrow new Error('Authentication failed');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.AlreadyAuthenticated: {\n\t\t\t\tthis.debug(['More than one auth payload was sent.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidSeq: {\n\t\t\t\tthis.debug(['An invalid sequence was sent.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.RateLimited: {\n\t\t\t\tthis.debug(['The WebSocket rate limit has been hit, this should never happen']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.SessionTimedOut: {\n\t\t\t\tthis.debug(['Session timed out.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidShard: {\n\t\t\t\tthrow new Error('Invalid shard');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.ShardingRequired: {\n\t\t\t\tthrow new Error('Sharding is required');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidAPIVersion: {\n\t\t\t\tthrow new Error('Used an invalid API version');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidIntents: {\n\t\t\t\tthrow new Error('Used invalid intents');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.DisallowedIntents: {\n\t\t\t\tthrow new Error('Used disallowed intents');\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tthis.debug([\n\t\t\t\t\t`The gateway closed with an unexpected code ${code}, attempting to ${\n\t\t\t\t\t\tthis.failedToConnectDueToNetworkError ? 'reconnect' : 'resume'\n\t\t\t\t\t}.`,\n\t\t\t\t]);\n\t\t\t\treturn this.destroy({\n\t\t\t\t\tcode,\n\t\t\t\t\trecover: this.failedToConnectDueToNetworkError\n\t\t\t\t\t\t? WebSocketShardDestroyRecovery.Reconnect\n\t\t\t\t\t\t: WebSocketShardDestroyRecovery.Resume,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate debug(messages: [string, ...string[]]) {\n\t\tconst message = `${messages[0]}${\n\t\t\tmessages.length > 1\n\t\t\t\t? `\\n${messages\n\t\t\t\t\t\t.slice(1)\n\t\t\t\t\t\t.map((m) => `\t${m}`)\n\t\t\t\t\t\t.join('\\n')}`\n\t\t\t\t: ''\n\t\t}`;\n\n\t\tthis.emit(WebSocketShardEvents.Debug, { message });\n\t}\n}\n","import process from 'node:process';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { APIVersion, GatewayOpcodes } from 'discord-api-types/v10';\nimport { SimpleShardingStrategy } from '../strategies/sharding/SimpleShardingStrategy.js';\nimport { SimpleIdentifyThrottler } from '../throttling/SimpleIdentifyThrottler.js';\nimport type { SessionInfo, OptionalWebSocketManagerOptions, WebSocketManager } from '../ws/WebSocketManager.js';\nimport type { SendRateLimitState } from '../ws/WebSocketShard.js';\n\n/**\n * Valid encoding types\n */\nexport enum Encoding {\n\tJSON = 'json',\n}\n\n/**\n * Valid compression methods\n */\nexport enum CompressionMethod {\n\tZlibStream = 'zlib-stream',\n}\n\nexport const DefaultDeviceProperty = `@discordjs/ws 0.8.3` as `@discordjs/ws ${string}`;\n\nconst getDefaultSessionStore = lazy(() => new Collection());\n\n/**\n * Default options used by the manager\n */\nexport const DefaultWebSocketManagerOptions = {\n\tasync buildIdentifyThrottler(manager: WebSocketManager) {\n\t\tconst info = await manager.fetchGatewayInformation();\n\t\treturn new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency);\n\t},\n\tbuildStrategy: (manager) => new SimpleShardingStrategy(manager),\n\tshardCount: null,\n\tshardIds: null,\n\tlargeThreshold: null,\n\tinitialPresence: null,\n\tidentifyProperties: {\n\t\tbrowser: DefaultDeviceProperty,\n\t\tdevice: DefaultDeviceProperty,\n\t\tos: process.platform,\n\t},\n\tversion: APIVersion,\n\tencoding: Encoding.JSON,\n\tcompression: null,\n\tretrieveSessionInfo(shardId) {\n\t\tconst store = getDefaultSessionStore();\n\t\treturn store.get(shardId) ?? null;\n\t},\n\tupdateSessionInfo(shardId: number, info: SessionInfo | null) {\n\t\tconst store = getDefaultSessionStore();\n\t\tif (info) {\n\t\t\tstore.set(shardId, info);\n\t\t} else {\n\t\t\tstore.delete(shardId);\n\t\t}\n\t},\n\thandshakeTimeout: 30_000,\n\thelloTimeout: 60_000,\n\treadyTimeout: 15_000,\n} as const satisfies OptionalWebSocketManagerOptions;\n\nexport const ImportantGatewayOpcodes = new Set([\n\tGatewayOpcodes.Heartbeat,\n\tGatewayOpcodes.Identify,\n\tGatewayOpcodes.Resume,\n]);\n\nexport function getInitialSendRateLimitState(): SendRateLimitState {\n\treturn {\n\t\tremaining: 120,\n\t\tresetAt: Date.now() + 60_000,\n\t};\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport { Collection } from '@discordjs/collection';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport type { IIdentifyThrottler } from './IIdentifyThrottler.js';\n\n/**\n * The state of a rate limit key's identify queue.\n */\nexport interface IdentifyState {\n\tqueue: AsyncQueue;\n\tresetsAt: number;\n}\n\n/**\n * Local, in-memory identify throttler.\n */\nexport class SimpleIdentifyThrottler implements IIdentifyThrottler {\n\tprivate readonly states = new Collection();\n\n\tpublic constructor(private readonly maxConcurrency: number) {}\n\n\t/**\n\t * {@inheritDoc IIdentifyThrottler.waitForIdentify}\n\t */\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst key = shardId % this.maxConcurrency;\n\n\t\tconst state = this.states.ensure(key, () => {\n\t\t\treturn {\n\t\t\t\tqueue: new AsyncQueue(),\n\t\t\t\tresetsAt: Number.POSITIVE_INFINITY,\n\t\t\t};\n\t\t});\n\n\t\tawait state.queue.wait({ signal });\n\n\t\ttry {\n\t\t\tconst diff = state.resetsAt - Date.now();\n\t\t\tif (diff <= 5_000) {\n\t\t\t\t// To account for the latency the IDENTIFY payload goes through, we add a bit more wait time\n\t\t\t\tconst time = diff + Math.random() * 1_500;\n\t\t\t\tawait sleep(time);\n\t\t\t}\n\n\t\t\tstate.resetsAt = Date.now() + 5_000;\n\t\t} finally {\n\t\t\tstate.queue.shift();\n\t\t}\n\t}\n}\n","import { isMainThread, parentPort, workerData } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { Awaitable } from '@discordjs/util';\nimport { WorkerContextFetchingStrategy } from '../strategies/context/WorkerContextFetchingStrategy.js';\nimport {\n\tWorkerReceivePayloadOp,\n\tWorkerSendPayloadOp,\n\ttype WorkerData,\n\ttype WorkerReceivePayload,\n\ttype WorkerSendPayload,\n} from '../strategies/sharding/WorkerShardingStrategy.js';\nimport type { WebSocketShardDestroyOptions } from '../ws/WebSocketShard.js';\nimport { WebSocketShardEvents, WebSocketShard } from '../ws/WebSocketShard.js';\n\n/**\n * Options for bootstrapping the worker\n */\nexport interface BootstrapOptions {\n\t/**\n\t * Shard events to just arbitrarily forward to the parent thread for the manager to emit\n\t * Note: By default, this will include ALL events\n\t * you most likely want to handle dispatch within the worker itself\n\t */\n\tforwardEvents?: WebSocketShardEvents[];\n\t/**\n\t * Function to call when a shard is created for additional setup\n\t */\n\tshardCallback?(shard: WebSocketShard): Awaitable;\n}\n\n/**\n * Utility class for bootstrapping a worker thread to be used for sharding\n */\nexport class WorkerBootstrapper {\n\t/**\n\t * The data passed to the worker thread\n\t */\n\tprotected readonly data = workerData as WorkerData;\n\n\t/**\n\t * The shards that are managed by this worker\n\t */\n\tprotected readonly shards = new Collection();\n\n\tpublic constructor() {\n\t\tif (isMainThread) {\n\t\t\tthrow new Error('Expected WorkerBootstrap to not be used within the main thread');\n\t\t}\n\t}\n\n\t/**\n\t * Helper method to initiate a shard's connection process\n\t */\n\tprotected async connect(shardId: number): Promise {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} does not exist`);\n\t\t}\n\n\t\tawait shard.connect();\n\t}\n\n\t/**\n\t * Helper method to destroy a shard\n\t */\n\tprotected async destroy(shardId: number, options?: WebSocketShardDestroyOptions): Promise {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} does not exist`);\n\t\t}\n\n\t\tawait shard.destroy(options);\n\t}\n\n\t/**\n\t * Helper method to attach event listeners to the parentPort\n\t */\n\tprotected setupThreadEvents(): void {\n\t\tparentPort!\n\t\t\t.on('messageerror', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('message', async (payload: WorkerSendPayload) => {\n\t\t\t\tswitch (payload.op) {\n\t\t\t\t\tcase WorkerSendPayloadOp.Connect: {\n\t\t\t\t\t\tawait this.connect(payload.shardId);\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.Connected,\n\t\t\t\t\t\t\tshardId: payload.shardId,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.Destroy: {\n\t\t\t\t\t\tawait this.destroy(payload.shardId, payload.options);\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.Destroyed,\n\t\t\t\t\t\t\tshardId: payload.shardId,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.Send: {\n\t\t\t\t\t\tconst shard = this.shards.get(payload.shardId);\n\t\t\t\t\t\tif (!shard) {\n\t\t\t\t\t\t\tthrow new RangeError(`Shard ${payload.shardId} does not exist`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait shard.send(payload.payload);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.SessionInfoResponse: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.ShardIdentifyResponse: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.FetchStatus: {\n\t\t\t\t\t\tconst shard = this.shards.get(payload.shardId);\n\t\t\t\t\t\tif (!shard) {\n\t\t\t\t\t\t\tthrow new Error(`Shard ${payload.shardId} does not exist`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.FetchStatusResponse,\n\t\t\t\t\t\t\tstatus: shard.status,\n\t\t\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t}\n\n\t/**\n\t * Bootstraps the worker thread with the provided options\n\t */\n\tpublic async bootstrap(options: Readonly = {}): Promise {\n\t\t// Start by initializing the shards\n\t\tfor (const shardId of this.data.shardIds) {\n\t\t\tconst shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId);\n\t\t\tfor (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) {\n\t\t\t\t// @ts-expect-error: Event types incompatible\n\t\t\t\tshard.on(event, (data) => {\n\t\t\t\t\tconst payload: WorkerReceivePayload = {\n\t\t\t\t\t\top: WorkerReceivePayloadOp.Event,\n\t\t\t\t\t\tevent,\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\tshardId,\n\t\t\t\t\t};\n\t\t\t\t\tparentPort!.postMessage(payload);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Any additional setup the user might want to do\n\t\t\tawait options.shardCallback?.(shard);\n\t\t\tthis.shards.set(shardId, shard);\n\t\t}\n\n\t\t// Lastly, start listening to messages from the parent thread\n\t\tthis.setupThreadEvents();\n\n\t\tconst message: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.WorkerReady,\n\t\t};\n\t\tparentPort!.postMessage(message);\n\t}\n}\n","import type { REST } from '@discordjs/rest';\nimport { range, type Awaitable } from '@discordjs/util';\nimport { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\nimport {\n\tRoutes,\n\ttype APIGatewayBotInfo,\n\ttype GatewayIdentifyProperties,\n\ttype GatewayPresenceUpdateData,\n\ttype RESTGetAPIGatewayBotResult,\n\ttype GatewayIntentBits,\n\ttype GatewaySendPayload,\n} from 'discord-api-types/v10';\nimport type { IShardingStrategy } from '../strategies/sharding/IShardingStrategy.js';\nimport type { IIdentifyThrottler } from '../throttling/IIdentifyThrottler.js';\nimport { DefaultWebSocketManagerOptions, type CompressionMethod, type Encoding } from '../utils/constants.js';\nimport type { WebSocketShardDestroyOptions, WebSocketShardEventsMap } from './WebSocketShard.js';\n\n/**\n * Represents a range of shard ids\n */\nexport interface ShardRange {\n\tend: number;\n\tstart: number;\n}\n\n/**\n * Session information for a given shard, used to resume a session\n */\nexport interface SessionInfo {\n\t/**\n\t * URL to use when resuming\n\t */\n\tresumeURL: string;\n\t/**\n\t * The sequence number of the last message sent by the shard\n\t */\n\tsequence: number;\n\t/**\n\t * Session id for this shard\n\t */\n\tsessionId: string;\n\t/**\n\t * The total number of shards at the time of this shard identifying\n\t */\n\tshardCount: number;\n\t/**\n\t * The id of the shard\n\t */\n\tshardId: number;\n}\n\n/**\n * Required options for the WebSocketManager\n */\nexport interface RequiredWebSocketManagerOptions {\n\t/**\n\t * The intents to request\n\t */\n\tintents: GatewayIntentBits | 0;\n\t/**\n\t * The REST instance to use for fetching gateway information\n\t */\n\trest: REST;\n\t/**\n\t * The token to use for identifying with the gateway\n\t */\n\ttoken: string;\n}\n\n/**\n * Optional additional configuration for the WebSocketManager\n */\nexport interface OptionalWebSocketManagerOptions {\n\t/**\n\t * Builds an identify throttler to use for this manager's shards\n\t */\n\tbuildIdentifyThrottler(manager: WebSocketManager): Awaitable;\n\t/**\n\t * Builds the strategy to use for sharding\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new WebSocketManager({\n\t * token: process.env.DISCORD_TOKEN,\n\t * intents: 0, // for no intents\n\t * rest,\n\t * buildStrategy: (manager) => new WorkerShardingStrategy(manager, { shardsPerWorker: 2 }),\n\t * });\n\t * ```\n\t */\n\tbuildStrategy(manager: WebSocketManager): IShardingStrategy;\n\t/**\n\t * The compression method to use\n\t *\n\t * @defaultValue `null` (no compression)\n\t */\n\tcompression: CompressionMethod | null;\n\t/**\n\t * The encoding to use\n\t *\n\t * @defaultValue `'json'`\n\t */\n\tencoding: Encoding;\n\t/**\n\t * How long to wait for a shard to connect before giving up\n\t */\n\thandshakeTimeout: number | null;\n\t/**\n\t * How long to wait for a shard's HELLO packet before giving up\n\t */\n\thelloTimeout: number | null;\n\t/**\n\t * Properties to send to the gateway when identifying\n\t */\n\tidentifyProperties: GatewayIdentifyProperties;\n\t/**\n\t * Initial presence data to send to the gateway when identifying\n\t */\n\tinitialPresence: GatewayPresenceUpdateData | null;\n\t/**\n\t * Value between 50 and 250, total number of members where the gateway will stop sending offline members in the guild member list\n\t */\n\tlargeThreshold: number | null;\n\t/**\n\t * How long to wait for a shard's READY packet before giving up\n\t */\n\treadyTimeout: number | null;\n\t/**\n\t * Function used to retrieve session information (and attempt to resume) for a given shard\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new WebSocketManager({\n\t * async retrieveSessionInfo(shardId): Awaitable {\n\t * // Fetch this info from redis or similar\n\t * return { sessionId: string, sequence: number };\n\t * // Return null if no information is found\n\t * },\n\t * });\n\t * ```\n\t */\n\tretrieveSessionInfo(shardId: number): Awaitable;\n\t/**\n\t * The total number of shards across all WebsocketManagers you intend to instantiate.\n\t * Use `null` to use Discord's recommended shard count\n\t */\n\tshardCount: number | null;\n\t/**\n\t * The ids of the shards this WebSocketManager should manage.\n\t * Use `null` to simply spawn 0 through `shardCount - 1`\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new WebSocketManager({\n\t * shardIds: [1, 3, 7], // spawns shard 1, 3, and 7, nothing else\n\t * });\n\t * ```\n\t * @example\n\t * ```ts\n\t * const manager = new WebSocketManager({\n\t * shardIds: {\n\t * start: 3,\n\t * end: 6,\n\t * }, // spawns shards 3, 4, 5, and 6\n\t * });\n\t * ```\n\t */\n\tshardIds: number[] | ShardRange | null;\n\t/**\n\t * Function used to store session information for a given shard\n\t */\n\tupdateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable;\n\t/**\n\t * The gateway version to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\nexport type WebSocketManagerOptions = OptionalWebSocketManagerOptions & RequiredWebSocketManagerOptions;\n\nexport type ManagerShardEventsMap = {\n\t[K in keyof WebSocketShardEventsMap]: [\n\t\tWebSocketShardEventsMap[K] extends [] ? { shardId: number } : WebSocketShardEventsMap[K][0] & { shardId: number },\n\t];\n};\n\nexport class WebSocketManager extends AsyncEventEmitter {\n\t/**\n\t * The options being used by this manager\n\t */\n\tpublic readonly options: WebSocketManagerOptions;\n\n\t/**\n\t * Internal cache for a GET /gateway/bot result\n\t */\n\tprivate gatewayInformation: {\n\t\tdata: APIGatewayBotInfo;\n\t\texpiresAt: number;\n\t} | null = null;\n\n\t/**\n\t * Internal cache for the shard ids\n\t */\n\tprivate shardIds: number[] | null = null;\n\n\t/**\n\t * Strategy used to manage shards\n\t *\n\t * @defaultValue `SimpleShardingStrategy`\n\t */\n\tprivate readonly strategy: IShardingStrategy;\n\n\tpublic constructor(options: Partial & RequiredWebSocketManagerOptions) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultWebSocketManagerOptions, ...options };\n\t\tthis.strategy = this.options.buildStrategy(this);\n\t}\n\n\t/**\n\t * Fetches the gateway information from Discord - or returns it from cache if available\n\t *\n\t * @param force - Whether to ignore the cache and force a fresh fetch\n\t */\n\tpublic async fetchGatewayInformation(force = false) {\n\t\tif (this.gatewayInformation) {\n\t\t\tif (this.gatewayInformation.expiresAt <= Date.now()) {\n\t\t\t\tthis.gatewayInformation = null;\n\t\t\t} else if (!force) {\n\t\t\t\treturn this.gatewayInformation.data;\n\t\t\t}\n\t\t}\n\n\t\tconst data = (await this.options.rest.get(Routes.gatewayBot())) as RESTGetAPIGatewayBotResult;\n\n\t\tthis.gatewayInformation = { data, expiresAt: Date.now() + data.session_start_limit.reset_after };\n\t\treturn this.gatewayInformation.data;\n\t}\n\n\t/**\n\t * Updates your total shard count on-the-fly, spawning shards as needed\n\t *\n\t * @param shardCount - The new shard count to use\n\t */\n\tpublic async updateShardCount(shardCount: number | null) {\n\t\tawait this.strategy.destroy({ reason: 'User is adjusting their shards' });\n\t\tthis.options.shardCount = shardCount;\n\n\t\tconst shardIds = await this.getShardIds(true);\n\t\tawait this.strategy.spawn(shardIds);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Yields the total number of shards across for your bot, accounting for Discord recommendations\n\t */\n\tpublic async getShardCount(): Promise {\n\t\tif (this.options.shardCount) {\n\t\t\treturn this.options.shardCount;\n\t\t}\n\n\t\tconst shardIds = await this.getShardIds();\n\t\treturn Math.max(...shardIds) + 1;\n\t}\n\n\t/**\n\t * Yields the ids of the shards this manager should manage\n\t */\n\tpublic async getShardIds(force = false): Promise {\n\t\tif (this.shardIds && !force) {\n\t\t\treturn this.shardIds;\n\t\t}\n\n\t\tlet shardIds: number[];\n\t\tif (this.options.shardIds) {\n\t\t\tif (Array.isArray(this.options.shardIds)) {\n\t\t\t\tshardIds = this.options.shardIds;\n\t\t\t} else {\n\t\t\t\tconst { start, end } = this.options.shardIds;\n\t\t\t\tshardIds = [...range({ start, end: end + 1 })];\n\t\t\t}\n\t\t} else {\n\t\t\tconst data = await this.fetchGatewayInformation();\n\t\t\tshardIds = [...range(this.options.shardCount ?? data.shards)];\n\t\t}\n\n\t\tthis.shardIds = shardIds;\n\t\treturn shardIds;\n\t}\n\n\tpublic async connect() {\n\t\tconst shardCount = await this.getShardCount();\n\n\t\tconst data = await this.fetchGatewayInformation();\n\t\tif (data.session_start_limit.remaining < shardCount) {\n\t\t\tthrow new Error(\n\t\t\t\t`Not enough sessions remaining to spawn ${shardCount} shards; only ${\n\t\t\t\t\tdata.session_start_limit.remaining\n\t\t\t\t} remaining; resets at ${new Date(Date.now() + data.session_start_limit.reset_after).toISOString()}`,\n\t\t\t);\n\t\t}\n\n\t\t// First, make sure all our shards are spawned\n\t\tawait this.updateShardCount(shardCount);\n\t\tawait this.strategy.connect();\n\t}\n\n\tpublic destroy(options?: Omit) {\n\t\treturn this.strategy.destroy(options);\n\t}\n\n\tpublic send(shardId: number, payload: GatewaySendPayload) {\n\t\treturn this.strategy.send(shardId, payload);\n\t}\n\n\tpublic fetchStatus() {\n\t\treturn this.strategy.fetchStatus();\n\t}\n}\n"],"mappings":";;;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AAAA,EAC3C;AAAA,EAEO,cAAc;AACpB,WAAO,KAAK,SAAS,YAAY;AAAA,EAClC;AACD;AApIa;;;AVtKN,IAAM,UAAU;","names":["import_node_worker_threads","import_collection","WorkerSendPayloadOp","WorkerReceivePayloadOp","workerData","resolve","resolve","payload","import_collection","import_node_events","import_promises","import_collection","import_util","import_async_queue","import_v10","import_collection","import_collection","sleep","Encoding","CompressionMethod","process","WebSocketShardEvents","WebSocketShardStatus","WebSocketShardDestroyRecovery","CloseCodes","version","sleep","resolve","session","import_node_worker_threads","import_collection","import_util","import_async_event_emitter","import_v10"]} \ No newline at end of file diff --git a/node_modules/@discordjs/ws/dist/index.mjs b/node_modules/@discordjs/ws/dist/index.mjs new file mode 100644 index 0000000..cf55d10 --- /dev/null +++ b/node_modules/@discordjs/ws/dist/index.mjs @@ -0,0 +1,1373 @@ +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw new Error('Dynamic require of "' + x + '" is not supported'); +}); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// ../../node_modules/tsup/assets/esm_shims.js +import { fileURLToPath } from "url"; +import path from "path"; +var getFilename = /* @__PURE__ */ __name(() => fileURLToPath(import.meta.url), "getFilename"); +var getDirname = /* @__PURE__ */ __name(() => path.dirname(getFilename()), "getDirname"); +var __dirname = /* @__PURE__ */ getDirname(); + +// src/strategies/context/IContextFetchingStrategy.ts +async function managerToFetchingStrategyOptions(manager) { + const { + buildIdentifyThrottler, + buildStrategy, + retrieveSessionInfo, + updateSessionInfo, + shardCount, + shardIds, + rest, + ...managerOptions + } = manager.options; + return { + ...managerOptions, + gatewayInformation: await manager.fetchGatewayInformation(), + shardCount: await manager.getShardCount() + }; +} +__name(managerToFetchingStrategyOptions, "managerToFetchingStrategyOptions"); + +// src/strategies/context/SimpleContextFetchingStrategy.ts +var _SimpleContextFetchingStrategy = class { + constructor(manager, options) { + this.manager = manager; + this.options = options; + } + static async ensureThrottler(manager) { + const throttler = _SimpleContextFetchingStrategy.throttlerCache.get(manager); + if (throttler) { + return throttler; + } + const newThrottler = await manager.options.buildIdentifyThrottler(manager); + _SimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler); + return newThrottler; + } + async retrieveSessionInfo(shardId) { + return this.manager.options.retrieveSessionInfo(shardId); + } + updateSessionInfo(shardId, sessionInfo) { + return this.manager.options.updateSessionInfo(shardId, sessionInfo); + } + async waitForIdentify(shardId, signal) { + const throttler = await _SimpleContextFetchingStrategy.ensureThrottler(this.manager); + await throttler.waitForIdentify(shardId, signal); + } +}; +var SimpleContextFetchingStrategy = _SimpleContextFetchingStrategy; +__name(SimpleContextFetchingStrategy, "SimpleContextFetchingStrategy"); +// This strategy assumes every shard is running under the same process - therefore we need a single +// IdentifyThrottler per manager. +__publicField(SimpleContextFetchingStrategy, "throttlerCache", /* @__PURE__ */ new WeakMap()); + +// src/strategies/context/WorkerContextFetchingStrategy.ts +import { isMainThread, parentPort } from "node:worker_threads"; +import { Collection as Collection2 } from "@discordjs/collection"; + +// src/strategies/sharding/WorkerShardingStrategy.ts +import { once } from "node:events"; +import { join, isAbsolute, resolve } from "node:path"; +import { Worker } from "node:worker_threads"; +import { Collection } from "@discordjs/collection"; +var WorkerSendPayloadOp = /* @__PURE__ */ ((WorkerSendPayloadOp2) => { + WorkerSendPayloadOp2[WorkerSendPayloadOp2["Connect"] = 0] = "Connect"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["Destroy"] = 1] = "Destroy"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["Send"] = 2] = "Send"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["SessionInfoResponse"] = 3] = "SessionInfoResponse"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["ShardIdentifyResponse"] = 4] = "ShardIdentifyResponse"; + WorkerSendPayloadOp2[WorkerSendPayloadOp2["FetchStatus"] = 5] = "FetchStatus"; + return WorkerSendPayloadOp2; +})(WorkerSendPayloadOp || {}); +var WorkerReceivePayloadOp = /* @__PURE__ */ ((WorkerReceivePayloadOp2) => { + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["Connected"] = 0] = "Connected"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["Destroyed"] = 1] = "Destroyed"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["Event"] = 2] = "Event"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["RetrieveSessionInfo"] = 3] = "RetrieveSessionInfo"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["UpdateSessionInfo"] = 4] = "UpdateSessionInfo"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["WaitForIdentify"] = 5] = "WaitForIdentify"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["FetchStatusResponse"] = 6] = "FetchStatusResponse"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["WorkerReady"] = 7] = "WorkerReady"; + WorkerReceivePayloadOp2[WorkerReceivePayloadOp2["CancelIdentify"] = 8] = "CancelIdentify"; + return WorkerReceivePayloadOp2; +})(WorkerReceivePayloadOp || {}); +var WorkerShardingStrategy = class { + manager; + options; + #workers = []; + #workerByShardId = new Collection(); + connectPromises = new Collection(); + destroyPromises = new Collection(); + fetchStatusPromises = new Collection(); + waitForIdentifyControllers = new Collection(); + throttler; + constructor(manager, options) { + this.manager = manager; + this.options = options; + } + /** + * {@inheritDoc IShardingStrategy.spawn} + */ + async spawn(shardIds) { + const shardsPerWorker = this.options.shardsPerWorker === "all" ? shardIds.length : this.options.shardsPerWorker; + const strategyOptions = await managerToFetchingStrategyOptions(this.manager); + const loops = Math.ceil(shardIds.length / shardsPerWorker); + const promises = []; + for (let idx = 0; idx < loops; idx++) { + const slice = shardIds.slice(idx * shardsPerWorker, (idx + 1) * shardsPerWorker); + const workerData2 = { + ...strategyOptions, + shardIds: slice + }; + promises.push(this.setupWorker(workerData2)); + } + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.connect} + */ + async connect() { + const promises = []; + for (const [shardId, worker] of this.#workerByShardId.entries()) { + const payload = { + op: 0 /* Connect */, + shardId + }; + const promise = new Promise((resolve2) => this.connectPromises.set(shardId, resolve2)); + worker.postMessage(payload); + promises.push(promise); + } + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.destroy} + */ + async destroy(options = {}) { + const promises = []; + for (const [shardId, worker] of this.#workerByShardId.entries()) { + const payload = { + op: 1 /* Destroy */, + shardId, + options + }; + promises.push( + // eslint-disable-next-line no-promise-executor-return, promise/prefer-await-to-then + new Promise((resolve2) => this.destroyPromises.set(shardId, resolve2)).then(async () => worker.terminate()) + ); + worker.postMessage(payload); + } + this.#workers = []; + this.#workerByShardId.clear(); + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.send} + */ + send(shardId, data) { + const worker = this.#workerByShardId.get(shardId); + if (!worker) { + throw new Error(`No worker found for shard ${shardId}`); + } + const payload = { + op: 2 /* Send */, + shardId, + payload: data + }; + worker.postMessage(payload); + } + /** + * {@inheritDoc IShardingStrategy.fetchStatus} + */ + async fetchStatus() { + const statuses = new Collection(); + for (const [shardId, worker] of this.#workerByShardId.entries()) { + const nonce = Math.random(); + const payload = { + op: 5 /* FetchStatus */, + shardId, + nonce + }; + const promise = new Promise((resolve2) => this.fetchStatusPromises.set(nonce, resolve2)); + worker.postMessage(payload); + const status = await promise; + statuses.set(shardId, status); + } + return statuses; + } + async setupWorker(workerData2) { + const worker = new Worker(this.resolveWorkerPath(), { workerData: workerData2 }); + await once(worker, "online"); + await this.waitForWorkerReady(worker); + worker.on("error", (err) => { + throw err; + }).on("messageerror", (err) => { + throw err; + }).on("message", async (payload) => this.onMessage(worker, payload)); + this.#workers.push(worker); + for (const shardId of workerData2.shardIds) { + this.#workerByShardId.set(shardId, worker); + } + } + resolveWorkerPath() { + const path2 = this.options.workerPath; + if (!path2) { + return join(__dirname, "defaultWorker.js"); + } + if (isAbsolute(path2)) { + return path2; + } + if (/^\.\.?[/\\]/.test(path2)) { + return resolve(path2); + } + try { + return __require.resolve(path2); + } catch { + return resolve(path2); + } + } + async waitForWorkerReady(worker) { + return new Promise((resolve2) => { + const handler = /* @__PURE__ */ __name((payload) => { + if (payload.op === 7 /* WorkerReady */) { + resolve2(); + worker.off("message", handler); + } + }, "handler"); + worker.on("message", handler); + }); + } + async onMessage(worker, payload) { + switch (payload.op) { + case 0 /* Connected */: { + this.connectPromises.get(payload.shardId)?.(); + this.connectPromises.delete(payload.shardId); + break; + } + case 1 /* Destroyed */: { + this.destroyPromises.get(payload.shardId)?.(); + this.destroyPromises.delete(payload.shardId); + break; + } + case 2 /* Event */: { + this.manager.emit(payload.event, { ...payload.data, shardId: payload.shardId }); + break; + } + case 3 /* RetrieveSessionInfo */: { + const session = await this.manager.options.retrieveSessionInfo(payload.shardId); + const response = { + op: 3 /* SessionInfoResponse */, + nonce: payload.nonce, + session + }; + worker.postMessage(response); + break; + } + case 4 /* UpdateSessionInfo */: { + await this.manager.options.updateSessionInfo(payload.shardId, payload.session); + break; + } + case 5 /* WaitForIdentify */: { + const throttler = await this.ensureThrottler(); + try { + const controller = new AbortController(); + this.waitForIdentifyControllers.set(payload.nonce, controller); + await throttler.waitForIdentify(payload.shardId, controller.signal); + } catch { + return; + } + const response = { + op: 4 /* ShardIdentifyResponse */, + nonce: payload.nonce, + ok: true + }; + worker.postMessage(response); + break; + } + case 6 /* FetchStatusResponse */: { + this.fetchStatusPromises.get(payload.nonce)?.(payload.status); + this.fetchStatusPromises.delete(payload.nonce); + break; + } + case 7 /* WorkerReady */: { + break; + } + case 8 /* CancelIdentify */: { + this.waitForIdentifyControllers.get(payload.nonce)?.abort(); + this.waitForIdentifyControllers.delete(payload.nonce); + const response = { + op: 4 /* ShardIdentifyResponse */, + nonce: payload.nonce, + ok: false + }; + worker.postMessage(response); + break; + } + } + } + async ensureThrottler() { + this.throttler ??= await this.manager.options.buildIdentifyThrottler(this.manager); + return this.throttler; + } +}; +__name(WorkerShardingStrategy, "WorkerShardingStrategy"); + +// src/strategies/context/WorkerContextFetchingStrategy.ts +var WorkerContextFetchingStrategy = class { + constructor(options) { + this.options = options; + if (isMainThread) { + throw new Error("Cannot instantiate WorkerContextFetchingStrategy on the main thread"); + } + parentPort.on("message", (payload) => { + if (payload.op === 3 /* SessionInfoResponse */) { + this.sessionPromises.get(payload.nonce)?.(payload.session); + this.sessionPromises.delete(payload.nonce); + } + if (payload.op === 4 /* ShardIdentifyResponse */) { + const promise = this.waitForIdentifyPromises.get(payload.nonce); + if (payload.ok) { + promise?.resolve(); + } else { + promise?.reject(); + } + this.waitForIdentifyPromises.delete(payload.nonce); + } + }); + } + sessionPromises = new Collection2(); + waitForIdentifyPromises = new Collection2(); + async retrieveSessionInfo(shardId) { + const nonce = Math.random(); + const payload = { + op: 3 /* RetrieveSessionInfo */, + shardId, + nonce + }; + const promise = new Promise((resolve2) => this.sessionPromises.set(nonce, resolve2)); + parentPort.postMessage(payload); + return promise; + } + updateSessionInfo(shardId, sessionInfo) { + const payload = { + op: 4 /* UpdateSessionInfo */, + shardId, + session: sessionInfo + }; + parentPort.postMessage(payload); + } + async waitForIdentify(shardId, signal) { + const nonce = Math.random(); + const payload = { + op: 5 /* WaitForIdentify */, + nonce, + shardId + }; + const promise = new Promise( + (resolve2, reject) => ( + // eslint-disable-next-line no-promise-executor-return + this.waitForIdentifyPromises.set(nonce, { resolve: resolve2, reject }) + ) + ); + parentPort.postMessage(payload); + const listener = /* @__PURE__ */ __name(() => { + const payload2 = { + op: 8 /* CancelIdentify */, + nonce + }; + parentPort.postMessage(payload2); + }, "listener"); + signal.addEventListener("abort", listener); + try { + await promise; + } finally { + signal.removeEventListener("abort", listener); + } + } +}; +__name(WorkerContextFetchingStrategy, "WorkerContextFetchingStrategy"); + +// src/strategies/sharding/SimpleShardingStrategy.ts +import { Collection as Collection6 } from "@discordjs/collection"; + +// src/ws/WebSocketShard.ts +import { Buffer as Buffer2 } from "node:buffer"; +import { once as once2 } from "node:events"; +import { clearInterval, clearTimeout, setInterval, setTimeout } from "node:timers"; +import { setTimeout as sleep2 } from "node:timers/promises"; +import { URLSearchParams } from "node:url"; +import { TextDecoder } from "node:util"; +import { inflate } from "node:zlib"; +import { Collection as Collection5 } from "@discordjs/collection"; +import { lazy as lazy2 } from "@discordjs/util"; +import { AsyncQueue as AsyncQueue2 } from "@sapphire/async-queue"; +import { AsyncEventEmitter } from "@vladfrangu/async_event_emitter"; +import { + GatewayCloseCodes, + GatewayDispatchEvents, + GatewayOpcodes as GatewayOpcodes2 +} from "discord-api-types/v10"; +import { WebSocket } from "ws"; + +// src/utils/constants.ts +import process from "node:process"; +import { Collection as Collection4 } from "@discordjs/collection"; +import { lazy } from "@discordjs/util"; +import { APIVersion, GatewayOpcodes } from "discord-api-types/v10"; + +// src/throttling/SimpleIdentifyThrottler.ts +import { setTimeout as sleep } from "node:timers/promises"; +import { Collection as Collection3 } from "@discordjs/collection"; +import { AsyncQueue } from "@sapphire/async-queue"; +var SimpleIdentifyThrottler = class { + constructor(maxConcurrency) { + this.maxConcurrency = maxConcurrency; + } + states = new Collection3(); + /** + * {@inheritDoc IIdentifyThrottler.waitForIdentify} + */ + async waitForIdentify(shardId, signal) { + const key = shardId % this.maxConcurrency; + const state = this.states.ensure(key, () => { + return { + queue: new AsyncQueue(), + resetsAt: Number.POSITIVE_INFINITY + }; + }); + await state.queue.wait({ signal }); + try { + const diff = state.resetsAt - Date.now(); + if (diff <= 5e3) { + const time = diff + Math.random() * 1500; + await sleep(time); + } + state.resetsAt = Date.now() + 5e3; + } finally { + state.queue.shift(); + } + } +}; +__name(SimpleIdentifyThrottler, "SimpleIdentifyThrottler"); + +// src/utils/constants.ts +var Encoding = /* @__PURE__ */ ((Encoding2) => { + Encoding2["JSON"] = "json"; + return Encoding2; +})(Encoding || {}); +var CompressionMethod = /* @__PURE__ */ ((CompressionMethod2) => { + CompressionMethod2["ZlibStream"] = "zlib-stream"; + return CompressionMethod2; +})(CompressionMethod || {}); +var DefaultDeviceProperty = `@discordjs/ws 0.8.3`; +var getDefaultSessionStore = lazy(() => new Collection4()); +var DefaultWebSocketManagerOptions = { + async buildIdentifyThrottler(manager) { + const info = await manager.fetchGatewayInformation(); + return new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency); + }, + buildStrategy: (manager) => new SimpleShardingStrategy(manager), + shardCount: null, + shardIds: null, + largeThreshold: null, + initialPresence: null, + identifyProperties: { + browser: DefaultDeviceProperty, + device: DefaultDeviceProperty, + os: process.platform + }, + version: APIVersion, + encoding: "json" /* JSON */, + compression: null, + retrieveSessionInfo(shardId) { + const store = getDefaultSessionStore(); + return store.get(shardId) ?? null; + }, + updateSessionInfo(shardId, info) { + const store = getDefaultSessionStore(); + if (info) { + store.set(shardId, info); + } else { + store.delete(shardId); + } + }, + handshakeTimeout: 3e4, + helloTimeout: 6e4, + readyTimeout: 15e3 +}; +var ImportantGatewayOpcodes = /* @__PURE__ */ new Set([ + GatewayOpcodes.Heartbeat, + GatewayOpcodes.Identify, + GatewayOpcodes.Resume +]); +function getInitialSendRateLimitState() { + return { + remaining: 120, + resetAt: Date.now() + 6e4 + }; +} +__name(getInitialSendRateLimitState, "getInitialSendRateLimitState"); + +// src/ws/WebSocketShard.ts +var getZlibSync = lazy2(async () => import("zlib-sync").then((mod) => mod.default).catch(() => null)); +var WebSocketShardEvents = /* @__PURE__ */ ((WebSocketShardEvents2) => { + WebSocketShardEvents2["Closed"] = "closed"; + WebSocketShardEvents2["Debug"] = "debug"; + WebSocketShardEvents2["Dispatch"] = "dispatch"; + WebSocketShardEvents2["Error"] = "error"; + WebSocketShardEvents2["HeartbeatComplete"] = "heartbeat"; + WebSocketShardEvents2["Hello"] = "hello"; + WebSocketShardEvents2["Ready"] = "ready"; + WebSocketShardEvents2["Resumed"] = "resumed"; + return WebSocketShardEvents2; +})(WebSocketShardEvents || {}); +var WebSocketShardStatus = /* @__PURE__ */ ((WebSocketShardStatus2) => { + WebSocketShardStatus2[WebSocketShardStatus2["Idle"] = 0] = "Idle"; + WebSocketShardStatus2[WebSocketShardStatus2["Connecting"] = 1] = "Connecting"; + WebSocketShardStatus2[WebSocketShardStatus2["Resuming"] = 2] = "Resuming"; + WebSocketShardStatus2[WebSocketShardStatus2["Ready"] = 3] = "Ready"; + return WebSocketShardStatus2; +})(WebSocketShardStatus || {}); +var WebSocketShardDestroyRecovery = /* @__PURE__ */ ((WebSocketShardDestroyRecovery2) => { + WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Reconnect"] = 0] = "Reconnect"; + WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Resume"] = 1] = "Resume"; + return WebSocketShardDestroyRecovery2; +})(WebSocketShardDestroyRecovery || {}); +var CloseCodes = /* @__PURE__ */ ((CloseCodes2) => { + CloseCodes2[CloseCodes2["Normal"] = 1e3] = "Normal"; + CloseCodes2[CloseCodes2["Resuming"] = 4200] = "Resuming"; + return CloseCodes2; +})(CloseCodes || {}); +var WebSocketShard = class extends AsyncEventEmitter { + connection = null; + useIdentifyCompress = false; + inflate = null; + textDecoder = new TextDecoder(); + replayedEvents = 0; + isAck = true; + sendRateLimitState = getInitialSendRateLimitState(); + initialHeartbeatTimeoutController = null; + heartbeatInterval = null; + lastHeartbeatAt = -1; + // Indicates whether the shard has already resolved its original connect() call + initialConnectResolved = false; + // Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET) + failedToConnectDueToNetworkError = false; + sendQueue = new AsyncQueue2(); + timeoutAbortControllers = new Collection5(); + strategy; + id; + #status = 0 /* Idle */; + get status() { + return this.#status; + } + constructor(strategy, id) { + super(); + this.strategy = strategy; + this.id = id; + } + async connect() { + const promise = this.initialConnectResolved ? Promise.resolve() : once2(this, "ready" /* Ready */); + void this.internalConnect(); + await promise; + this.initialConnectResolved = true; + } + async internalConnect() { + if (this.#status !== 0 /* Idle */) { + throw new Error("Tried to connect a shard that wasn't idle"); + } + const { version: version2, encoding, compression } = this.strategy.options; + const params = new URLSearchParams({ v: version2, encoding }); + if (compression) { + const zlib = await getZlibSync(); + if (zlib) { + params.append("compress", compression); + this.inflate = new zlib.Inflate({ + chunkSize: 65535, + to: "string" + }); + } else if (!this.useIdentifyCompress) { + this.useIdentifyCompress = true; + console.warn( + "WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress" + ); + } + } + const session = await this.strategy.retrieveSessionInfo(this.id); + const url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`; + this.debug([`Connecting to ${url}`]); + const connection = new WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? void 0 }).on("message", this.onMessage.bind(this)).on("error", this.onError.bind(this)).on("close", this.onClose.bind(this)); + connection.binaryType = "arraybuffer"; + this.connection = connection; + this.#status = 1 /* Connecting */; + this.sendRateLimitState = getInitialSendRateLimitState(); + const { ok } = await this.waitForEvent("hello" /* Hello */, this.strategy.options.helloTimeout); + if (!ok) { + return; + } + if (session?.shardCount === this.strategy.options.shardCount) { + await this.resume(session); + } else { + await this.identify(); + } + } + async destroy(options = {}) { + if (this.#status === 0 /* Idle */) { + this.debug(["Tried to destroy a shard that was idle"]); + return; + } + if (!options.code) { + options.code = options.recover === 1 /* Resume */ ? 4200 /* Resuming */ : 1e3 /* Normal */; + } + this.debug([ + "Destroying shard", + `Reason: ${options.reason ?? "none"}`, + `Code: ${options.code}`, + `Recover: ${options.recover === void 0 ? "none" : WebSocketShardDestroyRecovery[options.recover]}` + ]); + this.isAck = true; + if (this.heartbeatInterval) { + clearInterval(this.heartbeatInterval); + } + if (this.initialHeartbeatTimeoutController) { + this.initialHeartbeatTimeoutController.abort(); + this.initialHeartbeatTimeoutController = null; + } + this.lastHeartbeatAt = -1; + for (const controller of this.timeoutAbortControllers.values()) { + controller.abort(); + } + this.timeoutAbortControllers.clear(); + this.failedToConnectDueToNetworkError = false; + if (options.recover !== 1 /* Resume */) { + await this.strategy.updateSessionInfo(this.id, null); + } + if (this.connection) { + this.connection.removeAllListeners("message"); + this.connection.removeAllListeners("close"); + const shouldClose = this.connection.readyState === WebSocket.OPEN; + this.debug([ + "Connection status during destroy", + `Needs closing: ${shouldClose}`, + `Ready state: ${this.connection.readyState}` + ]); + if (shouldClose) { + this.connection.close(options.code, options.reason); + await once2(this.connection, "close"); + this.emit("closed" /* Closed */, { code: options.code }); + } + this.connection.removeAllListeners("error"); + } else { + this.debug(["Destroying a shard that has no connection; please open an issue on GitHub"]); + } + this.#status = 0 /* Idle */; + if (options.recover !== void 0) { + await sleep2(500); + return this.internalConnect(); + } + } + async waitForEvent(event, timeoutDuration) { + this.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : "indefinitely"}`]); + const timeoutController = new AbortController(); + const timeout = timeoutDuration ? setTimeout(() => timeoutController.abort(), timeoutDuration).unref() : null; + this.timeoutAbortControllers.set(event, timeoutController); + const closeController = new AbortController(); + try { + const closed = await Promise.race([ + once2(this, event, { signal: timeoutController.signal }).then(() => false), + once2(this, "closed" /* Closed */, { signal: closeController.signal }).then(() => true) + ]); + return { ok: !closed }; + } catch { + void this.destroy({ + code: 1e3 /* Normal */, + reason: "Something timed out or went wrong while waiting for an event", + recover: 0 /* Reconnect */ + }); + return { ok: false }; + } finally { + if (timeout) { + clearTimeout(timeout); + } + this.timeoutAbortControllers.delete(event); + if (!closeController.signal.aborted) { + closeController.abort(); + } + } + } + async send(payload) { + if (!this.connection) { + throw new Error("WebSocketShard wasn't connected"); + } + if (this.#status !== 3 /* Ready */ && !ImportantGatewayOpcodes.has(payload.op)) { + this.debug(["Tried to send a non-crucial payload before the shard was ready, waiting"]); + try { + await once2(this, "ready" /* Ready */); + } catch { + return this.send(payload); + } + } + await this.sendQueue.wait(); + if (--this.sendRateLimitState.remaining <= 0) { + const now = Date.now(); + if (this.sendRateLimitState.resetAt > now) { + const sleepFor = this.sendRateLimitState.resetAt - now; + this.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]); + const controller = new AbortController(); + const interrupted = await Promise.race([ + sleep2(sleepFor).then(() => false), + once2(this, "closed" /* Closed */, { signal: controller.signal }).then(() => true) + ]); + if (interrupted) { + this.debug(["Connection closed while waiting for the send rate limit to reset, re-queueing payload"]); + this.sendQueue.shift(); + return this.send(payload); + } + controller.abort(); + } + this.sendRateLimitState = getInitialSendRateLimitState(); + } + this.sendQueue.shift(); + this.connection.send(JSON.stringify(payload)); + } + async identify() { + this.debug(["Waiting for identify throttle"]); + const controller = new AbortController(); + const closeHandler = /* @__PURE__ */ __name(() => { + controller.abort(); + }, "closeHandler"); + this.on("closed" /* Closed */, closeHandler); + try { + await this.strategy.waitForIdentify(this.id, controller.signal); + } catch { + this.debug(["Was waiting for an identify, but the shard closed in the meantime"]); + return; + } finally { + this.off("closed" /* Closed */, closeHandler); + } + this.debug([ + "Identifying", + `shard id: ${this.id.toString()}`, + `shard count: ${this.strategy.options.shardCount}`, + `intents: ${this.strategy.options.intents}`, + `compression: ${this.inflate ? "zlib-stream" : this.useIdentifyCompress ? "identify" : "none"}` + ]); + const d = { + token: this.strategy.options.token, + properties: this.strategy.options.identifyProperties, + intents: this.strategy.options.intents, + compress: this.useIdentifyCompress, + shard: [this.id, this.strategy.options.shardCount] + }; + if (this.strategy.options.largeThreshold) { + d.large_threshold = this.strategy.options.largeThreshold; + } + if (this.strategy.options.initialPresence) { + d.presence = this.strategy.options.initialPresence; + } + await this.send({ + op: GatewayOpcodes2.Identify, + d + }); + await this.waitForEvent("ready" /* Ready */, this.strategy.options.readyTimeout); + } + async resume(session) { + this.debug([ + "Resuming session", + `resume url: ${session.resumeURL}`, + `sequence: ${session.sequence}`, + `shard id: ${this.id.toString()}` + ]); + this.#status = 2 /* Resuming */; + this.replayedEvents = 0; + return this.send({ + op: GatewayOpcodes2.Resume, + d: { + token: this.strategy.options.token, + seq: session.sequence, + session_id: session.sessionId + } + }); + } + async heartbeat(requested = false) { + if (!this.isAck && !requested) { + return this.destroy({ reason: "Zombie connection", recover: 1 /* Resume */ }); + } + const session = await this.strategy.retrieveSessionInfo(this.id); + await this.send({ + op: GatewayOpcodes2.Heartbeat, + d: session?.sequence ?? null + }); + this.lastHeartbeatAt = Date.now(); + this.isAck = false; + } + async unpackMessage(data, isBinary) { + const decompressable = new Uint8Array(data); + if (!isBinary) { + return JSON.parse(this.textDecoder.decode(decompressable)); + } + if (this.useIdentifyCompress) { + return new Promise((resolve2, reject) => { + inflate(decompressable, { chunkSize: 65535 }, (err, result) => { + if (err) { + reject(err); + return; + } + resolve2(JSON.parse(this.textDecoder.decode(result))); + }); + }); + } + if (this.inflate) { + const l = decompressable.length; + const flush = l >= 4 && decompressable[l - 4] === 0 && decompressable[l - 3] === 0 && decompressable[l - 2] === 255 && decompressable[l - 1] === 255; + const zlib = await getZlibSync(); + this.inflate.push(Buffer2.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH); + if (this.inflate.err) { + this.emit("error" /* Error */, { + error: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ""}`) + }); + } + if (!flush) { + return null; + } + const { result } = this.inflate; + if (!result) { + return null; + } + return JSON.parse(typeof result === "string" ? result : this.textDecoder.decode(result)); + } + this.debug([ + "Received a message we were unable to decompress", + `isBinary: ${isBinary.toString()}`, + `useIdentifyCompress: ${this.useIdentifyCompress.toString()}`, + `inflate: ${Boolean(this.inflate).toString()}` + ]); + return null; + } + async onMessage(data, isBinary) { + const payload = await this.unpackMessage(data, isBinary); + if (!payload) { + return; + } + switch (payload.op) { + case GatewayOpcodes2.Dispatch: { + if (this.#status === 2 /* Resuming */) { + this.replayedEvents++; + } + switch (payload.t) { + case GatewayDispatchEvents.Ready: { + this.#status = 3 /* Ready */; + const session2 = { + sequence: payload.s, + sessionId: payload.d.session_id, + shardId: this.id, + shardCount: this.strategy.options.shardCount, + resumeURL: payload.d.resume_gateway_url + }; + await this.strategy.updateSessionInfo(this.id, session2); + this.emit("ready" /* Ready */, { data: payload.d }); + break; + } + case GatewayDispatchEvents.Resumed: { + this.#status = 3 /* Ready */; + this.debug([`Resumed and replayed ${this.replayedEvents} events`]); + this.emit("resumed" /* Resumed */); + break; + } + default: { + break; + } + } + const session = await this.strategy.retrieveSessionInfo(this.id); + if (session) { + if (payload.s > session.sequence) { + await this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s }); + } + } else { + this.debug([ + `Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect` + ]); + } + this.emit("dispatch" /* Dispatch */, { data: payload }); + break; + } + case GatewayOpcodes2.Heartbeat: { + await this.heartbeat(true); + break; + } + case GatewayOpcodes2.Reconnect: { + await this.destroy({ + reason: "Told to reconnect by Discord", + recover: 1 /* Resume */ + }); + break; + } + case GatewayOpcodes2.InvalidSession: { + this.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]); + const session = await this.strategy.retrieveSessionInfo(this.id); + if (payload.d && session) { + await this.resume(session); + } else { + await this.destroy({ + reason: "Invalid session", + recover: 0 /* Reconnect */ + }); + } + break; + } + case GatewayOpcodes2.Hello: { + this.emit("hello" /* Hello */); + const jitter = Math.random(); + const firstWait = Math.floor(payload.d.heartbeat_interval * jitter); + this.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]); + try { + const controller = new AbortController(); + this.initialHeartbeatTimeoutController = controller; + await sleep2(firstWait, void 0, { signal: controller.signal }); + } catch { + this.debug(["Cancelled initial heartbeat due to #destroy being called"]); + return; + } finally { + this.initialHeartbeatTimeoutController = null; + } + await this.heartbeat(); + this.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]); + this.heartbeatInterval = setInterval(() => void this.heartbeat(), payload.d.heartbeat_interval); + break; + } + case GatewayOpcodes2.HeartbeatAck: { + this.isAck = true; + const ackAt = Date.now(); + this.emit("heartbeat" /* HeartbeatComplete */, { + ackAt, + heartbeatAt: this.lastHeartbeatAt, + latency: ackAt - this.lastHeartbeatAt + }); + break; + } + } + } + onError(error) { + if ("code" in error && ["ECONNRESET", "ECONNREFUSED"].includes(error.code)) { + this.debug(["Failed to connect to the gateway URL specified due to a network error"]); + this.failedToConnectDueToNetworkError = true; + return; + } + this.emit("error" /* Error */, { error }); + } + async onClose(code) { + this.emit("closed" /* Closed */, { code }); + switch (code) { + case 1e3 /* Normal */: { + return this.destroy({ + code, + reason: "Got disconnected by Discord", + recover: 0 /* Reconnect */ + }); + } + case 4200 /* Resuming */: { + break; + } + case GatewayCloseCodes.UnknownError: { + this.debug([`An unknown error occurred: ${code}`]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case GatewayCloseCodes.UnknownOpcode: { + this.debug(["An invalid opcode was sent to Discord."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case GatewayCloseCodes.DecodeError: { + this.debug(["An invalid payload was sent to Discord."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case GatewayCloseCodes.NotAuthenticated: { + this.debug(["A request was somehow sent before the identify/resume payload."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case GatewayCloseCodes.AuthenticationFailed: { + throw new Error("Authentication failed"); + } + case GatewayCloseCodes.AlreadyAuthenticated: { + this.debug(["More than one auth payload was sent."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case GatewayCloseCodes.InvalidSeq: { + this.debug(["An invalid sequence was sent."]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case GatewayCloseCodes.RateLimited: { + this.debug(["The WebSocket rate limit has been hit, this should never happen"]); + return this.destroy({ code, recover: 0 /* Reconnect */ }); + } + case GatewayCloseCodes.SessionTimedOut: { + this.debug(["Session timed out."]); + return this.destroy({ code, recover: 1 /* Resume */ }); + } + case GatewayCloseCodes.InvalidShard: { + throw new Error("Invalid shard"); + } + case GatewayCloseCodes.ShardingRequired: { + throw new Error("Sharding is required"); + } + case GatewayCloseCodes.InvalidAPIVersion: { + throw new Error("Used an invalid API version"); + } + case GatewayCloseCodes.InvalidIntents: { + throw new Error("Used invalid intents"); + } + case GatewayCloseCodes.DisallowedIntents: { + throw new Error("Used disallowed intents"); + } + default: { + this.debug([ + `The gateway closed with an unexpected code ${code}, attempting to ${this.failedToConnectDueToNetworkError ? "reconnect" : "resume"}.` + ]); + return this.destroy({ + code, + recover: this.failedToConnectDueToNetworkError ? 0 /* Reconnect */ : 1 /* Resume */ + }); + } + } + } + debug(messages) { + const message = `${messages[0]}${messages.length > 1 ? ` +${messages.slice(1).map((m) => ` ${m}`).join("\n")}` : ""}`; + this.emit("debug" /* Debug */, { message }); + } +}; +__name(WebSocketShard, "WebSocketShard"); + +// src/strategies/sharding/SimpleShardingStrategy.ts +var SimpleShardingStrategy = class { + manager; + shards = new Collection6(); + constructor(manager) { + this.manager = manager; + } + /** + * {@inheritDoc IShardingStrategy.spawn} + */ + async spawn(shardIds) { + const strategyOptions = await managerToFetchingStrategyOptions(this.manager); + for (const shardId of shardIds) { + const strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions); + const shard = new WebSocketShard(strategy, shardId); + for (const event of Object.values(WebSocketShardEvents)) { + shard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId })); + } + this.shards.set(shardId, shard); + } + } + /** + * {@inheritDoc IShardingStrategy.connect} + */ + async connect() { + const promises = []; + for (const shard of this.shards.values()) { + promises.push(shard.connect()); + } + await Promise.all(promises); + } + /** + * {@inheritDoc IShardingStrategy.destroy} + */ + async destroy(options) { + const promises = []; + for (const shard of this.shards.values()) { + promises.push(shard.destroy(options)); + } + await Promise.all(promises); + this.shards.clear(); + } + /** + * {@inheritDoc IShardingStrategy.send} + */ + async send(shardId, payload) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} not found`); + } + return shard.send(payload); + } + /** + * {@inheritDoc IShardingStrategy.fetchStatus} + */ + async fetchStatus() { + return this.shards.mapValues((shard) => shard.status); + } +}; +__name(SimpleShardingStrategy, "SimpleShardingStrategy"); + +// src/utils/WorkerBootstrapper.ts +import { isMainThread as isMainThread2, parentPort as parentPort2, workerData } from "node:worker_threads"; +import { Collection as Collection7 } from "@discordjs/collection"; +var WorkerBootstrapper = class { + /** + * The data passed to the worker thread + */ + data = workerData; + /** + * The shards that are managed by this worker + */ + shards = new Collection7(); + constructor() { + if (isMainThread2) { + throw new Error("Expected WorkerBootstrap to not be used within the main thread"); + } + } + /** + * Helper method to initiate a shard's connection process + */ + async connect(shardId) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} does not exist`); + } + await shard.connect(); + } + /** + * Helper method to destroy a shard + */ + async destroy(shardId, options) { + const shard = this.shards.get(shardId); + if (!shard) { + throw new RangeError(`Shard ${shardId} does not exist`); + } + await shard.destroy(options); + } + /** + * Helper method to attach event listeners to the parentPort + */ + setupThreadEvents() { + parentPort2.on("messageerror", (err) => { + throw err; + }).on("message", async (payload) => { + switch (payload.op) { + case 0 /* Connect */: { + await this.connect(payload.shardId); + const response = { + op: 0 /* Connected */, + shardId: payload.shardId + }; + parentPort2.postMessage(response); + break; + } + case 1 /* Destroy */: { + await this.destroy(payload.shardId, payload.options); + const response = { + op: 1 /* Destroyed */, + shardId: payload.shardId + }; + parentPort2.postMessage(response); + break; + } + case 2 /* Send */: { + const shard = this.shards.get(payload.shardId); + if (!shard) { + throw new RangeError(`Shard ${payload.shardId} does not exist`); + } + await shard.send(payload.payload); + break; + } + case 3 /* SessionInfoResponse */: { + break; + } + case 4 /* ShardIdentifyResponse */: { + break; + } + case 5 /* FetchStatus */: { + const shard = this.shards.get(payload.shardId); + if (!shard) { + throw new Error(`Shard ${payload.shardId} does not exist`); + } + const response = { + op: 6 /* FetchStatusResponse */, + status: shard.status, + nonce: payload.nonce + }; + parentPort2.postMessage(response); + break; + } + } + }); + } + /** + * Bootstraps the worker thread with the provided options + */ + async bootstrap(options = {}) { + for (const shardId of this.data.shardIds) { + const shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId); + for (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) { + shard.on(event, (data) => { + const payload = { + op: 2 /* Event */, + event, + data, + shardId + }; + parentPort2.postMessage(payload); + }); + } + await options.shardCallback?.(shard); + this.shards.set(shardId, shard); + } + this.setupThreadEvents(); + const message = { + op: 7 /* WorkerReady */ + }; + parentPort2.postMessage(message); + } +}; +__name(WorkerBootstrapper, "WorkerBootstrapper"); + +// src/ws/WebSocketManager.ts +import { range } from "@discordjs/util"; +import { AsyncEventEmitter as AsyncEventEmitter2 } from "@vladfrangu/async_event_emitter"; +import { + Routes +} from "discord-api-types/v10"; +var WebSocketManager = class extends AsyncEventEmitter2 { + /** + * The options being used by this manager + */ + options; + /** + * Internal cache for a GET /gateway/bot result + */ + gatewayInformation = null; + /** + * Internal cache for the shard ids + */ + shardIds = null; + /** + * Strategy used to manage shards + * + * @defaultValue `SimpleShardingStrategy` + */ + strategy; + constructor(options) { + super(); + this.options = { ...DefaultWebSocketManagerOptions, ...options }; + this.strategy = this.options.buildStrategy(this); + } + /** + * Fetches the gateway information from Discord - or returns it from cache if available + * + * @param force - Whether to ignore the cache and force a fresh fetch + */ + async fetchGatewayInformation(force = false) { + if (this.gatewayInformation) { + if (this.gatewayInformation.expiresAt <= Date.now()) { + this.gatewayInformation = null; + } else if (!force) { + return this.gatewayInformation.data; + } + } + const data = await this.options.rest.get(Routes.gatewayBot()); + this.gatewayInformation = { data, expiresAt: Date.now() + data.session_start_limit.reset_after }; + return this.gatewayInformation.data; + } + /** + * Updates your total shard count on-the-fly, spawning shards as needed + * + * @param shardCount - The new shard count to use + */ + async updateShardCount(shardCount) { + await this.strategy.destroy({ reason: "User is adjusting their shards" }); + this.options.shardCount = shardCount; + const shardIds = await this.getShardIds(true); + await this.strategy.spawn(shardIds); + return this; + } + /** + * Yields the total number of shards across for your bot, accounting for Discord recommendations + */ + async getShardCount() { + if (this.options.shardCount) { + return this.options.shardCount; + } + const shardIds = await this.getShardIds(); + return Math.max(...shardIds) + 1; + } + /** + * Yields the ids of the shards this manager should manage + */ + async getShardIds(force = false) { + if (this.shardIds && !force) { + return this.shardIds; + } + let shardIds; + if (this.options.shardIds) { + if (Array.isArray(this.options.shardIds)) { + shardIds = this.options.shardIds; + } else { + const { start, end } = this.options.shardIds; + shardIds = [...range({ start, end: end + 1 })]; + } + } else { + const data = await this.fetchGatewayInformation(); + shardIds = [...range(this.options.shardCount ?? data.shards)]; + } + this.shardIds = shardIds; + return shardIds; + } + async connect() { + const shardCount = await this.getShardCount(); + const data = await this.fetchGatewayInformation(); + if (data.session_start_limit.remaining < shardCount) { + throw new Error( + `Not enough sessions remaining to spawn ${shardCount} shards; only ${data.session_start_limit.remaining} remaining; resets at ${new Date(Date.now() + data.session_start_limit.reset_after).toISOString()}` + ); + } + await this.updateShardCount(shardCount); + await this.strategy.connect(); + } + destroy(options) { + return this.strategy.destroy(options); + } + send(shardId, payload) { + return this.strategy.send(shardId, payload); + } + fetchStatus() { + return this.strategy.fetchStatus(); + } +}; +__name(WebSocketManager, "WebSocketManager"); + +// src/index.ts +var version = "0.8.3"; +export { + CloseCodes, + CompressionMethod, + DefaultDeviceProperty, + DefaultWebSocketManagerOptions, + Encoding, + ImportantGatewayOpcodes, + SimpleContextFetchingStrategy, + SimpleIdentifyThrottler, + SimpleShardingStrategy, + WebSocketManager, + WebSocketShard, + WebSocketShardDestroyRecovery, + WebSocketShardEvents, + WebSocketShardStatus, + WorkerBootstrapper, + WorkerContextFetchingStrategy, + WorkerReceivePayloadOp, + WorkerSendPayloadOp, + WorkerShardingStrategy, + getInitialSendRateLimitState, + managerToFetchingStrategyOptions, + version +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/ws/dist/index.mjs.map b/node_modules/@discordjs/ws/dist/index.mjs.map new file mode 100644 index 0000000..620d1dd --- /dev/null +++ b/node_modules/@discordjs/ws/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/tsup/assets/esm_shims.js","../src/strategies/context/IContextFetchingStrategy.ts","../src/strategies/context/SimpleContextFetchingStrategy.ts","../src/strategies/context/WorkerContextFetchingStrategy.ts","../src/strategies/sharding/WorkerShardingStrategy.ts","../src/strategies/sharding/SimpleShardingStrategy.ts","../src/ws/WebSocketShard.ts","../src/utils/constants.ts","../src/throttling/SimpleIdentifyThrottler.ts","../src/utils/WorkerBootstrapper.ts","../src/ws/WebSocketManager.ts","../src/index.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport { fileURLToPath } from 'url'\nimport path from 'path'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","import type { Awaitable } from '@discordjs/util';\nimport type { APIGatewayBotInfo } from 'discord-api-types/v10';\nimport type { SessionInfo, WebSocketManager, WebSocketManagerOptions } from '../../ws/WebSocketManager.js';\n\nexport interface FetchingStrategyOptions\n\textends Omit<\n\t\tWebSocketManagerOptions,\n\t\t| 'buildIdentifyThrottler'\n\t\t| 'buildStrategy'\n\t\t| 'rest'\n\t\t| 'retrieveSessionInfo'\n\t\t| 'shardCount'\n\t\t| 'shardIds'\n\t\t| 'updateSessionInfo'\n\t> {\n\treadonly gatewayInformation: APIGatewayBotInfo;\n\treadonly shardCount: number;\n}\n\n/**\n * Strategies responsible solely for making manager information accessible\n */\nexport interface IContextFetchingStrategy {\n\treadonly options: FetchingStrategyOptions;\n\tretrieveSessionInfo(shardId: number): Awaitable;\n\tupdateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable;\n\t/**\n\t * Resolves once the given shard should be allowed to identify, or rejects if the operation was aborted\n\t */\n\twaitForIdentify(shardId: number, signal: AbortSignal): Promise;\n}\n\nexport async function managerToFetchingStrategyOptions(manager: WebSocketManager): Promise {\n\t/* eslint-disable @typescript-eslint/unbound-method */\n\tconst {\n\t\tbuildIdentifyThrottler,\n\t\tbuildStrategy,\n\t\tretrieveSessionInfo,\n\t\tupdateSessionInfo,\n\t\tshardCount,\n\t\tshardIds,\n\t\trest,\n\t\t...managerOptions\n\t} = manager.options;\n\t/* eslint-enable @typescript-eslint/unbound-method */\n\n\treturn {\n\t\t...managerOptions,\n\t\tgatewayInformation: await manager.fetchGatewayInformation(),\n\t\tshardCount: await manager.getShardCount(),\n\t};\n}\n","import type { IIdentifyThrottler } from '../../throttling/IIdentifyThrottler.js';\nimport type { SessionInfo, WebSocketManager } from '../../ws/WebSocketManager.js';\nimport type { FetchingStrategyOptions, IContextFetchingStrategy } from './IContextFetchingStrategy.js';\n\nexport class SimpleContextFetchingStrategy implements IContextFetchingStrategy {\n\t// This strategy assumes every shard is running under the same process - therefore we need a single\n\t// IdentifyThrottler per manager.\n\tprivate static throttlerCache = new WeakMap();\n\n\tprivate static async ensureThrottler(manager: WebSocketManager): Promise {\n\t\tconst throttler = SimpleContextFetchingStrategy.throttlerCache.get(manager);\n\t\tif (throttler) {\n\t\t\treturn throttler;\n\t\t}\n\n\t\tconst newThrottler = await manager.options.buildIdentifyThrottler(manager);\n\t\tSimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler);\n\n\t\treturn newThrottler;\n\t}\n\n\tpublic constructor(private readonly manager: WebSocketManager, public readonly options: FetchingStrategyOptions) {}\n\n\tpublic async retrieveSessionInfo(shardId: number): Promise {\n\t\treturn this.manager.options.retrieveSessionInfo(shardId);\n\t}\n\n\tpublic updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null) {\n\t\treturn this.manager.options.updateSessionInfo(shardId, sessionInfo);\n\t}\n\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst throttler = await SimpleContextFetchingStrategy.ensureThrottler(this.manager);\n\t\tawait throttler.waitForIdentify(shardId, signal);\n\t}\n}\n","import { isMainThread, parentPort } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { SessionInfo } from '../../ws/WebSocketManager.js';\nimport {\n\tWorkerReceivePayloadOp,\n\tWorkerSendPayloadOp,\n\ttype WorkerReceivePayload,\n\ttype WorkerSendPayload,\n} from '../sharding/WorkerShardingStrategy.js';\nimport type { FetchingStrategyOptions, IContextFetchingStrategy } from './IContextFetchingStrategy.js';\n\n// Because the global types are incomplete for whatever reason\ninterface PolyFillAbortSignal {\n\treadonly aborted: boolean;\n\taddEventListener(type: 'abort', listener: () => void): void;\n\tremoveEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport class WorkerContextFetchingStrategy implements IContextFetchingStrategy {\n\tprivate readonly sessionPromises = new Collection void>();\n\n\tprivate readonly waitForIdentifyPromises = new Collection();\n\n\tpublic constructor(public readonly options: FetchingStrategyOptions) {\n\t\tif (isMainThread) {\n\t\t\tthrow new Error('Cannot instantiate WorkerContextFetchingStrategy on the main thread');\n\t\t}\n\n\t\tparentPort!.on('message', (payload: WorkerSendPayload) => {\n\t\t\tif (payload.op === WorkerSendPayloadOp.SessionInfoResponse) {\n\t\t\t\tthis.sessionPromises.get(payload.nonce)?.(payload.session);\n\t\t\t\tthis.sessionPromises.delete(payload.nonce);\n\t\t\t}\n\n\t\t\tif (payload.op === WorkerSendPayloadOp.ShardIdentifyResponse) {\n\t\t\t\tconst promise = this.waitForIdentifyPromises.get(payload.nonce);\n\t\t\t\tif (payload.ok) {\n\t\t\t\t\tpromise?.resolve();\n\t\t\t\t} else {\n\t\t\t\t\tpromise?.reject();\n\t\t\t\t}\n\n\t\t\t\tthis.waitForIdentifyPromises.delete(payload.nonce);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async retrieveSessionInfo(shardId: number): Promise {\n\t\tconst nonce = Math.random();\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.RetrieveSessionInfo,\n\t\t\tshardId,\n\t\t\tnonce,\n\t\t};\n\t\t// eslint-disable-next-line no-promise-executor-return\n\t\tconst promise = new Promise((resolve) => this.sessionPromises.set(nonce, resolve));\n\t\tparentPort!.postMessage(payload);\n\t\treturn promise;\n\t}\n\n\tpublic updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null) {\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.UpdateSessionInfo,\n\t\t\tshardId,\n\t\t\tsession: sessionInfo,\n\t\t};\n\t\tparentPort!.postMessage(payload);\n\t}\n\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst nonce = Math.random();\n\n\t\tconst payload: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.WaitForIdentify,\n\t\t\tnonce,\n\t\t\tshardId,\n\t\t};\n\t\tconst promise = new Promise((resolve, reject) =>\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tthis.waitForIdentifyPromises.set(nonce, { resolve, reject }),\n\t\t);\n\n\t\tparentPort!.postMessage(payload);\n\n\t\tconst listener = () => {\n\t\t\tconst payload: WorkerReceivePayload = {\n\t\t\t\top: WorkerReceivePayloadOp.CancelIdentify,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\tparentPort!.postMessage(payload);\n\t\t};\n\n\t\t(signal as unknown as PolyFillAbortSignal).addEventListener('abort', listener);\n\n\t\ttry {\n\t\t\tawait promise;\n\t\t} finally {\n\t\t\t(signal as unknown as PolyFillAbortSignal).removeEventListener('abort', listener);\n\t\t}\n\t}\n}\n","import { once } from 'node:events';\nimport { join, isAbsolute, resolve } from 'node:path';\nimport { Worker } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { GatewaySendPayload } from 'discord-api-types/v10';\nimport type { IIdentifyThrottler } from '../../throttling/IIdentifyThrottler.js';\nimport type { SessionInfo, WebSocketManager } from '../../ws/WebSocketManager.js';\nimport type {\n\tWebSocketShardDestroyOptions,\n\tWebSocketShardEvents,\n\tWebSocketShardStatus,\n} from '../../ws/WebSocketShard.js';\nimport { managerToFetchingStrategyOptions, type FetchingStrategyOptions } from '../context/IContextFetchingStrategy.js';\nimport type { IShardingStrategy } from './IShardingStrategy.js';\n\nexport interface WorkerData extends FetchingStrategyOptions {\n\tshardIds: number[];\n}\n\nexport enum WorkerSendPayloadOp {\n\tConnect,\n\tDestroy,\n\tSend,\n\tSessionInfoResponse,\n\tShardIdentifyResponse,\n\tFetchStatus,\n}\n\nexport type WorkerSendPayload =\n\t| { nonce: number; ok: boolean; op: WorkerSendPayloadOp.ShardIdentifyResponse }\n\t| { nonce: number; op: WorkerSendPayloadOp.FetchStatus; shardId: number }\n\t| { nonce: number; op: WorkerSendPayloadOp.SessionInfoResponse; session: SessionInfo | null }\n\t| { op: WorkerSendPayloadOp.Connect; shardId: number }\n\t| { op: WorkerSendPayloadOp.Destroy; options?: WebSocketShardDestroyOptions; shardId: number }\n\t| { op: WorkerSendPayloadOp.Send; payload: GatewaySendPayload; shardId: number };\n\nexport enum WorkerReceivePayloadOp {\n\tConnected,\n\tDestroyed,\n\tEvent,\n\tRetrieveSessionInfo,\n\tUpdateSessionInfo,\n\tWaitForIdentify,\n\tFetchStatusResponse,\n\tWorkerReady,\n\tCancelIdentify,\n}\n\nexport type WorkerReceivePayload =\n\t// Can't seem to get a type-safe union based off of the event, so I'm sadly leaving data as any for now\n\t| { data: any; event: WebSocketShardEvents; op: WorkerReceivePayloadOp.Event; shardId: number }\n\t| { nonce: number; op: WorkerReceivePayloadOp.CancelIdentify }\n\t| { nonce: number; op: WorkerReceivePayloadOp.FetchStatusResponse; status: WebSocketShardStatus }\n\t| { nonce: number; op: WorkerReceivePayloadOp.RetrieveSessionInfo; shardId: number }\n\t| { nonce: number; op: WorkerReceivePayloadOp.WaitForIdentify; shardId: number }\n\t| { op: WorkerReceivePayloadOp.Connected; shardId: number }\n\t| { op: WorkerReceivePayloadOp.Destroyed; shardId: number }\n\t| { op: WorkerReceivePayloadOp.UpdateSessionInfo; session: SessionInfo | null; shardId: number }\n\t| { op: WorkerReceivePayloadOp.WorkerReady };\n\n/**\n * Options for a {@link WorkerShardingStrategy}\n */\nexport interface WorkerShardingStrategyOptions {\n\t/**\n\t * Dictates how many shards should be spawned per worker thread.\n\t */\n\tshardsPerWorker: number | 'all';\n\t/**\n\t * Path to the worker file to use. The worker requires quite a bit of setup, it is recommended you leverage the {@link WorkerBootstrapper} class.\n\t */\n\tworkerPath?: string;\n}\n\n/**\n * Strategy used to spawn threads in worker_threads\n */\nexport class WorkerShardingStrategy implements IShardingStrategy {\n\tprivate readonly manager: WebSocketManager;\n\n\tprivate readonly options: WorkerShardingStrategyOptions;\n\n\t#workers: Worker[] = [];\n\n\treadonly #workerByShardId = new Collection();\n\n\tprivate readonly connectPromises = new Collection void>();\n\n\tprivate readonly destroyPromises = new Collection void>();\n\n\tprivate readonly fetchStatusPromises = new Collection void>();\n\n\tprivate readonly waitForIdentifyControllers = new Collection();\n\n\tprivate throttler?: IIdentifyThrottler;\n\n\tpublic constructor(manager: WebSocketManager, options: WorkerShardingStrategyOptions) {\n\t\tthis.manager = manager;\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.spawn}\n\t */\n\tpublic async spawn(shardIds: number[]) {\n\t\tconst shardsPerWorker = this.options.shardsPerWorker === 'all' ? shardIds.length : this.options.shardsPerWorker;\n\t\tconst strategyOptions = await managerToFetchingStrategyOptions(this.manager);\n\n\t\tconst loops = Math.ceil(shardIds.length / shardsPerWorker);\n\t\tconst promises: Promise[] = [];\n\n\t\tfor (let idx = 0; idx < loops; idx++) {\n\t\t\tconst slice = shardIds.slice(idx * shardsPerWorker, (idx + 1) * shardsPerWorker);\n\t\t\tconst workerData: WorkerData = {\n\t\t\t\t...strategyOptions,\n\t\t\t\tshardIds: slice,\n\t\t\t};\n\n\t\t\tpromises.push(this.setupWorker(workerData));\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.connect}\n\t */\n\tpublic async connect() {\n\t\tconst promises = [];\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.Connect,\n\t\t\t\tshardId,\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tconst promise = new Promise((resolve) => this.connectPromises.set(shardId, resolve));\n\t\t\tworker.postMessage(payload);\n\t\t\tpromises.push(promise);\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.destroy}\n\t */\n\tpublic async destroy(options: Omit = {}) {\n\t\tconst promises = [];\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.Destroy,\n\t\t\t\tshardId,\n\t\t\t\toptions,\n\t\t\t};\n\n\t\t\tpromises.push(\n\t\t\t\t// eslint-disable-next-line no-promise-executor-return, promise/prefer-await-to-then\n\t\t\t\tnew Promise((resolve) => this.destroyPromises.set(shardId, resolve)).then(async () => worker.terminate()),\n\t\t\t);\n\t\t\tworker.postMessage(payload);\n\t\t}\n\n\t\tthis.#workers = [];\n\t\tthis.#workerByShardId.clear();\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.send}\n\t */\n\tpublic send(shardId: number, data: GatewaySendPayload) {\n\t\tconst worker = this.#workerByShardId.get(shardId);\n\t\tif (!worker) {\n\t\t\tthrow new Error(`No worker found for shard ${shardId}`);\n\t\t}\n\n\t\tconst payload: WorkerSendPayload = {\n\t\t\top: WorkerSendPayloadOp.Send,\n\t\t\tshardId,\n\t\t\tpayload: data,\n\t\t};\n\t\tworker.postMessage(payload);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.fetchStatus}\n\t */\n\tpublic async fetchStatus() {\n\t\tconst statuses = new Collection();\n\n\t\tfor (const [shardId, worker] of this.#workerByShardId.entries()) {\n\t\t\tconst nonce = Math.random();\n\t\t\tconst payload: WorkerSendPayload = {\n\t\t\t\top: WorkerSendPayloadOp.FetchStatus,\n\t\t\t\tshardId,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line no-promise-executor-return\n\t\t\tconst promise = new Promise((resolve) => this.fetchStatusPromises.set(nonce, resolve));\n\t\t\tworker.postMessage(payload);\n\n\t\t\tconst status = await promise;\n\t\t\tstatuses.set(shardId, status);\n\t\t}\n\n\t\treturn statuses;\n\t}\n\n\tprivate async setupWorker(workerData: WorkerData) {\n\t\tconst worker = new Worker(this.resolveWorkerPath(), { workerData });\n\n\t\tawait once(worker, 'online');\n\t\t// We do this in case the user has any potentially long running code in their worker\n\t\tawait this.waitForWorkerReady(worker);\n\n\t\tworker\n\t\t\t.on('error', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('messageerror', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('message', async (payload: WorkerReceivePayload) => this.onMessage(worker, payload));\n\n\t\tthis.#workers.push(worker);\n\t\tfor (const shardId of workerData.shardIds) {\n\t\t\tthis.#workerByShardId.set(shardId, worker);\n\t\t}\n\t}\n\n\tprivate resolveWorkerPath(): string {\n\t\tconst path = this.options.workerPath;\n\n\t\tif (!path) {\n\t\t\treturn join(__dirname, 'defaultWorker.js');\n\t\t}\n\n\t\tif (isAbsolute(path)) {\n\t\t\treturn path;\n\t\t}\n\n\t\tif (/^\\.\\.?[/\\\\]/.test(path)) {\n\t\t\treturn resolve(path);\n\t\t}\n\n\t\ttry {\n\t\t\treturn require.resolve(path);\n\t\t} catch {\n\t\t\treturn resolve(path);\n\t\t}\n\t}\n\n\tprivate async waitForWorkerReady(worker: Worker): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst handler = (payload: WorkerReceivePayload) => {\n\t\t\t\tif (payload.op === WorkerReceivePayloadOp.WorkerReady) {\n\t\t\t\t\tresolve();\n\t\t\t\t\tworker.off('message', handler);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tworker.on('message', handler);\n\t\t});\n\t}\n\n\tprivate async onMessage(worker: Worker, payload: WorkerReceivePayload) {\n\t\tswitch (payload.op) {\n\t\t\tcase WorkerReceivePayloadOp.Connected: {\n\t\t\t\tthis.connectPromises.get(payload.shardId)?.();\n\t\t\t\tthis.connectPromises.delete(payload.shardId);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.Destroyed: {\n\t\t\t\tthis.destroyPromises.get(payload.shardId)?.();\n\t\t\t\tthis.destroyPromises.delete(payload.shardId);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.Event: {\n\t\t\t\tthis.manager.emit(payload.event, { ...payload.data, shardId: payload.shardId });\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.RetrieveSessionInfo: {\n\t\t\t\tconst session = await this.manager.options.retrieveSessionInfo(payload.shardId);\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.SessionInfoResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tsession,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.UpdateSessionInfo: {\n\t\t\t\tawait this.manager.options.updateSessionInfo(payload.shardId, payload.session);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.WaitForIdentify: {\n\t\t\t\tconst throttler = await this.ensureThrottler();\n\n\t\t\t\t// If this rejects it means we aborted, in which case we reply elsewhere.\n\t\t\t\ttry {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\tthis.waitForIdentifyControllers.set(payload.nonce, controller);\n\t\t\t\t\tawait throttler.waitForIdentify(payload.shardId, controller.signal);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.ShardIdentifyResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tok: true,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.FetchStatusResponse: {\n\t\t\t\tthis.fetchStatusPromises.get(payload.nonce)?.(payload.status);\n\t\t\t\tthis.fetchStatusPromises.delete(payload.nonce);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.WorkerReady: {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase WorkerReceivePayloadOp.CancelIdentify: {\n\t\t\t\tthis.waitForIdentifyControllers.get(payload.nonce)?.abort();\n\t\t\t\tthis.waitForIdentifyControllers.delete(payload.nonce);\n\n\t\t\t\tconst response: WorkerSendPayload = {\n\t\t\t\t\top: WorkerSendPayloadOp.ShardIdentifyResponse,\n\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\tok: false,\n\t\t\t\t};\n\t\t\t\tworker.postMessage(response);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async ensureThrottler(): Promise {\n\t\tthis.throttler ??= await this.manager.options.buildIdentifyThrottler(this.manager);\n\t\treturn this.throttler;\n\t}\n}\n","import { Collection } from '@discordjs/collection';\nimport type { GatewaySendPayload } from 'discord-api-types/v10';\nimport type { WebSocketManager } from '../../ws/WebSocketManager.js';\nimport { WebSocketShard, WebSocketShardEvents, type WebSocketShardDestroyOptions } from '../../ws/WebSocketShard.js';\nimport { managerToFetchingStrategyOptions } from '../context/IContextFetchingStrategy.js';\nimport { SimpleContextFetchingStrategy } from '../context/SimpleContextFetchingStrategy.js';\nimport type { IShardingStrategy } from './IShardingStrategy.js';\n\n/**\n * Simple strategy that just spawns shards in the current process\n */\nexport class SimpleShardingStrategy implements IShardingStrategy {\n\tprivate readonly manager: WebSocketManager;\n\n\tprivate readonly shards = new Collection();\n\n\tpublic constructor(manager: WebSocketManager) {\n\t\tthis.manager = manager;\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.spawn}\n\t */\n\tpublic async spawn(shardIds: number[]) {\n\t\tconst strategyOptions = await managerToFetchingStrategyOptions(this.manager);\n\n\t\tfor (const shardId of shardIds) {\n\t\t\tconst strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions);\n\t\t\tconst shard = new WebSocketShard(strategy, shardId);\n\t\t\tfor (const event of Object.values(WebSocketShardEvents)) {\n\t\t\t\t// @ts-expect-error: Intentional\n\t\t\t\tshard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId }));\n\t\t\t}\n\n\t\t\tthis.shards.set(shardId, shard);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.connect}\n\t */\n\tpublic async connect() {\n\t\tconst promises = [];\n\n\t\tfor (const shard of this.shards.values()) {\n\t\t\tpromises.push(shard.connect());\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.destroy}\n\t */\n\tpublic async destroy(options?: Omit) {\n\t\tconst promises = [];\n\n\t\tfor (const shard of this.shards.values()) {\n\t\t\tpromises.push(shard.destroy(options));\n\t\t}\n\n\t\tawait Promise.all(promises);\n\t\tthis.shards.clear();\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.send}\n\t */\n\tpublic async send(shardId: number, payload: GatewaySendPayload) {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} not found`);\n\t\t}\n\n\t\treturn shard.send(payload);\n\t}\n\n\t/**\n\t * {@inheritDoc IShardingStrategy.fetchStatus}\n\t */\n\tpublic async fetchStatus() {\n\t\treturn this.shards.mapValues((shard) => shard.status);\n\t}\n}\n","/* eslint-disable id-length */\nimport { Buffer } from 'node:buffer';\nimport { once } from 'node:events';\nimport { clearInterval, clearTimeout, setInterval, setTimeout } from 'node:timers';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { URLSearchParams } from 'node:url';\nimport { TextDecoder } from 'node:util';\nimport { inflate } from 'node:zlib';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\nimport {\n\tGatewayCloseCodes,\n\tGatewayDispatchEvents,\n\tGatewayOpcodes,\n\ttype GatewayDispatchPayload,\n\ttype GatewayIdentifyData,\n\ttype GatewayReadyDispatchData,\n\ttype GatewayReceivePayload,\n\ttype GatewaySendPayload,\n} from 'discord-api-types/v10';\nimport { WebSocket, type RawData } from 'ws';\nimport type { Inflate } from 'zlib-sync';\nimport type { IContextFetchingStrategy } from '../strategies/context/IContextFetchingStrategy.js';\nimport { ImportantGatewayOpcodes, getInitialSendRateLimitState } from '../utils/constants.js';\nimport type { SessionInfo } from './WebSocketManager.js';\n\n// eslint-disable-next-line promise/prefer-await-to-then\nconst getZlibSync = lazy(async () => import('zlib-sync').then((mod) => mod.default).catch(() => null));\n\nexport enum WebSocketShardEvents {\n\tClosed = 'closed',\n\tDebug = 'debug',\n\tDispatch = 'dispatch',\n\tError = 'error',\n\tHeartbeatComplete = 'heartbeat',\n\tHello = 'hello',\n\tReady = 'ready',\n\tResumed = 'resumed',\n}\n\nexport enum WebSocketShardStatus {\n\tIdle,\n\tConnecting,\n\tResuming,\n\tReady,\n}\n\nexport enum WebSocketShardDestroyRecovery {\n\tReconnect,\n\tResume,\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport type WebSocketShardEventsMap = {\n\t[WebSocketShardEvents.Closed]: [{ code: number }];\n\t[WebSocketShardEvents.Debug]: [payload: { message: string }];\n\t[WebSocketShardEvents.Dispatch]: [payload: { data: GatewayDispatchPayload }];\n\t[WebSocketShardEvents.Error]: [payload: { error: Error }];\n\t[WebSocketShardEvents.Hello]: [];\n\t[WebSocketShardEvents.Ready]: [payload: { data: GatewayReadyDispatchData }];\n\t[WebSocketShardEvents.Resumed]: [];\n\t[WebSocketShardEvents.HeartbeatComplete]: [payload: { ackAt: number; heartbeatAt: number; latency: number }];\n};\n\nexport interface WebSocketShardDestroyOptions {\n\tcode?: number;\n\treason?: string;\n\trecover?: WebSocketShardDestroyRecovery;\n}\n\nexport enum CloseCodes {\n\tNormal = 1_000,\n\tResuming = 4_200,\n}\n\nexport interface SendRateLimitState {\n\tremaining: number;\n\tresetAt: number;\n}\n\nexport class WebSocketShard extends AsyncEventEmitter {\n\tprivate connection: WebSocket | null = null;\n\n\tprivate useIdentifyCompress = false;\n\n\tprivate inflate: Inflate | null = null;\n\n\tprivate readonly textDecoder = new TextDecoder();\n\n\tprivate replayedEvents = 0;\n\n\tprivate isAck = true;\n\n\tprivate sendRateLimitState: SendRateLimitState = getInitialSendRateLimitState();\n\n\tprivate initialHeartbeatTimeoutController: AbortController | null = null;\n\n\tprivate heartbeatInterval: NodeJS.Timer | null = null;\n\n\tprivate lastHeartbeatAt = -1;\n\n\t// Indicates whether the shard has already resolved its original connect() call\n\tprivate initialConnectResolved = false;\n\n\t// Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET)\n\tprivate failedToConnectDueToNetworkError = false;\n\n\tprivate readonly sendQueue = new AsyncQueue();\n\n\tprivate readonly timeoutAbortControllers = new Collection();\n\n\tprivate readonly strategy: IContextFetchingStrategy;\n\n\tpublic readonly id: number;\n\n\t#status: WebSocketShardStatus = WebSocketShardStatus.Idle;\n\n\tpublic get status(): WebSocketShardStatus {\n\t\treturn this.#status;\n\t}\n\n\tpublic constructor(strategy: IContextFetchingStrategy, id: number) {\n\t\tsuper();\n\t\tthis.strategy = strategy;\n\t\tthis.id = id;\n\t}\n\n\tpublic async connect() {\n\t\tconst promise = this.initialConnectResolved ? Promise.resolve() : once(this, WebSocketShardEvents.Ready);\n\t\tvoid this.internalConnect();\n\n\t\tawait promise;\n\t\tthis.initialConnectResolved = true;\n\t}\n\n\tprivate async internalConnect() {\n\t\tif (this.#status !== WebSocketShardStatus.Idle) {\n\t\t\tthrow new Error(\"Tried to connect a shard that wasn't idle\");\n\t\t}\n\n\t\tconst { version, encoding, compression } = this.strategy.options;\n\t\tconst params = new URLSearchParams({ v: version, encoding });\n\t\tif (compression) {\n\t\t\tconst zlib = await getZlibSync();\n\t\t\tif (zlib) {\n\t\t\t\tparams.append('compress', compression);\n\t\t\t\tthis.inflate = new zlib.Inflate({\n\t\t\t\t\tchunkSize: 65_535,\n\t\t\t\t\tto: 'string',\n\t\t\t\t});\n\t\t\t} else if (!this.useIdentifyCompress) {\n\t\t\t\tthis.useIdentifyCompress = true;\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\n\t\tconst url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`;\n\t\tthis.debug([`Connecting to ${url}`]);\n\t\tconst connection = new WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? undefined })\n\t\t\t.on('message', this.onMessage.bind(this))\n\t\t\t.on('error', this.onError.bind(this))\n\t\t\t.on('close', this.onClose.bind(this));\n\n\t\tconnection.binaryType = 'arraybuffer';\n\t\tthis.connection = connection;\n\n\t\tthis.#status = WebSocketShardStatus.Connecting;\n\n\t\tthis.sendRateLimitState = getInitialSendRateLimitState();\n\n\t\tconst { ok } = await this.waitForEvent(WebSocketShardEvents.Hello, this.strategy.options.helloTimeout);\n\t\tif (!ok) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (session?.shardCount === this.strategy.options.shardCount) {\n\t\t\tawait this.resume(session);\n\t\t} else {\n\t\t\tawait this.identify();\n\t\t}\n\t}\n\n\tpublic async destroy(options: WebSocketShardDestroyOptions = {}) {\n\t\tif (this.#status === WebSocketShardStatus.Idle) {\n\t\t\tthis.debug(['Tried to destroy a shard that was idle']);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!options.code) {\n\t\t\toptions.code = options.recover === WebSocketShardDestroyRecovery.Resume ? CloseCodes.Resuming : CloseCodes.Normal;\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Destroying shard',\n\t\t\t`Reason: ${options.reason ?? 'none'}`,\n\t\t\t`Code: ${options.code}`,\n\t\t\t`Recover: ${options.recover === undefined ? 'none' : WebSocketShardDestroyRecovery[options.recover]!}`,\n\t\t]);\n\n\t\t// Reset state\n\t\tthis.isAck = true;\n\t\tif (this.heartbeatInterval) {\n\t\t\tclearInterval(this.heartbeatInterval);\n\t\t}\n\n\t\tif (this.initialHeartbeatTimeoutController) {\n\t\t\tthis.initialHeartbeatTimeoutController.abort();\n\t\t\tthis.initialHeartbeatTimeoutController = null;\n\t\t}\n\n\t\tthis.lastHeartbeatAt = -1;\n\n\t\tfor (const controller of this.timeoutAbortControllers.values()) {\n\t\t\tcontroller.abort();\n\t\t}\n\n\t\tthis.timeoutAbortControllers.clear();\n\n\t\tthis.failedToConnectDueToNetworkError = false;\n\n\t\t// Clear session state if applicable\n\t\tif (options.recover !== WebSocketShardDestroyRecovery.Resume) {\n\t\t\tawait this.strategy.updateSessionInfo(this.id, null);\n\t\t}\n\n\t\tif (this.connection) {\n\t\t\t// No longer need to listen to messages\n\t\t\tthis.connection.removeAllListeners('message');\n\t\t\t// Prevent a reconnection loop by unbinding the main close event\n\t\t\tthis.connection.removeAllListeners('close');\n\n\t\t\tconst shouldClose = this.connection.readyState === WebSocket.OPEN;\n\n\t\t\tthis.debug([\n\t\t\t\t'Connection status during destroy',\n\t\t\t\t`Needs closing: ${shouldClose}`,\n\t\t\t\t`Ready state: ${this.connection.readyState}`,\n\t\t\t]);\n\n\t\t\tif (shouldClose) {\n\t\t\t\tthis.connection.close(options.code, options.reason);\n\t\t\t\tawait once(this.connection, 'close');\n\t\t\t\tthis.emit(WebSocketShardEvents.Closed, { code: options.code });\n\t\t\t}\n\n\t\t\t// Lastly, remove the error event.\n\t\t\t// Doing this earlier would cause a hard crash in case an error event fired on our `close` call\n\t\t\tthis.connection.removeAllListeners('error');\n\t\t} else {\n\t\t\tthis.debug(['Destroying a shard that has no connection; please open an issue on GitHub']);\n\t\t}\n\n\t\tthis.#status = WebSocketShardStatus.Idle;\n\n\t\tif (options.recover !== undefined) {\n\t\t\t// There's cases (like no internet connection) where we immediately fail to connect,\n\t\t\t// causing a very fast and draining reconnection loop.\n\t\t\tawait sleep(500);\n\t\t\treturn this.internalConnect();\n\t\t}\n\t}\n\n\tprivate async waitForEvent(event: WebSocketShardEvents, timeoutDuration?: number | null): Promise<{ ok: boolean }> {\n\t\tthis.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : 'indefinitely'}`]);\n\t\tconst timeoutController = new AbortController();\n\t\tconst timeout = timeoutDuration ? setTimeout(() => timeoutController.abort(), timeoutDuration).unref() : null;\n\n\t\tthis.timeoutAbortControllers.set(event, timeoutController);\n\n\t\tconst closeController = new AbortController();\n\n\t\ttry {\n\t\t\t// If the first promise resolves, all is well. If the 2nd promise resolves,\n\t\t\t// the shard has meanwhile closed. In that case, a destroy is already ongoing, so we just need to\n\t\t\t// return false. Meanwhile, if something rejects (error event) or the first controller is aborted,\n\t\t\t// we enter the catch block and trigger a destroy there.\n\t\t\tconst closed = await Promise.race([\n\t\t\t\tonce(this, event, { signal: timeoutController.signal }).then(() => false),\n\t\t\t\tonce(this, WebSocketShardEvents.Closed, { signal: closeController.signal }).then(() => true),\n\t\t\t]);\n\n\t\t\treturn { ok: !closed };\n\t\t} catch {\n\t\t\t// If we're here because of other reasons, we need to destroy the shard\n\t\t\tvoid this.destroy({\n\t\t\t\tcode: CloseCodes.Normal,\n\t\t\t\treason: 'Something timed out or went wrong while waiting for an event',\n\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t});\n\n\t\t\treturn { ok: false };\n\t\t} finally {\n\t\t\tif (timeout) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t}\n\n\t\t\tthis.timeoutAbortControllers.delete(event);\n\n\t\t\t// Clean up the close listener to not leak memory\n\t\t\tif (!closeController.signal.aborted) {\n\t\t\t\tcloseController.abort();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async send(payload: GatewaySendPayload): Promise {\n\t\tif (!this.connection) {\n\t\t\tthrow new Error(\"WebSocketShard wasn't connected\");\n\t\t}\n\n\t\tif (this.#status !== WebSocketShardStatus.Ready && !ImportantGatewayOpcodes.has(payload.op)) {\n\t\t\tthis.debug(['Tried to send a non-crucial payload before the shard was ready, waiting']);\n\t\t\t// This will throw if the shard throws an error event in the meantime, just requeue the payload\n\t\t\ttry {\n\t\t\t\tawait once(this, WebSocketShardEvents.Ready);\n\t\t\t} catch {\n\t\t\t\treturn this.send(payload);\n\t\t\t}\n\t\t}\n\n\t\tawait this.sendQueue.wait();\n\n\t\tif (--this.sendRateLimitState.remaining <= 0) {\n\t\t\tconst now = Date.now();\n\n\t\t\tif (this.sendRateLimitState.resetAt > now) {\n\t\t\t\tconst sleepFor = this.sendRateLimitState.resetAt - now;\n\n\t\t\t\tthis.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]);\n\t\t\t\tconst controller = new AbortController();\n\n\t\t\t\t// Sleep for the remaining time, but if the connection closes in the meantime, we shouldn't wait the remainder to avoid blocking the new conn\n\t\t\t\tconst interrupted = await Promise.race([\n\t\t\t\t\tsleep(sleepFor).then(() => false),\n\t\t\t\t\tonce(this, WebSocketShardEvents.Closed, { signal: controller.signal }).then(() => true),\n\t\t\t\t]);\n\n\t\t\t\tif (interrupted) {\n\t\t\t\t\tthis.debug(['Connection closed while waiting for the send rate limit to reset, re-queueing payload']);\n\t\t\t\t\tthis.sendQueue.shift();\n\t\t\t\t\treturn this.send(payload);\n\t\t\t\t}\n\n\t\t\t\t// This is so the listener from the `once` call is removed\n\t\t\t\tcontroller.abort();\n\t\t\t}\n\n\t\t\tthis.sendRateLimitState = getInitialSendRateLimitState();\n\t\t}\n\n\t\tthis.sendQueue.shift();\n\t\tthis.connection.send(JSON.stringify(payload));\n\t}\n\n\tprivate async identify() {\n\t\tthis.debug(['Waiting for identify throttle']);\n\n\t\tconst controller = new AbortController();\n\t\tconst closeHandler = () => {\n\t\t\tcontroller.abort();\n\t\t};\n\n\t\tthis.on(WebSocketShardEvents.Closed, closeHandler);\n\n\t\ttry {\n\t\t\tawait this.strategy.waitForIdentify(this.id, controller.signal);\n\t\t} catch {\n\t\t\tthis.debug(['Was waiting for an identify, but the shard closed in the meantime']);\n\t\t\treturn;\n\t\t} finally {\n\t\t\tthis.off(WebSocketShardEvents.Closed, closeHandler);\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Identifying',\n\t\t\t`shard id: ${this.id.toString()}`,\n\t\t\t`shard count: ${this.strategy.options.shardCount}`,\n\t\t\t`intents: ${this.strategy.options.intents}`,\n\t\t\t`compression: ${this.inflate ? 'zlib-stream' : this.useIdentifyCompress ? 'identify' : 'none'}`,\n\t\t]);\n\n\t\tconst d: GatewayIdentifyData = {\n\t\t\ttoken: this.strategy.options.token,\n\t\t\tproperties: this.strategy.options.identifyProperties,\n\t\t\tintents: this.strategy.options.intents,\n\t\t\tcompress: this.useIdentifyCompress,\n\t\t\tshard: [this.id, this.strategy.options.shardCount],\n\t\t};\n\n\t\tif (this.strategy.options.largeThreshold) {\n\t\t\td.large_threshold = this.strategy.options.largeThreshold;\n\t\t}\n\n\t\tif (this.strategy.options.initialPresence) {\n\t\t\td.presence = this.strategy.options.initialPresence;\n\t\t}\n\n\t\tawait this.send({\n\t\t\top: GatewayOpcodes.Identify,\n\t\t\td,\n\t\t});\n\n\t\tawait this.waitForEvent(WebSocketShardEvents.Ready, this.strategy.options.readyTimeout);\n\t}\n\n\tprivate async resume(session: SessionInfo) {\n\t\tthis.debug([\n\t\t\t'Resuming session',\n\t\t\t`resume url: ${session.resumeURL}`,\n\t\t\t`sequence: ${session.sequence}`,\n\t\t\t`shard id: ${this.id.toString()}`,\n\t\t]);\n\n\t\tthis.#status = WebSocketShardStatus.Resuming;\n\t\tthis.replayedEvents = 0;\n\t\treturn this.send({\n\t\t\top: GatewayOpcodes.Resume,\n\t\t\td: {\n\t\t\t\ttoken: this.strategy.options.token,\n\t\t\t\tseq: session.sequence,\n\t\t\t\tsession_id: session.sessionId,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async heartbeat(requested = false) {\n\t\tif (!this.isAck && !requested) {\n\t\t\treturn this.destroy({ reason: 'Zombie connection', recover: WebSocketShardDestroyRecovery.Resume });\n\t\t}\n\n\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\n\t\tawait this.send({\n\t\t\top: GatewayOpcodes.Heartbeat,\n\t\t\td: session?.sequence ?? null,\n\t\t});\n\n\t\tthis.lastHeartbeatAt = Date.now();\n\t\tthis.isAck = false;\n\t}\n\n\tprivate async unpackMessage(data: ArrayBuffer | Buffer, isBinary: boolean): Promise {\n\t\tconst decompressable = new Uint8Array(data);\n\n\t\t// Deal with no compression\n\t\tif (!isBinary) {\n\t\t\treturn JSON.parse(this.textDecoder.decode(decompressable)) as GatewayReceivePayload;\n\t\t}\n\n\t\t// Deal with identify compress\n\t\tif (this.useIdentifyCompress) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tinflate(decompressable, { chunkSize: 65_535 }, (err, result) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(JSON.parse(this.textDecoder.decode(result)) as GatewayReceivePayload);\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\t// Deal with gw wide zlib-stream compression\n\t\tif (this.inflate) {\n\t\t\tconst l = decompressable.length;\n\t\t\tconst flush =\n\t\t\t\tl >= 4 &&\n\t\t\t\tdecompressable[l - 4] === 0x00 &&\n\t\t\t\tdecompressable[l - 3] === 0x00 &&\n\t\t\t\tdecompressable[l - 2] === 0xff &&\n\t\t\t\tdecompressable[l - 1] === 0xff;\n\n\t\t\tconst zlib = (await getZlibSync())!;\n\t\t\tthis.inflate.push(Buffer.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH);\n\n\t\t\tif (this.inflate.err) {\n\t\t\t\tthis.emit(WebSocketShardEvents.Error, {\n\t\t\t\t\terror: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ''}`),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!flush) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst { result } = this.inflate;\n\t\t\tif (!result) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn JSON.parse(typeof result === 'string' ? result : this.textDecoder.decode(result)) as GatewayReceivePayload;\n\t\t}\n\n\t\tthis.debug([\n\t\t\t'Received a message we were unable to decompress',\n\t\t\t`isBinary: ${isBinary.toString()}`,\n\t\t\t`useIdentifyCompress: ${this.useIdentifyCompress.toString()}`,\n\t\t\t`inflate: ${Boolean(this.inflate).toString()}`,\n\t\t]);\n\n\t\treturn null;\n\t}\n\n\tprivate async onMessage(data: RawData, isBinary: boolean) {\n\t\tconst payload = await this.unpackMessage(data as ArrayBuffer | Buffer, isBinary);\n\t\tif (!payload) {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (payload.op) {\n\t\t\tcase GatewayOpcodes.Dispatch: {\n\t\t\t\tif (this.#status === WebSocketShardStatus.Resuming) {\n\t\t\t\t\tthis.replayedEvents++;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line sonarjs/no-nested-switch\n\t\t\t\tswitch (payload.t) {\n\t\t\t\t\tcase GatewayDispatchEvents.Ready: {\n\t\t\t\t\t\tthis.#status = WebSocketShardStatus.Ready;\n\n\t\t\t\t\t\tconst session = {\n\t\t\t\t\t\t\tsequence: payload.s,\n\t\t\t\t\t\t\tsessionId: payload.d.session_id,\n\t\t\t\t\t\t\tshardId: this.id,\n\t\t\t\t\t\t\tshardCount: this.strategy.options.shardCount,\n\t\t\t\t\t\t\tresumeURL: payload.d.resume_gateway_url,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tawait this.strategy.updateSessionInfo(this.id, session);\n\n\t\t\t\t\t\tthis.emit(WebSocketShardEvents.Ready, { data: payload.d });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase GatewayDispatchEvents.Resumed: {\n\t\t\t\t\t\tthis.#status = WebSocketShardStatus.Ready;\n\t\t\t\t\t\tthis.debug([`Resumed and replayed ${this.replayedEvents} events`]);\n\t\t\t\t\t\tthis.emit(WebSocketShardEvents.Resumed);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\t\t\t\tif (session) {\n\t\t\t\t\tif (payload.s > session.sequence) {\n\t\t\t\t\t\tawait this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s });\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.debug([\n\t\t\t\t\t\t`Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect`,\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tthis.emit(WebSocketShardEvents.Dispatch, { data: payload });\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Heartbeat: {\n\t\t\t\tawait this.heartbeat(true);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Reconnect: {\n\t\t\t\tawait this.destroy({\n\t\t\t\t\treason: 'Told to reconnect by Discord',\n\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Resume,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.InvalidSession: {\n\t\t\t\tthis.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]);\n\t\t\t\tconst session = await this.strategy.retrieveSessionInfo(this.id);\n\t\t\t\tif (payload.d && session) {\n\t\t\t\t\tawait this.resume(session);\n\t\t\t\t} else {\n\t\t\t\t\tawait this.destroy({\n\t\t\t\t\t\treason: 'Invalid session',\n\t\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.Hello: {\n\t\t\t\tthis.emit(WebSocketShardEvents.Hello);\n\t\t\t\tconst jitter = Math.random();\n\t\t\t\tconst firstWait = Math.floor(payload.d.heartbeat_interval * jitter);\n\t\t\t\tthis.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\tthis.initialHeartbeatTimeoutController = controller;\n\t\t\t\t\tawait sleep(firstWait, undefined, { signal: controller.signal });\n\t\t\t\t} catch {\n\t\t\t\t\tthis.debug(['Cancelled initial heartbeat due to #destroy being called']);\n\t\t\t\t\treturn;\n\t\t\t\t} finally {\n\t\t\t\t\tthis.initialHeartbeatTimeoutController = null;\n\t\t\t\t}\n\n\t\t\t\tawait this.heartbeat();\n\n\t\t\t\tthis.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]);\n\t\t\t\tthis.heartbeatInterval = setInterval(() => void this.heartbeat(), payload.d.heartbeat_interval);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayOpcodes.HeartbeatAck: {\n\t\t\t\tthis.isAck = true;\n\n\t\t\t\tconst ackAt = Date.now();\n\t\t\t\tthis.emit(WebSocketShardEvents.HeartbeatComplete, {\n\t\t\t\t\tackAt,\n\t\t\t\t\theartbeatAt: this.lastHeartbeatAt,\n\t\t\t\t\tlatency: ackAt - this.lastHeartbeatAt,\n\t\t\t\t});\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate onError(error: Error) {\n\t\tif ('code' in error && ['ECONNRESET', 'ECONNREFUSED'].includes(error.code as string)) {\n\t\t\tthis.debug(['Failed to connect to the gateway URL specified due to a network error']);\n\t\t\tthis.failedToConnectDueToNetworkError = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.emit(WebSocketShardEvents.Error, { error });\n\t}\n\n\tprivate async onClose(code: number) {\n\t\tthis.emit(WebSocketShardEvents.Closed, { code });\n\n\t\tswitch (code) {\n\t\t\tcase CloseCodes.Normal: {\n\t\t\t\treturn this.destroy({\n\t\t\t\t\tcode,\n\t\t\t\t\treason: 'Got disconnected by Discord',\n\t\t\t\t\trecover: WebSocketShardDestroyRecovery.Reconnect,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase CloseCodes.Resuming: {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.UnknownError: {\n\t\t\t\tthis.debug([`An unknown error occurred: ${code}`]);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.UnknownOpcode: {\n\t\t\t\tthis.debug(['An invalid opcode was sent to Discord.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.DecodeError: {\n\t\t\t\tthis.debug(['An invalid payload was sent to Discord.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.NotAuthenticated: {\n\t\t\t\tthis.debug(['A request was somehow sent before the identify/resume payload.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.AuthenticationFailed: {\n\t\t\t\tthrow new Error('Authentication failed');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.AlreadyAuthenticated: {\n\t\t\t\tthis.debug(['More than one auth payload was sent.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidSeq: {\n\t\t\t\tthis.debug(['An invalid sequence was sent.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.RateLimited: {\n\t\t\t\tthis.debug(['The WebSocket rate limit has been hit, this should never happen']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Reconnect });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.SessionTimedOut: {\n\t\t\t\tthis.debug(['Session timed out.']);\n\t\t\t\treturn this.destroy({ code, recover: WebSocketShardDestroyRecovery.Resume });\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidShard: {\n\t\t\t\tthrow new Error('Invalid shard');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.ShardingRequired: {\n\t\t\t\tthrow new Error('Sharding is required');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidAPIVersion: {\n\t\t\t\tthrow new Error('Used an invalid API version');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.InvalidIntents: {\n\t\t\t\tthrow new Error('Used invalid intents');\n\t\t\t}\n\n\t\t\tcase GatewayCloseCodes.DisallowedIntents: {\n\t\t\t\tthrow new Error('Used disallowed intents');\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tthis.debug([\n\t\t\t\t\t`The gateway closed with an unexpected code ${code}, attempting to ${\n\t\t\t\t\t\tthis.failedToConnectDueToNetworkError ? 'reconnect' : 'resume'\n\t\t\t\t\t}.`,\n\t\t\t\t]);\n\t\t\t\treturn this.destroy({\n\t\t\t\t\tcode,\n\t\t\t\t\trecover: this.failedToConnectDueToNetworkError\n\t\t\t\t\t\t? WebSocketShardDestroyRecovery.Reconnect\n\t\t\t\t\t\t: WebSocketShardDestroyRecovery.Resume,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate debug(messages: [string, ...string[]]) {\n\t\tconst message = `${messages[0]}${\n\t\t\tmessages.length > 1\n\t\t\t\t? `\\n${messages\n\t\t\t\t\t\t.slice(1)\n\t\t\t\t\t\t.map((m) => `\t${m}`)\n\t\t\t\t\t\t.join('\\n')}`\n\t\t\t\t: ''\n\t\t}`;\n\n\t\tthis.emit(WebSocketShardEvents.Debug, { message });\n\t}\n}\n","import process from 'node:process';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { APIVersion, GatewayOpcodes } from 'discord-api-types/v10';\nimport { SimpleShardingStrategy } from '../strategies/sharding/SimpleShardingStrategy.js';\nimport { SimpleIdentifyThrottler } from '../throttling/SimpleIdentifyThrottler.js';\nimport type { SessionInfo, OptionalWebSocketManagerOptions, WebSocketManager } from '../ws/WebSocketManager.js';\nimport type { SendRateLimitState } from '../ws/WebSocketShard.js';\n\n/**\n * Valid encoding types\n */\nexport enum Encoding {\n\tJSON = 'json',\n}\n\n/**\n * Valid compression methods\n */\nexport enum CompressionMethod {\n\tZlibStream = 'zlib-stream',\n}\n\nexport const DefaultDeviceProperty = `@discordjs/ws 0.8.3` as `@discordjs/ws ${string}`;\n\nconst getDefaultSessionStore = lazy(() => new Collection());\n\n/**\n * Default options used by the manager\n */\nexport const DefaultWebSocketManagerOptions = {\n\tasync buildIdentifyThrottler(manager: WebSocketManager) {\n\t\tconst info = await manager.fetchGatewayInformation();\n\t\treturn new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency);\n\t},\n\tbuildStrategy: (manager) => new SimpleShardingStrategy(manager),\n\tshardCount: null,\n\tshardIds: null,\n\tlargeThreshold: null,\n\tinitialPresence: null,\n\tidentifyProperties: {\n\t\tbrowser: DefaultDeviceProperty,\n\t\tdevice: DefaultDeviceProperty,\n\t\tos: process.platform,\n\t},\n\tversion: APIVersion,\n\tencoding: Encoding.JSON,\n\tcompression: null,\n\tretrieveSessionInfo(shardId) {\n\t\tconst store = getDefaultSessionStore();\n\t\treturn store.get(shardId) ?? null;\n\t},\n\tupdateSessionInfo(shardId: number, info: SessionInfo | null) {\n\t\tconst store = getDefaultSessionStore();\n\t\tif (info) {\n\t\t\tstore.set(shardId, info);\n\t\t} else {\n\t\t\tstore.delete(shardId);\n\t\t}\n\t},\n\thandshakeTimeout: 30_000,\n\thelloTimeout: 60_000,\n\treadyTimeout: 15_000,\n} as const satisfies OptionalWebSocketManagerOptions;\n\nexport const ImportantGatewayOpcodes = new Set([\n\tGatewayOpcodes.Heartbeat,\n\tGatewayOpcodes.Identify,\n\tGatewayOpcodes.Resume,\n]);\n\nexport function getInitialSendRateLimitState(): SendRateLimitState {\n\treturn {\n\t\tremaining: 120,\n\t\tresetAt: Date.now() + 60_000,\n\t};\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport { Collection } from '@discordjs/collection';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport type { IIdentifyThrottler } from './IIdentifyThrottler.js';\n\n/**\n * The state of a rate limit key's identify queue.\n */\nexport interface IdentifyState {\n\tqueue: AsyncQueue;\n\tresetsAt: number;\n}\n\n/**\n * Local, in-memory identify throttler.\n */\nexport class SimpleIdentifyThrottler implements IIdentifyThrottler {\n\tprivate readonly states = new Collection();\n\n\tpublic constructor(private readonly maxConcurrency: number) {}\n\n\t/**\n\t * {@inheritDoc IIdentifyThrottler.waitForIdentify}\n\t */\n\tpublic async waitForIdentify(shardId: number, signal: AbortSignal): Promise {\n\t\tconst key = shardId % this.maxConcurrency;\n\n\t\tconst state = this.states.ensure(key, () => {\n\t\t\treturn {\n\t\t\t\tqueue: new AsyncQueue(),\n\t\t\t\tresetsAt: Number.POSITIVE_INFINITY,\n\t\t\t};\n\t\t});\n\n\t\tawait state.queue.wait({ signal });\n\n\t\ttry {\n\t\t\tconst diff = state.resetsAt - Date.now();\n\t\t\tif (diff <= 5_000) {\n\t\t\t\t// To account for the latency the IDENTIFY payload goes through, we add a bit more wait time\n\t\t\t\tconst time = diff + Math.random() * 1_500;\n\t\t\t\tawait sleep(time);\n\t\t\t}\n\n\t\t\tstate.resetsAt = Date.now() + 5_000;\n\t\t} finally {\n\t\t\tstate.queue.shift();\n\t\t}\n\t}\n}\n","import { isMainThread, parentPort, workerData } from 'node:worker_threads';\nimport { Collection } from '@discordjs/collection';\nimport type { Awaitable } from '@discordjs/util';\nimport { WorkerContextFetchingStrategy } from '../strategies/context/WorkerContextFetchingStrategy.js';\nimport {\n\tWorkerReceivePayloadOp,\n\tWorkerSendPayloadOp,\n\ttype WorkerData,\n\ttype WorkerReceivePayload,\n\ttype WorkerSendPayload,\n} from '../strategies/sharding/WorkerShardingStrategy.js';\nimport type { WebSocketShardDestroyOptions } from '../ws/WebSocketShard.js';\nimport { WebSocketShardEvents, WebSocketShard } from '../ws/WebSocketShard.js';\n\n/**\n * Options for bootstrapping the worker\n */\nexport interface BootstrapOptions {\n\t/**\n\t * Shard events to just arbitrarily forward to the parent thread for the manager to emit\n\t * Note: By default, this will include ALL events\n\t * you most likely want to handle dispatch within the worker itself\n\t */\n\tforwardEvents?: WebSocketShardEvents[];\n\t/**\n\t * Function to call when a shard is created for additional setup\n\t */\n\tshardCallback?(shard: WebSocketShard): Awaitable;\n}\n\n/**\n * Utility class for bootstrapping a worker thread to be used for sharding\n */\nexport class WorkerBootstrapper {\n\t/**\n\t * The data passed to the worker thread\n\t */\n\tprotected readonly data = workerData as WorkerData;\n\n\t/**\n\t * The shards that are managed by this worker\n\t */\n\tprotected readonly shards = new Collection();\n\n\tpublic constructor() {\n\t\tif (isMainThread) {\n\t\t\tthrow new Error('Expected WorkerBootstrap to not be used within the main thread');\n\t\t}\n\t}\n\n\t/**\n\t * Helper method to initiate a shard's connection process\n\t */\n\tprotected async connect(shardId: number): Promise {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} does not exist`);\n\t\t}\n\n\t\tawait shard.connect();\n\t}\n\n\t/**\n\t * Helper method to destroy a shard\n\t */\n\tprotected async destroy(shardId: number, options?: WebSocketShardDestroyOptions): Promise {\n\t\tconst shard = this.shards.get(shardId);\n\t\tif (!shard) {\n\t\t\tthrow new RangeError(`Shard ${shardId} does not exist`);\n\t\t}\n\n\t\tawait shard.destroy(options);\n\t}\n\n\t/**\n\t * Helper method to attach event listeners to the parentPort\n\t */\n\tprotected setupThreadEvents(): void {\n\t\tparentPort!\n\t\t\t.on('messageerror', (err) => {\n\t\t\t\tthrow err;\n\t\t\t})\n\t\t\t.on('message', async (payload: WorkerSendPayload) => {\n\t\t\t\tswitch (payload.op) {\n\t\t\t\t\tcase WorkerSendPayloadOp.Connect: {\n\t\t\t\t\t\tawait this.connect(payload.shardId);\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.Connected,\n\t\t\t\t\t\t\tshardId: payload.shardId,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.Destroy: {\n\t\t\t\t\t\tawait this.destroy(payload.shardId, payload.options);\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.Destroyed,\n\t\t\t\t\t\t\tshardId: payload.shardId,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.Send: {\n\t\t\t\t\t\tconst shard = this.shards.get(payload.shardId);\n\t\t\t\t\t\tif (!shard) {\n\t\t\t\t\t\t\tthrow new RangeError(`Shard ${payload.shardId} does not exist`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait shard.send(payload.payload);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.SessionInfoResponse: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.ShardIdentifyResponse: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase WorkerSendPayloadOp.FetchStatus: {\n\t\t\t\t\t\tconst shard = this.shards.get(payload.shardId);\n\t\t\t\t\t\tif (!shard) {\n\t\t\t\t\t\t\tthrow new Error(`Shard ${payload.shardId} does not exist`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst response: WorkerReceivePayload = {\n\t\t\t\t\t\t\top: WorkerReceivePayloadOp.FetchStatusResponse,\n\t\t\t\t\t\t\tstatus: shard.status,\n\t\t\t\t\t\t\tnonce: payload.nonce,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tparentPort!.postMessage(response);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t}\n\n\t/**\n\t * Bootstraps the worker thread with the provided options\n\t */\n\tpublic async bootstrap(options: Readonly = {}): Promise {\n\t\t// Start by initializing the shards\n\t\tfor (const shardId of this.data.shardIds) {\n\t\t\tconst shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId);\n\t\t\tfor (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) {\n\t\t\t\t// @ts-expect-error: Event types incompatible\n\t\t\t\tshard.on(event, (data) => {\n\t\t\t\t\tconst payload: WorkerReceivePayload = {\n\t\t\t\t\t\top: WorkerReceivePayloadOp.Event,\n\t\t\t\t\t\tevent,\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\tshardId,\n\t\t\t\t\t};\n\t\t\t\t\tparentPort!.postMessage(payload);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Any additional setup the user might want to do\n\t\t\tawait options.shardCallback?.(shard);\n\t\t\tthis.shards.set(shardId, shard);\n\t\t}\n\n\t\t// Lastly, start listening to messages from the parent thread\n\t\tthis.setupThreadEvents();\n\n\t\tconst message: WorkerReceivePayload = {\n\t\t\top: WorkerReceivePayloadOp.WorkerReady,\n\t\t};\n\t\tparentPort!.postMessage(message);\n\t}\n}\n","import type { REST } from '@discordjs/rest';\nimport { range, type Awaitable } from '@discordjs/util';\nimport { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\nimport {\n\tRoutes,\n\ttype APIGatewayBotInfo,\n\ttype GatewayIdentifyProperties,\n\ttype GatewayPresenceUpdateData,\n\ttype RESTGetAPIGatewayBotResult,\n\ttype GatewayIntentBits,\n\ttype GatewaySendPayload,\n} from 'discord-api-types/v10';\nimport type { IShardingStrategy } from '../strategies/sharding/IShardingStrategy.js';\nimport type { IIdentifyThrottler } from '../throttling/IIdentifyThrottler.js';\nimport { DefaultWebSocketManagerOptions, type CompressionMethod, type Encoding } from '../utils/constants.js';\nimport type { WebSocketShardDestroyOptions, WebSocketShardEventsMap } from './WebSocketShard.js';\n\n/**\n * Represents a range of shard ids\n */\nexport interface ShardRange {\n\tend: number;\n\tstart: number;\n}\n\n/**\n * Session information for a given shard, used to resume a session\n */\nexport interface SessionInfo {\n\t/**\n\t * URL to use when resuming\n\t */\n\tresumeURL: string;\n\t/**\n\t * The sequence number of the last message sent by the shard\n\t */\n\tsequence: number;\n\t/**\n\t * Session id for this shard\n\t */\n\tsessionId: string;\n\t/**\n\t * The total number of shards at the time of this shard identifying\n\t */\n\tshardCount: number;\n\t/**\n\t * The id of the shard\n\t */\n\tshardId: number;\n}\n\n/**\n * Required options for the WebSocketManager\n */\nexport interface RequiredWebSocketManagerOptions {\n\t/**\n\t * The intents to request\n\t */\n\tintents: GatewayIntentBits | 0;\n\t/**\n\t * The REST instance to use for fetching gateway information\n\t */\n\trest: REST;\n\t/**\n\t * The token to use for identifying with the gateway\n\t */\n\ttoken: string;\n}\n\n/**\n * Optional additional configuration for the WebSocketManager\n */\nexport interface OptionalWebSocketManagerOptions {\n\t/**\n\t * Builds an identify throttler to use for this manager's shards\n\t */\n\tbuildIdentifyThrottler(manager: WebSocketManager): Awaitable;\n\t/**\n\t * Builds the strategy to use for sharding\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new WebSocketManager({\n\t * token: process.env.DISCORD_TOKEN,\n\t * intents: 0, // for no intents\n\t * rest,\n\t * buildStrategy: (manager) => new WorkerShardingStrategy(manager, { shardsPerWorker: 2 }),\n\t * });\n\t * ```\n\t */\n\tbuildStrategy(manager: WebSocketManager): IShardingStrategy;\n\t/**\n\t * The compression method to use\n\t *\n\t * @defaultValue `null` (no compression)\n\t */\n\tcompression: CompressionMethod | null;\n\t/**\n\t * The encoding to use\n\t *\n\t * @defaultValue `'json'`\n\t */\n\tencoding: Encoding;\n\t/**\n\t * How long to wait for a shard to connect before giving up\n\t */\n\thandshakeTimeout: number | null;\n\t/**\n\t * How long to wait for a shard's HELLO packet before giving up\n\t */\n\thelloTimeout: number | null;\n\t/**\n\t * Properties to send to the gateway when identifying\n\t */\n\tidentifyProperties: GatewayIdentifyProperties;\n\t/**\n\t * Initial presence data to send to the gateway when identifying\n\t */\n\tinitialPresence: GatewayPresenceUpdateData | null;\n\t/**\n\t * Value between 50 and 250, total number of members where the gateway will stop sending offline members in the guild member list\n\t */\n\tlargeThreshold: number | null;\n\t/**\n\t * How long to wait for a shard's READY packet before giving up\n\t */\n\treadyTimeout: number | null;\n\t/**\n\t * Function used to retrieve session information (and attempt to resume) for a given shard\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new WebSocketManager({\n\t * async retrieveSessionInfo(shardId): Awaitable {\n\t * // Fetch this info from redis or similar\n\t * return { sessionId: string, sequence: number };\n\t * // Return null if no information is found\n\t * },\n\t * });\n\t * ```\n\t */\n\tretrieveSessionInfo(shardId: number): Awaitable;\n\t/**\n\t * The total number of shards across all WebsocketManagers you intend to instantiate.\n\t * Use `null` to use Discord's recommended shard count\n\t */\n\tshardCount: number | null;\n\t/**\n\t * The ids of the shards this WebSocketManager should manage.\n\t * Use `null` to simply spawn 0 through `shardCount - 1`\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new WebSocketManager({\n\t * shardIds: [1, 3, 7], // spawns shard 1, 3, and 7, nothing else\n\t * });\n\t * ```\n\t * @example\n\t * ```ts\n\t * const manager = new WebSocketManager({\n\t * shardIds: {\n\t * start: 3,\n\t * end: 6,\n\t * }, // spawns shards 3, 4, 5, and 6\n\t * });\n\t * ```\n\t */\n\tshardIds: number[] | ShardRange | null;\n\t/**\n\t * Function used to store session information for a given shard\n\t */\n\tupdateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable;\n\t/**\n\t * The gateway version to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\nexport type WebSocketManagerOptions = OptionalWebSocketManagerOptions & RequiredWebSocketManagerOptions;\n\nexport type ManagerShardEventsMap = {\n\t[K in keyof WebSocketShardEventsMap]: [\n\t\tWebSocketShardEventsMap[K] extends [] ? { shardId: number } : WebSocketShardEventsMap[K][0] & { shardId: number },\n\t];\n};\n\nexport class WebSocketManager extends AsyncEventEmitter {\n\t/**\n\t * The options being used by this manager\n\t */\n\tpublic readonly options: WebSocketManagerOptions;\n\n\t/**\n\t * Internal cache for a GET /gateway/bot result\n\t */\n\tprivate gatewayInformation: {\n\t\tdata: APIGatewayBotInfo;\n\t\texpiresAt: number;\n\t} | null = null;\n\n\t/**\n\t * Internal cache for the shard ids\n\t */\n\tprivate shardIds: number[] | null = null;\n\n\t/**\n\t * Strategy used to manage shards\n\t *\n\t * @defaultValue `SimpleShardingStrategy`\n\t */\n\tprivate readonly strategy: IShardingStrategy;\n\n\tpublic constructor(options: Partial & RequiredWebSocketManagerOptions) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultWebSocketManagerOptions, ...options };\n\t\tthis.strategy = this.options.buildStrategy(this);\n\t}\n\n\t/**\n\t * Fetches the gateway information from Discord - or returns it from cache if available\n\t *\n\t * @param force - Whether to ignore the cache and force a fresh fetch\n\t */\n\tpublic async fetchGatewayInformation(force = false) {\n\t\tif (this.gatewayInformation) {\n\t\t\tif (this.gatewayInformation.expiresAt <= Date.now()) {\n\t\t\t\tthis.gatewayInformation = null;\n\t\t\t} else if (!force) {\n\t\t\t\treturn this.gatewayInformation.data;\n\t\t\t}\n\t\t}\n\n\t\tconst data = (await this.options.rest.get(Routes.gatewayBot())) as RESTGetAPIGatewayBotResult;\n\n\t\tthis.gatewayInformation = { data, expiresAt: Date.now() + data.session_start_limit.reset_after };\n\t\treturn this.gatewayInformation.data;\n\t}\n\n\t/**\n\t * Updates your total shard count on-the-fly, spawning shards as needed\n\t *\n\t * @param shardCount - The new shard count to use\n\t */\n\tpublic async updateShardCount(shardCount: number | null) {\n\t\tawait this.strategy.destroy({ reason: 'User is adjusting their shards' });\n\t\tthis.options.shardCount = shardCount;\n\n\t\tconst shardIds = await this.getShardIds(true);\n\t\tawait this.strategy.spawn(shardIds);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Yields the total number of shards across for your bot, accounting for Discord recommendations\n\t */\n\tpublic async getShardCount(): Promise {\n\t\tif (this.options.shardCount) {\n\t\t\treturn this.options.shardCount;\n\t\t}\n\n\t\tconst shardIds = await this.getShardIds();\n\t\treturn Math.max(...shardIds) + 1;\n\t}\n\n\t/**\n\t * Yields the ids of the shards this manager should manage\n\t */\n\tpublic async getShardIds(force = false): Promise {\n\t\tif (this.shardIds && !force) {\n\t\t\treturn this.shardIds;\n\t\t}\n\n\t\tlet shardIds: number[];\n\t\tif (this.options.shardIds) {\n\t\t\tif (Array.isArray(this.options.shardIds)) {\n\t\t\t\tshardIds = this.options.shardIds;\n\t\t\t} else {\n\t\t\t\tconst { start, end } = this.options.shardIds;\n\t\t\t\tshardIds = [...range({ start, end: end + 1 })];\n\t\t\t}\n\t\t} else {\n\t\t\tconst data = await this.fetchGatewayInformation();\n\t\t\tshardIds = [...range(this.options.shardCount ?? data.shards)];\n\t\t}\n\n\t\tthis.shardIds = shardIds;\n\t\treturn shardIds;\n\t}\n\n\tpublic async connect() {\n\t\tconst shardCount = await this.getShardCount();\n\n\t\tconst data = await this.fetchGatewayInformation();\n\t\tif (data.session_start_limit.remaining < shardCount) {\n\t\t\tthrow new Error(\n\t\t\t\t`Not enough sessions remaining to spawn ${shardCount} shards; only ${\n\t\t\t\t\tdata.session_start_limit.remaining\n\t\t\t\t} remaining; resets at ${new Date(Date.now() + data.session_start_limit.reset_after).toISOString()}`,\n\t\t\t);\n\t\t}\n\n\t\t// First, make sure all our shards are spawned\n\t\tawait this.updateShardCount(shardCount);\n\t\tawait this.strategy.connect();\n\t}\n\n\tpublic destroy(options?: Omit) {\n\t\treturn this.strategy.destroy(options);\n\t}\n\n\tpublic send(shardId: number, payload: GatewaySendPayload) {\n\t\treturn this.strategy.send(shardId, payload);\n\t}\n\n\tpublic fetchStatus() {\n\t\treturn this.strategy.fetchStatus();\n\t}\n}\n","export * from './strategies/context/IContextFetchingStrategy.js';\nexport * from './strategies/context/SimpleContextFetchingStrategy.js';\nexport * from './strategies/context/WorkerContextFetchingStrategy.js';\n\nexport * from './strategies/sharding/IShardingStrategy.js';\nexport * from './strategies/sharding/SimpleShardingStrategy.js';\nexport * from './strategies/sharding/WorkerShardingStrategy.js';\n\nexport * from './throttling/IIdentifyThrottler.js';\nexport * from './throttling/SimpleIdentifyThrottler.js';\n\nexport * from './utils/constants.js';\nexport * from './utils/WorkerBootstrapper.js';\n\nexport * from './ws/WebSocketManager.js';\nexport * from './ws/WebSocketShard.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/ws/#readme | @discordjs/ws} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '0.8.3' as string;\n"],"mappings":";;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ACD;AAGA,UAAM,KAAK,iBAAiB,UAAU;AACtC,UAAM,KAAK,SAAS,QAAQ;AAAA,EAC7B;AAAA,EAEO,QAAQ,SAAyD;AACvE,WAAO,KAAK,SAAS,QAAQ,OAAO;AAAA,EACrC;AAAA,EAEO,KAAK,SAAiB,SAA6B;AACzD,WAAO,KAAK,SAAS,KAAK,SAAS,OAAO;AAAA,EAC3C;AAAA,EAEO,cAAc;AACpB,WAAO,KAAK,SAAS,YAAY;AAAA,EAClC;AACD;AApIa;;;ACtKN,IAAM,UAAU;","names":["Collection","WorkerSendPayloadOp","WorkerReceivePayloadOp","workerData","resolve","path","Collection","resolve","payload","Collection","Buffer","once","sleep","Collection","lazy","AsyncQueue","GatewayOpcodes","Collection","Collection","Collection","Encoding","CompressionMethod","Collection","lazy","WebSocketShardEvents","WebSocketShardStatus","WebSocketShardDestroyRecovery","CloseCodes","AsyncQueue","Collection","once","version","sleep","GatewayOpcodes","resolve","Buffer","session","Collection","isMainThread","parentPort","Collection","Collection","isMainThread","parentPort","AsyncEventEmitter","AsyncEventEmitter"]} \ No newline at end of file diff --git a/node_modules/@discordjs/ws/package.json b/node_modules/@discordjs/ws/package.json new file mode 100644 index 0000000..803afeb --- /dev/null +++ b/node_modules/@discordjs/ws/package.json @@ -0,0 +1,99 @@ +{ + "name": "@discordjs/ws", + "version": "0.8.3", + "description": "Wrapper around Discord's gateway", + "scripts": { + "test": "vitest run", + "build": "tsup", + "build:docs": "tsc -p tsconfig.docs.json", + "lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty", + "format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", + "prepack": "yarn build && yarn lint", + "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/ws/*'", + "release": "cliff-jumper" + }, + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "typings": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./defaultWorker": { + "types": null, + "import": "./dist/defaultWorker.mjs", + "require": "./dist/defaultWorker.js" + } + }, + "directories": { + "lib": "src", + "test": "__tests__" + }, + "files": [ + "dist" + ], + "contributors": [ + "Crawl ", + "Amish Shah ", + "SpaceEEC ", + "Vlad Frangu ", + "Aura Román ", + "DD " + ], + "license": "Apache-2.0", + "keywords": [ + "discord", + "api", + "gateway", + "discordapp", + "discordjs" + ], + "repository": { + "type": "git", + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/ws" + }, + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" + }, + "homepage": "https://discord.js.org", + "dependencies": { + "@discordjs/collection": "^1.5.1", + "@discordjs/rest": "^1.7.1", + "@discordjs/util": "^0.3.1", + "@sapphire/async-queue": "^1.5.0", + "@types/ws": "^8.5.4", + "@vladfrangu/async_event_emitter": "^2.2.1", + "discord-api-types": "^0.37.41", + "tslib": "^2.5.0", + "ws": "^8.13.0" + }, + "devDependencies": { + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.8", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.31.0", + "cross-env": "^7.0.3", + "esbuild-plugin-version-injector": "^1.1.0", + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.46", + "eslint-formatter-pretty": "^5.0.0", + "mock-socket": "^9.2.1", + "prettier": "^2.8.8", + "tsup": "^6.7.0", + "turbo": "^1.9.4-canary.9", + "typescript": "^5.0.4", + "undici": "^5.22.0", + "vitest": "^0.31.0", + "zlib-sync": "^0.1.8" + }, + "engines": { + "node": ">=16.9.0" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/node_modules/@sapphire/shapeshift/CHANGELOG.md b/node_modules/@sapphire/shapeshift/CHANGELOG.md index d048520..1d4b4a3 100644 --- a/node_modules/@sapphire/shapeshift/CHANGELOG.md +++ b/node_modules/@sapphire/shapeshift/CHANGELOG.md @@ -2,6 +2,35 @@ All notable changes to this project will be documented in this file. +# [3.9.2](https://github.com/sapphiredev/shapeshift/compare/v3.9.1...v3.9.2) - (2023-06-04) + +## 🐛 Bug Fixes + +- **arrayvalidator:** Fixed runaway type instantiation with TypeScript >=5.1 (#275) ([f59d901](https://github.com/sapphiredev/shapeshift/commit/f59d90112181e6625230c28e6a4f0f065ced6344)) + +# [3.9.1](https://github.com/sapphiredev/shapeshift/compare/v3.9.0...v3.9.1) - (2023-06-02) + +## 🐛 Bug Fixes + +- **types:** Move the `types` condition to the front (#273) ([5a3e202](https://github.com/sapphiredev/shapeshift/commit/5a3e202e9ceafb3d330a568e93c060dd5aac1dde)) + +# [3.9.0](https://github.com/sapphiredev/shapeshift/compare/v3.8.2...v3.9.0) - (2023-05-09) + +## 🐛 Bug Fixes + +- Resolve minor grammar mistake (#260) ([62df609](https://github.com/sapphiredev/shapeshift/commit/62df6094845ffa118aa93ea3c5f47f81f1c5d99f)) + +## 🚀 Features + +- Add BaseValidator.describe (#267) ([d9e1a2d](https://github.com/sapphiredev/shapeshift/commit/d9e1a2d2f3c5e6378f0025becf8497138ee6d97c)) + +# [3.8.2](https://github.com/sapphiredev/shapeshift/compare/v3.8.1...v3.8.2) - (2023-04-02) + +## 🐛 Bug Fixes + +- ***:** TypeScript 5.x compatibility (#253) ([eba2a88](https://github.com/sapphiredev/shapeshift/commit/eba2a88b91fb6631f431313753299ec7a70cf6ce)) +- Remove `node:` prefix (#249) ([af766b5](https://github.com/sapphiredev/shapeshift/commit/af766b504c1013f3cd24f7bf803ac9ff7442a8d7)) + # [3.8.1](https://github.com/sapphiredev/shapeshift/compare/v3.8.0...v3.8.1) - (2022-12-15) ## 🐛 Bug Fixes diff --git a/node_modules/@sapphire/shapeshift/README.md b/node_modules/@sapphire/shapeshift/README.md index f970cb1..c9f113f 100644 --- a/node_modules/@sapphire/shapeshift/README.md +++ b/node_modules/@sapphire/shapeshift/README.md @@ -1,6 +1,6 @@
-![Sapphire Logo](https://cdn.skyra.pw/gh-assets/sapphire-banner.png) +![Sapphire Logo](https://raw.githubusercontent.com/sapphiredev/assets/main/banners/SapphireCommunity.png) # @sapphire/shapeshift @@ -920,36 +920,15 @@ below to donate through your method of choice. [Back to top][toc] -Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): +Please make sure to read the [Contributing Guide][contributing] before making a pull request. - - - - - - - - - - - - - - - - - - -

Antonio Román

💻 📖 🤔

Vlad Frangu

💻 📖 🤔

Jeroen Claassens

📖 🚧 🚇

renovate[bot]

🚧

WhiteSource Renovate

🚧

John

💻

Parbez

💻 ⚠️ 🐛 📖

allcontributors[bot]

📖

Hezekiah Hendry

🔧

Voxelli

📖
+Thank you to all the people who already contributed to Sapphire! - - - - - -This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. -Contributions of any kind welcome! + + + +[contributing]: https://github.com/sapphiredev/.github/blob/main/.github/CONTRIBUTING.md [`zod`]: https://github.com/colinhacks/zod [documentation]: https://www.sapphirejs.dev/docs/Documentation/api-shapeshift/ [toc]: #table-of-contents diff --git a/node_modules/@sapphire/shapeshift/dist/index.d.ts b/node_modules/@sapphire/shapeshift/dist/index.d.ts index 586de82..748451d 100644 --- a/node_modules/@sapphire/shapeshift/dist/index.d.ts +++ b/node_modules/@sapphire/shapeshift/dist/index.d.ts @@ -1,4 +1,4 @@ -import { InspectOptionsStylized } from 'node:util'; +import { InspectOptionsStylized } from 'util'; declare class Result { readonly success: boolean; @@ -301,7 +301,7 @@ declare class ObjectValidator> exte private handleStrictStrategy; private handlePassthroughStrategy; } -declare const enum ObjectValidatorStrategy { +declare enum ObjectValidatorStrategy { Ignore = 0, Strict = 1, Passthrough = 2 @@ -500,6 +500,7 @@ declare class ArrayValidator extends BaseVal } declare abstract class BaseValidator { + description?: string; protected parent?: object; protected constraints: readonly IConstraint[]; protected isValidationEnabled: boolean | (() => boolean) | null; @@ -517,6 +518,7 @@ declare abstract class BaseValidator { reshape, O = InferResultType>(cb: (input: T) => R): BaseValidator; default(value: Exclude | (() => Exclude)): DefaultValidator>; when = this>(key: Key, options: WhenOptions): this; + describe(description: string): this; run(value: unknown): Result; parse(value: unknown): R; is(value: unknown): value is R; @@ -650,7 +652,7 @@ type ExpandSmallerTuples = T extends [T[0], ...infer Tail] type Shift> = ((...args: A) => void) extends (...args: [A[0], ...infer R]) => void ? R : never; type GrowExpRev, N extends number, P extends Array>> = A['length'] extends N ? A : GrowExpRev<[...A, ...P[0]][N] extends undefined ? [...A, ...P[0]] : A, N, Shift

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

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

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

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

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

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

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

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

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

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

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

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

= (...params: P) => E | null;\n","import { MultiplePossibilitiesConstraintError } from '../../lib/errors/MultiplePossibilitiesConstraintError';\nimport { combinedErrorFn, type ErrorFn } from './common/combinedResultFn';\n\nexport type StringProtocol = `${string}:`;\n\nexport type StringDomain = `${string}.${string}`;\n\nexport interface UrlOptions {\n\tallowedProtocols?: StringProtocol[];\n\tallowedDomains?: StringDomain[];\n}\n\nexport function createUrlValidators(options?: UrlOptions) {\n\tconst fns: ErrorFn<[input: string, url: URL], MultiplePossibilitiesConstraintError>[] = [];\n\n\tif (options?.allowedProtocols?.length) fns.push(allowedProtocolsFn(options.allowedProtocols));\n\tif (options?.allowedDomains?.length) fns.push(allowedDomainsFn(options.allowedDomains));\n\n\treturn combinedErrorFn(...fns);\n}\n\nfunction allowedProtocolsFn(allowedProtocols: StringProtocol[]) {\n\treturn (input: string, url: URL) =>\n\t\tallowedProtocols.includes(url.protocol as StringProtocol)\n\t\t\t? null\n\t\t\t: new MultiplePossibilitiesConstraintError('s.string.url', 'Invalid URL protocol', input, allowedProtocols);\n}\n\nfunction allowedDomainsFn(allowedDomains: StringDomain[]) {\n\treturn (input: string, url: URL) =>\n\t\tallowedDomains.includes(url.hostname as StringDomain)\n\t\t\t? null\n\t\t\t: new MultiplePossibilitiesConstraintError('s.string.url', 'Invalid URL domain', input, allowedDomains);\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { validateEmail } from './util/emailValidator';\nimport { isIP, isIPv4, isIPv6 } from './util/net';\nimport { equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual, type Comparator } from './util/operators';\nimport { validatePhoneNumber } from './util/phoneValidator';\nimport { createUrlValidators } from './util/urlValidators';\n\nexport type StringConstraintName =\n\t| `s.string.${\n\t\t\t| `length${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual'}`\n\t\t\t| 'regex'\n\t\t\t| 'url'\n\t\t\t| 'uuid'\n\t\t\t| 'email'\n\t\t\t| `ip${'v4' | 'v6' | ''}`\n\t\t\t| 'date'\n\t\t\t| 'phone'}`;\n\nexport type StringProtocol = `${string}:`;\n\nexport type StringDomain = `${string}.${string}`;\n\nexport interface UrlOptions {\n\tallowedProtocols?: StringProtocol[];\n\tallowedDomains?: StringDomain[];\n}\n\nexport type UUIDVersion = 1 | 3 | 4 | 5;\n\nexport interface StringUuidOptions {\n\tversion?: UUIDVersion | `${UUIDVersion}-${UUIDVersion}` | null;\n\tnullable?: boolean;\n}\n\nfunction stringLengthComparator(comparator: Comparator, name: StringConstraintName, expected: string, length: number): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid string length', input, expected));\n\t\t}\n\t};\n}\n\nexport function stringLengthLessThan(length: number): IConstraint {\n\tconst expected = `expected.length < ${length}`;\n\treturn stringLengthComparator(lessThan, 's.string.lengthLessThan', expected, length);\n}\n\nexport function stringLengthLessThanOrEqual(length: number): IConstraint {\n\tconst expected = `expected.length <= ${length}`;\n\treturn stringLengthComparator(lessThanOrEqual, 's.string.lengthLessThanOrEqual', expected, length);\n}\n\nexport function stringLengthGreaterThan(length: number): IConstraint {\n\tconst expected = `expected.length > ${length}`;\n\treturn stringLengthComparator(greaterThan, 's.string.lengthGreaterThan', expected, length);\n}\n\nexport function stringLengthGreaterThanOrEqual(length: number): IConstraint {\n\tconst expected = `expected.length >= ${length}`;\n\treturn stringLengthComparator(greaterThanOrEqual, 's.string.lengthGreaterThanOrEqual', expected, length);\n}\n\nexport function stringLengthEqual(length: number): IConstraint {\n\tconst expected = `expected.length === ${length}`;\n\treturn stringLengthComparator(equal, 's.string.lengthEqual', expected, length);\n}\n\nexport function stringLengthNotEqual(length: number): IConstraint {\n\tconst expected = `expected.length !== ${length}`;\n\treturn stringLengthComparator(notEqual, 's.string.lengthNotEqual', expected, length);\n}\n\nexport function stringEmail(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validateEmail(input)\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.string.email', 'Invalid email address', input, 'expected to be an email address'));\n\t\t}\n\t};\n}\n\nfunction stringRegexValidator(type: StringConstraintName, expected: string, regex: RegExp): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn regex.test(input) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(type, 'Invalid string format', input, expected));\n\t\t}\n\t};\n}\n\nexport function stringUrl(options?: UrlOptions): IConstraint {\n\tconst validatorFn = createUrlValidators(options);\n\treturn {\n\t\trun(input: string) {\n\t\t\tlet url: URL;\n\t\t\ttry {\n\t\t\t\turl = new URL(input);\n\t\t\t} catch {\n\t\t\t\treturn Result.err(new ExpectedConstraintError('s.string.url', 'Invalid URL', input, 'expected to match a URL'));\n\t\t\t}\n\n\t\t\tconst validatorFnResult = validatorFn(input, url);\n\t\t\tif (validatorFnResult === null) return Result.ok(input);\n\t\t\treturn Result.err(validatorFnResult);\n\t\t}\n\t};\n}\n\nexport function stringIp(version?: 4 | 6): IConstraint {\n\tconst ipVersion = version ? (`v${version}` as const) : '';\n\tconst validatorFn = version === 4 ? isIPv4 : version === 6 ? isIPv6 : isIP;\n\n\tconst name = `s.string.ip${ipVersion}` as const;\n\tconst message = `Invalid IP${ipVersion} address`;\n\tconst expected = `expected to be an IP${ipVersion} address`;\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validatorFn(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, message, input, expected));\n\t\t}\n\t};\n}\n\nexport function stringRegex(regex: RegExp) {\n\treturn stringRegexValidator('s.string.regex', `expected ${regex}.test(expected) to be true`, regex);\n}\n\nexport function stringUuid({ version = 4, nullable = false }: StringUuidOptions = {}) {\n\tversion ??= '1-5';\n\tconst regex = new RegExp(\n\t\t`^(?:[0-9A-F]{8}-[0-9A-F]{4}-[${version}][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}${\n\t\t\tnullable ? '|00000000-0000-0000-0000-000000000000' : ''\n\t\t})$`,\n\t\t'i'\n\t);\n\tconst expected = `expected to match UUID${typeof version === 'number' ? `v${version}` : ` in range of ${version}`}`;\n\treturn stringRegexValidator('s.string.uuid', expected, regex);\n}\n\nexport function stringDate(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\tconst time = Date.parse(input);\n\n\t\t\treturn Number.isNaN(time)\n\t\t\t\t? Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError(\n\t\t\t\t\t\t\t's.string.date',\n\t\t\t\t\t\t\t'Invalid date string',\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t'expected to be a valid date string (in the ISO 8601 or ECMA-262 format)'\n\t\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t: Result.ok(input);\n\t\t}\n\t};\n}\n\nexport function stringPhone(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validatePhoneNumber(input)\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.string.phone', 'Invalid phone number', input, 'expected to be a phone number'));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tstringDate,\n\tstringEmail,\n\tstringIp,\n\tstringLengthEqual,\n\tstringLengthGreaterThan,\n\tstringLengthGreaterThanOrEqual,\n\tstringLengthLessThan,\n\tstringLengthLessThanOrEqual,\n\tstringLengthNotEqual,\n\tstringPhone,\n\tstringRegex,\n\tstringUrl,\n\tstringUuid,\n\ttype StringUuidOptions,\n\ttype UrlOptions\n} from '../constraints/StringConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class StringValidator extends BaseValidator {\n\tpublic lengthLessThan(length: number): this {\n\t\treturn this.addConstraint(stringLengthLessThan(length) as IConstraint);\n\t}\n\n\tpublic lengthLessThanOrEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthLessThanOrEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthGreaterThan(length: number): this {\n\t\treturn this.addConstraint(stringLengthGreaterThan(length) as IConstraint);\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthGreaterThanOrEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthNotEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthNotEqual(length) as IConstraint);\n\t}\n\n\tpublic get email(): this {\n\t\treturn this.addConstraint(stringEmail() as IConstraint);\n\t}\n\n\tpublic url(options?: UrlOptions): this {\n\t\treturn this.addConstraint(stringUrl(options) as IConstraint);\n\t}\n\n\tpublic uuid(options?: StringUuidOptions): this {\n\t\treturn this.addConstraint(stringUuid(options) as IConstraint);\n\t}\n\n\tpublic regex(regex: RegExp): this {\n\t\treturn this.addConstraint(stringRegex(regex) as IConstraint);\n\t}\n\n\tpublic get date() {\n\t\treturn this.addConstraint(stringDate() as IConstraint);\n\t}\n\n\tpublic get ipv4(): this {\n\t\treturn this.ip(4);\n\t}\n\n\tpublic get ipv6(): this {\n\t\treturn this.ip(6);\n\t}\n\n\tpublic ip(version?: 4 | 6): this {\n\t\treturn this.addConstraint(stringIp(version) as IConstraint);\n\t}\n\n\tpublic phone(): this {\n\t\treturn this.addConstraint(stringPhone() as IConstraint);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'string' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.string', 'Expected a string primitive', value));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class TupleValidator extends BaseValidator<[...T]> {\n\tprivate readonly validators: BaseValidator<[...T]>[] = [];\n\n\tpublic constructor(validators: BaseValidator<[...T]>[], constraints: readonly IConstraint<[...T]>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validators = validators;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validators, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result<[...T], ValidationError | CombinedPropertyError> {\n\t\tif (!Array.isArray(values)) {\n\t\t\treturn Result.err(new ValidationError('s.tuple(T)', 'Expected an array', values));\n\t\t}\n\n\t\tif (values.length !== this.validators.length) {\n\t\t\treturn Result.err(new ValidationError('s.tuple(T)', `Expected an array of length ${this.validators.length}`, values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values as [...T]);\n\t\t}\n\n\t\tconst errors: [number, BaseError][] = [];\n\t\tconst transformed: T = [] as unknown as T;\n\n\t\tfor (let i = 0; i < values.length; i++) {\n\t\t\tconst result = this.validators[i].run(values[i]);\n\t\t\tif (result.isOk()) transformed.push(result.value);\n\t\t\telse errors.push([i, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class MapValidator extends BaseValidator> {\n\tprivate readonly keyValidator: BaseValidator;\n\tprivate readonly valueValidator: BaseValidator;\n\n\tpublic constructor(keyValidator: BaseValidator, valueValidator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.keyValidator = keyValidator;\n\t\tthis.valueValidator = valueValidator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.keyValidator, this.valueValidator, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result, ValidationError | CombinedPropertyError> {\n\t\tif (!(value instanceof Map)) {\n\t\t\treturn Result.err(new ValidationError('s.map(K, V)', 'Expected a map', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value);\n\t\t}\n\n\t\tconst errors: [string, BaseError][] = [];\n\t\tconst transformed = new Map();\n\n\t\tfor (const [key, val] of value.entries()) {\n\t\t\tconst keyResult = this.keyValidator.run(key);\n\t\t\tconst valueResult = this.valueValidator.run(val);\n\t\t\tconst { length } = errors;\n\t\t\tif (keyResult.isErr()) errors.push([key, keyResult.error]);\n\t\t\tif (valueResult.isErr()) errors.push([key, valueResult.error]);\n\t\t\tif (errors.length === length) transformed.set(keyResult.value!, valueResult.value!);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { Result } from '../lib/Result';\nimport type { IConstraint, Unwrap } from '../type-exports';\nimport { BaseValidator, type ValidatorError } from './imports';\n\nexport class LazyValidator, R = Unwrap> extends BaseValidator {\n\tprivate readonly validator: (value: unknown) => T;\n\n\tpublic constructor(validator: (value: unknown) => T, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result {\n\t\treturn this.validator(values).run(values) as Result;\n\t}\n}\n","import type { InspectOptionsStylized } from 'util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class UnknownEnumValueError extends BaseError {\n\tpublic readonly value: string | number;\n\tpublic readonly enumKeys: string[];\n\tpublic readonly enumMappings: Map;\n\n\tpublic constructor(value: string | number, keys: string[], enumMappings: Map) {\n\t\tsuper('Expected the value to be one of the following enum values:');\n\n\t\tthis.value = value;\n\t\tthis.enumKeys = keys;\n\t\tthis.enumMappings = enumMappings;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalue: this.value,\n\t\t\tenumKeys: this.enumKeys,\n\t\t\tenumMappings: [...this.enumMappings.entries()]\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst value = options.stylize(this.value.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[UnknownEnumValueError: ${value}]`, 'special');\n\t\t}\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst pairs = this.enumKeys\n\t\t\t.map((key) => {\n\t\t\t\tconst enumValue = this.enumMappings.get(key)!;\n\t\t\t\treturn `${options.stylize(key, 'string')} or ${options.stylize(\n\t\t\t\t\tenumValue.toString(),\n\t\t\t\t\ttypeof enumValue === 'number' ? 'number' : 'string'\n\t\t\t\t)}`;\n\t\t\t})\n\t\t\t.join(padding);\n\n\t\tconst header = `${options.stylize('UnknownEnumValueError', 'special')} > ${value}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst pairsBlock = `${padding}${pairs}`;\n\t\treturn `${header}\\n ${message}\\n${pairsBlock}`;\n\t}\n}\n","import { UnknownEnumValueError } from '../lib/errors/UnknownEnumValueError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NativeEnumValidator extends BaseValidator {\n\tpublic readonly enumShape: T;\n\tpublic readonly hasNumericElements: boolean = false;\n\tprivate readonly enumKeys: string[];\n\tprivate readonly enumMapping = new Map();\n\n\tpublic constructor(enumShape: T) {\n\t\tsuper();\n\t\tthis.enumShape = enumShape;\n\n\t\tthis.enumKeys = Object.keys(enumShape).filter((key) => {\n\t\t\treturn typeof enumShape[enumShape[key]] !== 'number';\n\t\t});\n\n\t\tfor (const key of this.enumKeys) {\n\t\t\tconst enumValue = enumShape[key] as T[keyof T];\n\n\t\t\tthis.enumMapping.set(key, enumValue);\n\t\t\tthis.enumMapping.set(enumValue, enumValue);\n\n\t\t\tif (typeof enumValue === 'number') {\n\t\t\t\tthis.hasNumericElements = true;\n\t\t\t\tthis.enumMapping.set(`${enumValue}`, enumValue);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected override handle(value: unknown): Result {\n\t\tconst typeOfValue = typeof value;\n\n\t\tif (typeOfValue === 'number') {\n\t\t\tif (!this.hasNumericElements) {\n\t\t\t\treturn Result.err(new ValidationError('s.nativeEnum(T)', 'Expected the value to be a string', value));\n\t\t\t}\n\t\t} else if (typeOfValue !== 'string') {\n\t\t\t// typeOfValue !== 'number' is implied here\n\t\t\treturn Result.err(new ValidationError('s.nativeEnum(T)', 'Expected the value to be a string or number', value));\n\t\t}\n\n\t\tconst casted = value as string | number;\n\n\t\tconst possibleEnumValue = this.enumMapping.get(casted);\n\n\t\treturn typeof possibleEnumValue === 'undefined'\n\t\t\t? Result.err(new UnknownEnumValueError(casted, this.enumKeys, this.enumMapping))\n\t\t\t: Result.ok(possibleEnumValue);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.enumShape]);\n\t}\n}\n\nexport interface NativeEnumLike {\n\t[key: string]: string | number;\n\t[key: number]: string;\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual, type Comparator } from './util/operators';\nimport type { TypedArray } from './util/typedArray';\n\nexport type TypedArrayConstraintName = `s.typedArray(T).${'byteLength' | 'length'}${\n\t| 'LessThan'\n\t| 'LessThanOrEqual'\n\t| 'GreaterThan'\n\t| 'GreaterThanOrEqual'\n\t| 'Equal'\n\t| 'NotEqual'\n\t| 'Range'\n\t| 'RangeInclusive'\n\t| 'RangeExclusive'}`;\n\nfunction typedArrayByteLengthComparator(\n\tcomparator: Comparator,\n\tname: TypedArrayConstraintName,\n\texpected: string,\n\tlength: number\n): IConstraint {\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn comparator(input.byteLength, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Typed Array byte length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.byteLength < ${value}`;\n\treturn typedArrayByteLengthComparator(lessThan, 's.typedArray(T).byteLengthLessThan', expected, value);\n}\n\nexport function typedArrayByteLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength <= ${value}`;\n\treturn typedArrayByteLengthComparator(lessThanOrEqual, 's.typedArray(T).byteLengthLessThanOrEqual', expected, value);\n}\n\nexport function typedArrayByteLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.byteLength > ${value}`;\n\treturn typedArrayByteLengthComparator(greaterThan, 's.typedArray(T).byteLengthGreaterThan', expected, value);\n}\n\nexport function typedArrayByteLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength >= ${value}`;\n\treturn typedArrayByteLengthComparator(greaterThanOrEqual, 's.typedArray(T).byteLengthGreaterThanOrEqual', expected, value);\n}\n\nexport function typedArrayByteLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength === ${value}`;\n\treturn typedArrayByteLengthComparator(equal, 's.typedArray(T).byteLengthEqual', expected, value);\n}\n\nexport function typedArrayByteLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength !== ${value}`;\n\treturn typedArrayByteLengthComparator(notEqual, 's.typedArray(T).byteLengthNotEqual', expected, value);\n}\n\nexport function typedArrayByteLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.byteLength >= ${start} && expected.byteLength < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength >= start && input.byteLength < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).byteLengthRange', 'Invalid Typed Array byte length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthRangeInclusive(start: number, end: number) {\n\tconst expected = `expected.byteLength >= ${start} && expected.byteLength <= ${end}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength >= start && input.byteLength <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError('s.typedArray(T).byteLengthRangeInclusive', 'Invalid Typed Array byte length', input, expected)\n\t\t\t\t );\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.byteLength > ${startAfter} && expected.byteLength < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength > startAfter && input.byteLength < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError('s.typedArray(T).byteLengthRangeExclusive', 'Invalid Typed Array byte length', input, expected)\n\t\t\t\t );\n\t\t}\n\t};\n}\n\nfunction typedArrayLengthComparator(\n\tcomparator: Comparator,\n\tname: TypedArrayConstraintName,\n\texpected: string,\n\tlength: number\n): IConstraint {\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.length < ${value}`;\n\treturn typedArrayLengthComparator(lessThan, 's.typedArray(T).lengthLessThan', expected, value);\n}\n\nexport function typedArrayLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length <= ${value}`;\n\treturn typedArrayLengthComparator(lessThanOrEqual, 's.typedArray(T).lengthLessThanOrEqual', expected, value);\n}\n\nexport function typedArrayLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.length > ${value}`;\n\treturn typedArrayLengthComparator(greaterThan, 's.typedArray(T).lengthGreaterThan', expected, value);\n}\n\nexport function typedArrayLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length >= ${value}`;\n\treturn typedArrayLengthComparator(greaterThanOrEqual, 's.typedArray(T).lengthGreaterThanOrEqual', expected, value);\n}\n\nexport function typedArrayLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.length === ${value}`;\n\treturn typedArrayLengthComparator(equal, 's.typedArray(T).lengthEqual', expected, value);\n}\n\nexport function typedArrayLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.length !== ${value}`;\n\treturn typedArrayLengthComparator(notEqual, 's.typedArray(T).lengthNotEqual', expected, value);\n}\n\nexport function typedArrayLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length >= start && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRange', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthRangeInclusive(start: number, end: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length <= ${end}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length >= start && input.length <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRangeInclusive', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length > startAfter && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRangeExclusive', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n","const vowels = ['a', 'e', 'i', 'o', 'u'];\n\nexport const aOrAn = (word: string) => {\n\treturn `${vowels.includes(word[0].toLowerCase()) ? 'an' : 'a'} ${word}`;\n};\n","export type TypedArray =\n\t| Int8Array\n\t| Uint8Array\n\t| Uint8ClampedArray\n\t| Int16Array\n\t| Uint16Array\n\t| Int32Array\n\t| Uint32Array\n\t| Float32Array\n\t| Float64Array\n\t| BigInt64Array\n\t| BigUint64Array;\n\nexport const TypedArrays = {\n\tInt8Array: (x: unknown): x is Int8Array => x instanceof Int8Array,\n\tUint8Array: (x: unknown): x is Uint8Array => x instanceof Uint8Array,\n\tUint8ClampedArray: (x: unknown): x is Uint8ClampedArray => x instanceof Uint8ClampedArray,\n\tInt16Array: (x: unknown): x is Int16Array => x instanceof Int16Array,\n\tUint16Array: (x: unknown): x is Uint16Array => x instanceof Uint16Array,\n\tInt32Array: (x: unknown): x is Int32Array => x instanceof Int32Array,\n\tUint32Array: (x: unknown): x is Uint32Array => x instanceof Uint32Array,\n\tFloat32Array: (x: unknown): x is Float32Array => x instanceof Float32Array,\n\tFloat64Array: (x: unknown): x is Float64Array => x instanceof Float64Array,\n\tBigInt64Array: (x: unknown): x is BigInt64Array => x instanceof BigInt64Array,\n\tBigUint64Array: (x: unknown): x is BigUint64Array => x instanceof BigUint64Array,\n\tTypedArray: (x: unknown): x is TypedArray => ArrayBuffer.isView(x) && !(x instanceof DataView)\n} as const;\n\nexport type TypedArrayName = keyof typeof TypedArrays;\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\ttypedArrayByteLengthEqual,\n\ttypedArrayByteLengthGreaterThan,\n\ttypedArrayByteLengthGreaterThanOrEqual,\n\ttypedArrayByteLengthLessThan,\n\ttypedArrayByteLengthLessThanOrEqual,\n\ttypedArrayByteLengthNotEqual,\n\ttypedArrayByteLengthRange,\n\ttypedArrayByteLengthRangeExclusive,\n\ttypedArrayByteLengthRangeInclusive,\n\ttypedArrayLengthEqual,\n\ttypedArrayLengthGreaterThan,\n\ttypedArrayLengthGreaterThanOrEqual,\n\ttypedArrayLengthLessThan,\n\ttypedArrayLengthLessThanOrEqual,\n\ttypedArrayLengthNotEqual,\n\ttypedArrayLengthRange,\n\ttypedArrayLengthRangeExclusive,\n\ttypedArrayLengthRangeInclusive\n} from '../constraints/TypedArrayLengthConstraints';\nimport { aOrAn } from '../constraints/util/common/vowels';\nimport { TypedArrays, type TypedArray, type TypedArrayName } from '../constraints/util/typedArray';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class TypedArrayValidator extends BaseValidator {\n\tprivate readonly type: TypedArrayName;\n\n\tpublic constructor(type: TypedArrayName, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.type = type;\n\t}\n\n\tpublic byteLengthLessThan(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthLessThan(length));\n\t}\n\n\tpublic byteLengthLessThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthLessThanOrEqual(length));\n\t}\n\n\tpublic byteLengthGreaterThan(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthGreaterThan(length));\n\t}\n\n\tpublic byteLengthGreaterThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthGreaterThanOrEqual(length));\n\t}\n\n\tpublic byteLengthEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthEqual(length));\n\t}\n\n\tpublic byteLengthNotEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthNotEqual(length));\n\t}\n\n\tpublic byteLengthRange(start: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRange(start, endBefore));\n\t}\n\n\tpublic byteLengthRangeInclusive(startAt: number, endAt: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRangeInclusive(startAt, endAt) as IConstraint);\n\t}\n\n\tpublic byteLengthRangeExclusive(startAfter: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRangeExclusive(startAfter, endBefore));\n\t}\n\n\tpublic lengthLessThan(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthLessThan(length));\n\t}\n\n\tpublic lengthLessThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthLessThanOrEqual(length));\n\t}\n\n\tpublic lengthGreaterThan(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthGreaterThan(length));\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthGreaterThanOrEqual(length));\n\t}\n\n\tpublic lengthEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthEqual(length));\n\t}\n\n\tpublic lengthNotEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthNotEqual(length));\n\t}\n\n\tpublic lengthRange(start: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayLengthRange(start, endBefore));\n\t}\n\n\tpublic lengthRangeInclusive(startAt: number, endAt: number) {\n\t\treturn this.addConstraint(typedArrayLengthRangeInclusive(startAt, endAt));\n\t}\n\n\tpublic lengthRangeExclusive(startAfter: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayLengthRangeExclusive(startAfter, endBefore));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.type, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn TypedArrays[this.type](value)\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.typedArray', `Expected ${aOrAn(this.type)}`, value));\n\t}\n}\n","import type { TypedArray, TypedArrayName } from '../constraints/util/typedArray';\nimport type { Unwrap, UnwrapTuple } from '../lib/util-types';\nimport {\n\tArrayValidator,\n\tBaseValidator,\n\tBigIntValidator,\n\tBooleanValidator,\n\tDateValidator,\n\tInstanceValidator,\n\tLiteralValidator,\n\tMapValidator,\n\tNeverValidator,\n\tNullishValidator,\n\tNumberValidator,\n\tObjectValidator,\n\tPassthroughValidator,\n\tRecordValidator,\n\tSetValidator,\n\tStringValidator,\n\tTupleValidator,\n\tUnionValidator\n} from '../validators/imports';\nimport { LazyValidator } from '../validators/LazyValidator';\nimport { NativeEnumValidator, type NativeEnumLike } from '../validators/NativeEnumValidator';\nimport { TypedArrayValidator } from '../validators/TypedArrayValidator';\nimport type { Constructor, MappedObjectValidator } from './util-types';\n\nexport class Shapes {\n\tpublic get string() {\n\t\treturn new StringValidator();\n\t}\n\n\tpublic get number() {\n\t\treturn new NumberValidator();\n\t}\n\n\tpublic get bigint() {\n\t\treturn new BigIntValidator();\n\t}\n\n\tpublic get boolean() {\n\t\treturn new BooleanValidator();\n\t}\n\n\tpublic get date() {\n\t\treturn new DateValidator();\n\t}\n\n\tpublic object(shape: MappedObjectValidator) {\n\t\treturn new ObjectValidator(shape);\n\t}\n\n\tpublic get undefined() {\n\t\treturn this.literal(undefined);\n\t}\n\n\tpublic get null() {\n\t\treturn this.literal(null);\n\t}\n\n\tpublic get nullish() {\n\t\treturn new NullishValidator();\n\t}\n\n\tpublic get any() {\n\t\treturn new PassthroughValidator();\n\t}\n\n\tpublic get unknown() {\n\t\treturn new PassthroughValidator();\n\t}\n\n\tpublic get never() {\n\t\treturn new NeverValidator();\n\t}\n\n\tpublic enum(...values: readonly T[]) {\n\t\treturn this.union(...values.map((value) => this.literal(value)));\n\t}\n\n\tpublic nativeEnum(enumShape: T): NativeEnumValidator {\n\t\treturn new NativeEnumValidator(enumShape);\n\t}\n\n\tpublic literal(value: T): BaseValidator {\n\t\tif (value instanceof Date) return this.date.equal(value) as unknown as BaseValidator;\n\t\treturn new LiteralValidator(value);\n\t}\n\n\tpublic instance(expected: Constructor): InstanceValidator {\n\t\treturn new InstanceValidator(expected);\n\t}\n\n\tpublic union[]]>(...validators: [...T]): UnionValidator> {\n\t\treturn new UnionValidator(validators);\n\t}\n\n\tpublic array(validator: BaseValidator): ArrayValidator;\n\tpublic array(validator: BaseValidator): ArrayValidator;\n\tpublic array(validator: BaseValidator) {\n\t\treturn new ArrayValidator(validator);\n\t}\n\n\tpublic typedArray(type: TypedArrayName = 'TypedArray') {\n\t\treturn new TypedArrayValidator(type);\n\t}\n\n\tpublic get int8Array() {\n\t\treturn this.typedArray('Int8Array');\n\t}\n\n\tpublic get uint8Array() {\n\t\treturn this.typedArray('Uint8Array');\n\t}\n\n\tpublic get uint8ClampedArray() {\n\t\treturn this.typedArray('Uint8ClampedArray');\n\t}\n\n\tpublic get int16Array() {\n\t\treturn this.typedArray('Int16Array');\n\t}\n\n\tpublic get uint16Array() {\n\t\treturn this.typedArray('Uint16Array');\n\t}\n\n\tpublic get int32Array() {\n\t\treturn this.typedArray('Int32Array');\n\t}\n\n\tpublic get uint32Array() {\n\t\treturn this.typedArray('Uint32Array');\n\t}\n\n\tpublic get float32Array() {\n\t\treturn this.typedArray('Float32Array');\n\t}\n\n\tpublic get float64Array() {\n\t\treturn this.typedArray('Float64Array');\n\t}\n\n\tpublic get bigInt64Array() {\n\t\treturn this.typedArray('BigInt64Array');\n\t}\n\n\tpublic get bigUint64Array() {\n\t\treturn this.typedArray('BigUint64Array');\n\t}\n\n\tpublic tuple[]]>(validators: [...T]): TupleValidator> {\n\t\treturn new TupleValidator(validators);\n\t}\n\n\tpublic set(validator: BaseValidator) {\n\t\treturn new SetValidator(validator);\n\t}\n\n\tpublic record(validator: BaseValidator) {\n\t\treturn new RecordValidator(validator);\n\t}\n\n\tpublic map(keyValidator: BaseValidator, valueValidator: BaseValidator) {\n\t\treturn new MapValidator(keyValidator, valueValidator);\n\t}\n\n\tpublic lazy>(validator: (value: unknown) => T) {\n\t\treturn new LazyValidator(validator);\n\t}\n}\n","import { Shapes } from './lib/Shapes';\n\nexport const s = new Shapes();\n\nexport * from './lib/Result';\nexport * from './lib/configs';\nexport * from './lib/errors/BaseError';\nexport * from './lib/errors/CombinedError';\nexport * from './lib/errors/CombinedPropertyError';\nexport * from './lib/errors/ExpectedConstraintError';\nexport * from './lib/errors/ExpectedValidationError';\nexport * from './lib/errors/MissingPropertyError';\nexport * from './lib/errors/MultiplePossibilitiesConstraintError';\nexport * from './lib/errors/UnknownEnumValueError';\nexport * from './lib/errors/UnknownPropertyError';\nexport * from './lib/errors/ValidationError';\nexport * from './type-exports';\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/shapeshift/package.json b/node_modules/@sapphire/shapeshift/package.json index 85012f9..cd7d6e6 100644 --- a/node_modules/@sapphire/shapeshift/package.json +++ b/node_modules/@sapphire/shapeshift/package.json @@ -1,6 +1,6 @@ { "name": "@sapphire/shapeshift", - "version": "3.8.1", + "version": "3.9.2", "description": "Blazing fast input validation and transformation ⚡", "author": "@sapphire", "license": "MIT", @@ -10,9 +10,9 @@ "unpkg": "dist/index.global.js", "types": "dist/index.d.ts", "exports": { + "types": "./dist/index.d.ts", "import": "./dist/index.mjs", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" + "require": "./dist/index.js" }, "sideEffects": false, "homepage": "https://www.sapphirejs.dev", @@ -21,8 +21,6 @@ "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", @@ -32,38 +30,42 @@ "prepack": "yarn build && pinst --disable", "postpack": "pinst --enable" }, + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, "devDependencies": { - "@commitlint/cli": "^17.3.0", - "@commitlint/config-conventional": "^17.3.0", - "@favware/cliff-jumper": "^1.9.0", + "@commitlint/cli": "^17.6.5", + "@commitlint/config-conventional": "^17.6.5", + "@favware/cliff-jumper": "^2.0.1", "@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", + "@sapphire/eslint-config": "^4.4.2", + "@sapphire/prettier-config": "^1.4.5", + "@sapphire/ts-config": "^4.0.0", + "@types/jsdom": "^21.1.1", + "@types/lodash": "^4.14.195", + "@types/node": "^18.16.16", + "@typescript-eslint/eslint-plugin": "^5.59.8", + "@typescript-eslint/parser": "^5.59.8", + "@vitest/coverage-c8": "^0.31.4", "cz-conventional-changelog": "^3.3.0", - "esbuild-plugins-node-modules-polyfill": "^1.0.7", - "eslint": "^8.29.0", - "eslint-config-prettier": "^8.5.0", + "esbuild-plugins-node-modules-polyfill": "^1.0.14", + "eslint": "^8.42.0", + "eslint-config-prettier": "^8.8.0", "eslint-plugin-prettier": "^4.2.1", - "husky": "^8.0.2", - "jsdom": "^20.0.3", - "lint-staged": "^13.1.0", + "husky": "^8.0.3", + "jsdom": "^22.1.0", + "lint-staged": "^13.2.2", "pinst": "^3.0.0", - "prettier": "^2.8.1", + "prettier": "^2.8.8", "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" + "tsup": "^6.7.0", + "typedoc": "^0.24.7", + "typedoc-json-parser": "^8.1.2", + "typescript": "^5.1.3", + "vite": "^4.3.9", + "vitest": "^0.31.4" }, "repository": { "type": "git", @@ -117,11 +119,7 @@ }, "resolutions": { "ansi-regex": "^5.0.1", - "minimist": "^1.2.7" + "minimist": "^1.2.8" }, - "packageManager": "yarn@3.3.0", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "lodash": "^4.17.21" - } + "packageManager": "yarn@3.6.0" } \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/CHANGELOG.md b/node_modules/@sapphire/snowflake/CHANGELOG.md index 42792aa..511b056 100644 --- a/node_modules/@sapphire/snowflake/CHANGELOG.md +++ b/node_modules/@sapphire/snowflake/CHANGELOG.md @@ -2,6 +2,37 @@ All notable changes to this project will be documented in this file. +# [@sapphire/snowflake@3.5.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.5.0...@sapphire/snowflake@3.5.1) - (2023-05-12) + +## 🏠 Refactor + +- **snowflake:** Handle out-of-bounds `increment` correctly (#596) ([b5276d7](https://github.com/sapphiredev/utilities/commit/b5276d7372c33356975a302bafb5ae8aba604431)) + +# [@sapphire/snowflake@3.5.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.4.3...@sapphire/snowflake@3.5.0) - (2023-05-10) + +## 🚀 Features + +- **snowflake:** Expose `processId` and `workerId` (#595) ([b873c1c](https://github.com/sapphiredev/utilities/commit/b873c1cc3b30cb54d710a49f7618e125ac1132ad)) + +# [@sapphire/snowflake@3.4.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.4.1...@sapphire/snowflake@3.4.2) - (2023-04-12) + +## 🏠 Refactor + +- **Snowflake:** Simplify `compare` logic (#578) ([886254e](https://github.com/sapphiredev/utilities/commit/886254eea2f0cc5e8f63d015acffaf0e61489357)) + +# [@sapphire/snowflake@3.4.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.4.0...@sapphire/snowflake@3.4.1) - (2023-04-10) + +## 🐛 Bug Fixes + +- **snowflake:** Ensure strings are never compared with bigints ([22199a5](https://github.com/sapphiredev/utilities/commit/22199a5aa0c6150f46e01bfbe328deecb9f818ba)) +- **deps:** Update all non-major dependencies (#577) ([291dd67](https://github.com/sapphiredev/utilities/commit/291dd6783e57d8f075ce566218ba076ef6c4bbbd)) +- **deps:** Update all non-major dependencies (#545) ([40ca040](https://github.com/sapphiredev/utilities/commit/40ca040a21d8a0949682051a3a974538183a400e)) +- **deps:** Update all non-major dependencies (#544) ([cc78f17](https://github.com/sapphiredev/utilities/commit/cc78f17390c7f3db08af92bf46a5a70a9c11dd5f)) + +## 🧪 Testing + +- Cleanup tests ([aec1bb2](https://github.com/sapphiredev/utilities/commit/aec1bb290d0f3c00a1ae4f4c86302ebbb161d348)) + # [@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 diff --git a/node_modules/@sapphire/snowflake/README.md b/node_modules/@sapphire/snowflake/README.md index e8d3089..c8f0901 100644 --- a/node_modules/@sapphire/snowflake/README.md +++ b/node_modules/@sapphire/snowflake/README.md @@ -1,6 +1,6 @@

-![Sapphire Logo](https://cdn.skyra.pw/gh-assets/sapphire-banner.png) +![Sapphire Logo](https://raw.githubusercontent.com/sapphiredev/assets/main/banners/SapphireCommunity.png) # @sapphire/snowflake @@ -157,78 +157,14 @@ We accept donations through Open Collective, Ko-fi, PayPal, Patreon and GitHub S | Patreon | [Click Here](https://sapphirejs.dev/patreon) | | PayPal | [Click Here](https://sapphirejs.dev/paypal) | -## Contributors ✨ +## Contributors -Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): +Please make sure to read the [Contributing Guide][contributing] before making a pull request. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Jeroen Claassens

💻 🚇 📆 📖 ⚠️

Aura Román

💻 📆 👀 ⚠️

Gryffon Bellish

💻 👀 ⚠️

Vlad Frangu

💻 🐛 👀 📓 ⚠️

Stitch07

💻 📆 ⚠️

depfu[bot]

🚧

allcontributors[bot]

📖

Tyler J Russell

📖

Ivan Lieder

💻 🐛

Hezekiah Hendry

💻 🔧

Vetlix

💻

Ethan Mitchell

📖

Elliot

💻

Jurien Hamaker

💻

Charalampos Fanoulis

📖

dependabot[bot]

🚧

Kaname

💻

nandhagk

🐛

megatank58

💻

UndiedGamer

💻

Lioness100

📖 💻

David

💻

renovate[bot]

🚧

WhiteSource Renovate

🚧

FC

💻

Jérémy de Saint Denis

💻

MrCube

💻

bitomic

💻

c43721

💻

Commandtechno

💻

Aura

💻

Jonathan

💻

Parbez

🚧

Paul Andrew

📖

Mzato

💻 🐛

Harry Allen

📖

Evo

💻

Enes Genç

💻

muchnameless

💻

Priyam

💻

Voxelli

💻

Cit The Dev

💻

Goestav

💻

DD

💻

amber

💻
+Thank you to all the people who already contributed to Sapphire! - - +
+ + - - -This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! +[contributing]: https://github.com/sapphiredev/.github/blob/main/.github/CONTRIBUTING.md diff --git a/node_modules/@sapphire/snowflake/dist/index.d.ts b/node_modules/@sapphire/snowflake/dist/index.d.ts index 398d957..76db741 100644 --- a/node_modules/@sapphire/snowflake/dist/index.d.ts +++ b/node_modules/@sapphire/snowflake/dist/index.d.ts @@ -1,3 +1,19 @@ +declare const IncrementSymbol: unique symbol; +declare const EpochSymbol: unique symbol; +declare const ProcessIdSymbol: unique symbol; +declare const WorkerIdSymbol: unique symbol; +/** + * The maximum value the `workerId` field accepts in snowflakes. + */ +declare const MaximumWorkerId = 31n; +/** + * The maximum value the `processId` field accepts in snowflakes. + */ +declare const MaximumProcessId = 31n; +/** + * The maximum value the `increment` field accepts in snowflakes. + */ +declare const MaximumIncrement = 4095n; /** * A class for generating and deconstructing Twitter snowflakes. * @@ -12,19 +28,56 @@ * ``` */ declare class Snowflake { - #private; /** * Alias for {@link deconstruct} */ decode: (id: string | bigint) => DeconstructedSnowflake; + /** + * Internal reference of the epoch passed in the constructor + * @internal + */ + private readonly [EpochSymbol]; + /** + * Internal incrementor for generating snowflakes + * @internal + */ + private [IncrementSymbol]; + /** + * The process ID that will be used by default in the generate method + * @internal + */ + private [ProcessIdSymbol]; + /** + * The worker ID that will be used by default in the generate method + * @internal + */ + private [WorkerIdSymbol]; /** * @param epoch the epoch to use */ constructor(epoch: number | bigint | Date); /** - * The epoch for this snowflake. + * The epoch for this snowflake */ get epoch(): bigint; + /** + * Gets the configured process ID + */ + get processId(): bigint; + /** + * Sets the process ID that will be used by default for the {@link generate} method + * @param value The new value, will be coerced to BigInt and masked with `0b11111n` + */ + set processId(value: number | bigint); + /** + * Gets the configured worker ID + */ + get workerId(): bigint; + /** + * Sets the worker ID that will be used by default for the {@link generate} method + * @param value The new value, will be coerced to BigInt and masked with `0b11111n` + */ + set workerId(value: number | bigint); /** * Generates a snowflake given an epoch and optionally a timestamp * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions} @@ -146,4 +199,4 @@ declare const DiscordSnowflake: Snowflake; */ declare const TwitterSnowflake: Snowflake; -export { DeconstructedSnowflake, DiscordSnowflake, Snowflake, SnowflakeGenerateOptions, TwitterSnowflake }; +export { DeconstructedSnowflake, DiscordSnowflake, MaximumIncrement, MaximumProcessId, MaximumWorkerId, Snowflake, SnowflakeGenerateOptions, TwitterSnowflake }; diff --git a/node_modules/@sapphire/snowflake/dist/index.global.js b/node_modules/@sapphire/snowflake/dist/index.global.js index bb4b1c1..dbcad34 100644 --- a/node_modules/@sapphire/snowflake/dist/index.global.js +++ b/node_modules/@sapphire/snowflake/dist/index.global.js @@ -8,48 +8,98 @@ var SapphireSnowflake = (function (exports) { __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 IncrementSymbol = Symbol("@sapphire/snowflake.increment"); + var EpochSymbol = Symbol("@sapphire/snowflake.epoch"); + var ProcessIdSymbol = Symbol("@sapphire/snowflake.processId"); + var WorkerIdSymbol = Symbol("@sapphire/snowflake.workerId"); + var MaximumWorkerId = 0b11111n; + var MaximumProcessId = 0b11111n; + var MaximumIncrement = 0b111111111111n; + var _a, _b, _c, _d; var Snowflake = class { + /** + * @param epoch the epoch to use + */ constructor(epoch) { + /** + * Alias for {@link deconstruct} + */ + // eslint-disable-next-line @typescript-eslint/unbound-method __publicField(this, "decode", this.deconstruct); - __privateAdd(this, _increment, 0n); - __privateAdd(this, _epoch, void 0); - __privateSet(this, _epoch, BigInt(epoch instanceof Date ? epoch.getTime() : epoch)); + /** + * Internal reference of the epoch passed in the constructor + * @internal + */ + __publicField(this, _a); + /** + * Internal incrementor for generating snowflakes + * @internal + */ + __publicField(this, _b, 0n); + /** + * The process ID that will be used by default in the generate method + * @internal + */ + __publicField(this, _c, 1n); + /** + * The worker ID that will be used by default in the generate method + * @internal + */ + __publicField(this, _d, 0n); + this[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch); } + /** + * The epoch for this snowflake + */ get epoch() { - return __privateGet(this, _epoch); + return this[EpochSymbol]; } - generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId } = {}) { + /** + * Gets the configured process ID + */ + get processId() { + return this[ProcessIdSymbol]; + } + /** + * Sets the process ID that will be used by default for the {@link generate} method + * @param value The new value, will be coerced to BigInt and masked with `0b11111n` + */ + set processId(value) { + this[ProcessIdSymbol] = BigInt(value) & MaximumProcessId; + } + /** + * Gets the configured worker ID + */ + get workerId() { + return this[WorkerIdSymbol]; + } + /** + * Sets the worker ID that will be used by default for the {@link generate} method + * @param value The new value, will be coerced to BigInt and masked with `0b11111n` + */ + set workerId(value) { + this[WorkerIdSymbol] = BigInt(value) & MaximumWorkerId; + } + /** + * 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 = Date.now(), + workerId = this[WorkerIdSymbol], + processId = this[ProcessIdSymbol] + } = {}) { if (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime()); else if (typeof timestamp === "number") @@ -57,43 +107,76 @@ var SapphireSnowflake = (function (exports) { 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); + if (typeof increment !== "bigint") { + increment = this[IncrementSymbol]; + this[IncrementSymbol] = increment + 1n & MaximumIncrement; } - return timestamp - __privateGet(this, _epoch) << 22n | (workerId & 0b11111n) << 17n | (processId & 0b11111n) << 12n | increment; + return timestamp - this[EpochSymbol] << 22n | (workerId & MaximumWorkerId) << 17n | (processId & MaximumProcessId) << 12n | increment & MaximumIncrement; } + /** + * 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) { const bigIntId = BigInt(id); + const epoch = this[EpochSymbol]; return { id: bigIntId, - timestamp: (bigIntId >> 22n) + __privateGet(this, _epoch), - workerId: bigIntId >> 17n & 0b11111n, - processId: bigIntId >> 12n & 0b11111n, - increment: bigIntId & 0b111111111111n, - epoch: __privateGet(this, _epoch) + timestamp: (bigIntId >> 22n) + epoch, + workerId: bigIntId >> 17n & MaximumWorkerId, + processId: bigIntId >> 12n & MaximumProcessId, + increment: bigIntId & MaximumIncrement, + epoch }; } + /** + * 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) { - return Number((BigInt(id) >> 22n) + __privateGet(this, _epoch)); + return Number((BigInt(id) >> 22n) + this[EpochSymbol]); } + /** + * 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, 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; + const typeA = typeof a; + return typeA === typeof b ? typeA === "string" ? cmpString(a, b) : cmpBigInt(a, b) : cmpBigInt(BigInt(a), BigInt(b)); } }; __name(Snowflake, "Snowflake"); - _increment = new WeakMap(); - _epoch = new WeakMap(); + _a = EpochSymbol, _b = IncrementSymbol, _c = ProcessIdSymbol, _d = WorkerIdSymbol; + function cmpBigInt(a, b) { + return a === b ? 0 : a < b ? -1 : 1; + } + __name(cmpBigInt, "cmpBigInt"); + function cmpString(a, b) { + return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1; + } + __name(cmpString, "cmpString"); // src/lib/DiscordSnowflake.ts var DiscordSnowflake = new Snowflake(1420070400000n); @@ -102,6 +185,9 @@ var SapphireSnowflake = (function (exports) { var TwitterSnowflake = new Snowflake(1288834974657n); exports.DiscordSnowflake = DiscordSnowflake; + exports.MaximumIncrement = MaximumIncrement; + exports.MaximumProcessId = MaximumProcessId; + exports.MaximumWorkerId = MaximumWorkerId; exports.Snowflake = Snowflake; exports.TwitterSnowflake = TwitterSnowflake; diff --git a/node_modules/@sapphire/snowflake/dist/index.global.js.map b/node_modules/@sapphire/snowflake/dist/index.global.js.map index 3a05a29..4204534 100644 --- a/node_modules/@sapphire/snowflake/dist/index.global.js.map +++ b/node_modules/@sapphire/snowflake/dist/index.global.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/lib/Snowflake.ts","../src/lib/DiscordSnowflake.ts","../src/lib/TwitterSnowflake.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAM,YAAY;AAClB,IAAM,WAAW;AADjB;AAgBO,IAAM,YAAN,MAAgB;AAAA,EAsBf,YAAY,OAA+B;AAjBlD,wBAAO,UAAS,KAAK;AAMrB,mCAAa;AAMb;AAMC,uBAAK,QAAS,OAAO,iBAAiB,OAAO,MAAM,QAAQ,IAAI,KAAK;AAAA,EACrE;AAAA,EAKA,IAAW,QAAgB;AAC1B,WAAO,mBAAK;AAAA,EACb;AAAA,EAcO,SAAS,EAAE,WAAW,YAAY,KAAK,IAAI,G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AAM,mBAAmB,IAAI,UAAU,cAAc;;;ACArD,IAAM,mBAAmB,IAAI,UAAU,cAAc","sourcesContent":["const ProcessId = 1n;\nconst WorkerId = 0n;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n */\nexport class Snowflake {\n\t/**\n\t * Alias for {@link deconstruct}\n\t */\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\tpublic decode = this.deconstruct;\n\n\t/**\n\t * Internal incrementor for generating snowflakes\n\t * @internal\n\t */\n\t#increment = 0n;\n\n\t/**\n\t * Internal reference of the epoch passed in the constructor\n\t * @internal\n\t */\n\t#epoch: bigint;\n\n\t/**\n\t * @param epoch the epoch to use\n\t */\n\tpublic constructor(epoch: number | bigint | Date) {\n\t\tthis.#epoch = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);\n\t}\n\n\t/**\n\t * The epoch for this snowflake.\n\t */\n\tpublic get epoch(): bigint {\n\t\treturn this.#epoch;\n\t}\n\n\t/**\n\t * Generates a snowflake given an epoch and optionally a timestamp\n\t * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}\n\t *\n\t * **note** when `increment` is not provided it defaults to the private `increment` of the instance\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).generate();\n\t * ```\n\t * @returns A unique snowflake\n\t */\n\tpublic generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId }: SnowflakeGenerateOptions = {}) {\n\t\tif (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());\n\t\telse if (typeof timestamp === 'number') timestamp = BigInt(timestamp);\n\t\telse if (typeof timestamp !== 'bigint') {\n\t\t\tthrow new TypeError(`\"timestamp\" argument must be a number, bigint, or Date (received ${typeof timestamp})`);\n\t\t}\n\n\t\tif (typeof increment === 'bigint' && increment >= 4095n) increment = 0n;\n\t\telse {\n\t\t\tincrement = this.#increment++;\n\t\t\tif (this.#increment >= 4095n) this.#increment = 0n;\n\t\t}\n\n\t\t// timestamp, workerId, processId, increment\n\t\treturn ((timestamp - this.#epoch) << 22n) | ((workerId & 0b11111n) << 17n) | ((processId & 0b11111n) << 12n) | increment;\n\t}\n\n\t/**\n\t * Deconstructs a snowflake given a snowflake ID\n\t * @param id the snowflake to deconstruct\n\t * @returns a deconstructed snowflake\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n\t * ```\n\t */\n\tpublic deconstruct(id: string | bigint): DeconstructedSnowflake {\n\t\tconst bigIntId = BigInt(id);\n\t\treturn {\n\t\t\tid: bigIntId,\n\t\t\ttimestamp: (bigIntId >> 22n) + this.#epoch,\n\t\t\tworkerId: (bigIntId >> 17n) & 0b11111n,\n\t\t\tprocessId: (bigIntId >> 12n) & 0b11111n,\n\t\t\tincrement: bigIntId & 0b111111111111n,\n\t\t\tepoch: this.#epoch\n\t\t};\n\t}\n\n\t/**\n\t * Retrieves the timestamp field's value from a snowflake.\n\t * @param id The snowflake to get the timestamp value from.\n\t * @returns The UNIX timestamp that is stored in `id`.\n\t */\n\tpublic timestampFrom(id: string | bigint): number {\n\t\treturn Number((BigInt(id) >> 22n) + this.#epoch);\n\t}\n\n\t/**\n\t * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n\t * snowflake in sort order.\n\t * @param a The first snowflake to compare.\n\t * @param b The second snowflake to compare.\n\t * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n\t * @example Sort snowflakes in ascending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => Snowflake.compare(a, b)));\n\t * // → ['254360814063058944', '737141877803057244', '1056191128120082432'];\n\t * ```\n\t * @example Sort snowflakes in descending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));\n\t * // → ['1056191128120082432', '737141877803057244', '254360814063058944'];\n\t * ```\n\t */\n\tpublic static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1 {\n\t\tif (typeof a === 'bigint' || typeof b === 'bigint') {\n\t\t\tif (typeof a === 'string') a = BigInt(a);\n\t\t\telse if (typeof b === 'string') b = BigInt(b);\n\t\t\treturn a === b ? 0 : a < b ? -1 : 1;\n\t\t}\n\n\t\treturn a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;\n\t}\n}\n\n/**\n * Options for Snowflake#generate\n */\nexport interface SnowflakeGenerateOptions {\n\t/**\n\t * Timestamp or date of the snowflake to generate\n\t * @default Date.now()\n\t */\n\ttimestamp?: number | bigint | Date;\n\n\t/**\n\t * The increment to use\n\t * @default 0n\n\t * @remark keep in mind that this bigint is auto-incremented between generate calls\n\t */\n\tincrement?: bigint;\n\n\t/**\n\t * The worker ID to use, will be truncated to 5 bits (0-31)\n\t * @default 0n\n\t */\n\tworkerId?: bigint;\n\n\t/**\n\t * The process ID to use, will be truncated to 5 bits (0-31)\n\t * @default 1n\n\t */\n\tprocessId?: bigint;\n}\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n\t/**\n\t * The id in BigInt form\n\t */\n\tid: bigint;\n\n\t/**\n\t * The timestamp stored in the snowflake\n\t */\n\ttimestamp: bigint;\n\n\t/**\n\t * The worker id stored in the snowflake\n\t */\n\tworkerId: bigint;\n\n\t/**\n\t * The process id stored in the snowflake\n\t */\n\tprocessId: bigint;\n\n\t/**\n\t * The increment stored in the snowflake\n\t */\n\tincrement: bigint;\n\n\t/**\n\t * The epoch to use in the snowflake\n\t */\n\tepoch: bigint;\n}\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Discord's snowflake epoch\n *\n * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}\n */\nexport const DiscordSnowflake = new Snowflake(1420070400000n);\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Twitter's snowflake epoch\n *\n * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}\n */\nexport const TwitterSnowflake = new Snowflake(1288834974657n);\n"]} \ No newline at end of file +{"version":3,"sources":["../src/lib/Snowflake.ts","../src/lib/DiscordSnowflake.ts","../src/lib/TwitterSnowflake.ts"],"names":[],"mappings":";;;;;;;;;AAAA,IAAM,kBAAkB,OAAO,+BAA+B;AAC9D,IAAM,cAAc,OAAO,2BAA2B;AACtD,IAAM,kBAAkB,OAAO,+BAA+B;AAC9D,IAAM,iBAAiB,OAAO,8BAA8B;AAKrD,IAAM,kBAAkB;AAKxB,IAAM,mBAAmB;AAKzB,IAAM,mBAAmB;AAlBhC;AAiCO,IAAM,YAAN,MAAgB;AAAA;AAAA;AAAA;AAAA,EAkCf,YAAY,OAA+B;AA7BlD;AAAA;AAAA;AAAA;AAAA,wBAAO,UAAS,KAAK;AAMrB;AAAA;AAAA;AAAA;AAAA,wBAAkB;AAMlB;AAAA;AAAA;AAAA;AAAA,wBAAS,IAAmB;AAM5B;AAAA;AAAA;AAAA;AAAA,wBAAS,IAAmB;AAM5B;AAAA;AAAA;AAAA;AAAA,wBAAS,IAAkB;AAM1B,SAAK,WAAW,IAAI,OAAO,iBAAiB,OAAO,MAAM,QAAQ,IAAI,KAAK;AAAA,EAC3E;AAAA;AAAA;AAAA;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AAO;AAAA,MACN,IAAI;AAAA,MACJ,YAAY,YAAY,OAAO;AAAA,MAC/B,UAAW,YAAY,MAAO;AAAA,MAC9B,WAAY,YAAY,MAAO;AAAA,MAC/B,WAAW,WAAW;AAAA,MACtB;AAAA,IACD;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,cAAc,IAA6B;AACjD,WAAO,QAAQ,OAAO,EAAE,KAAK,OAAO,KAAK,WAAW,CAAC;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBA,OAAc,QAAQ,GAAoB,GAAgC;AACzE,UAAM,QAAQ,OAAO;AACrB,WAAO,UAAU,OAAO,IACrB,UAAU,WACT,UAAU,GAAa,CAAW,IAClC,UAAU,GAAa,CAAW,IACnC,UAAU,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC;AAAA,EAClC;AACD;AA5Ka;AAWM,kBAMT,sBAMA,sBAMA;AAkJV,SAAS,UAAU,GAAW,GAAW;AACxC,SAAO,MAAM,IAAI,IAAI,IAAI,IAAI,KAAK;AACnC;AAFS;AAKT,SAAS,UAAU,GAAW,GAAW;AACxC,SAAO,MAAM,IAAI,IAAI,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,IAAI,IAAI,IAAI,KAAK;AACxF;AAFS;;;AC9MF,IAAM,mBAAmB,IAAI,UAAU,cAAc;;;ACArD,IAAM,mBAAmB,IAAI,UAAU,cAAc","sourcesContent":["const IncrementSymbol = Symbol('@sapphire/snowflake.increment');\nconst EpochSymbol = Symbol('@sapphire/snowflake.epoch');\nconst ProcessIdSymbol = Symbol('@sapphire/snowflake.processId');\nconst WorkerIdSymbol = Symbol('@sapphire/snowflake.workerId');\n\n/**\n * The maximum value the `workerId` field accepts in snowflakes.\n */\nexport const MaximumWorkerId = 0b11111n;\n\n/**\n * The maximum value the `processId` field accepts in snowflakes.\n */\nexport const MaximumProcessId = 0b11111n;\n\n/**\n * The maximum value the `increment` field accepts in snowflakes.\n */\nexport const MaximumIncrement = 0b111111111111n;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n */\nexport class Snowflake {\n\t/**\n\t * Alias for {@link deconstruct}\n\t */\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\tpublic decode = this.deconstruct;\n\n\t/**\n\t * Internal reference of the epoch passed in the constructor\n\t * @internal\n\t */\n\tprivate readonly [EpochSymbol]: bigint;\n\n\t/**\n\t * Internal incrementor for generating snowflakes\n\t * @internal\n\t */\n\tprivate [IncrementSymbol] = 0n;\n\n\t/**\n\t * The process ID that will be used by default in the generate method\n\t * @internal\n\t */\n\tprivate [ProcessIdSymbol] = 1n;\n\n\t/**\n\t * The worker ID that will be used by default in the generate method\n\t * @internal\n\t */\n\tprivate [WorkerIdSymbol] = 0n;\n\n\t/**\n\t * @param epoch the epoch to use\n\t */\n\tpublic constructor(epoch: number | bigint | Date) {\n\t\tthis[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);\n\t}\n\n\t/**\n\t * The epoch for this snowflake\n\t */\n\tpublic get epoch(): bigint {\n\t\treturn this[EpochSymbol];\n\t}\n\n\t/**\n\t * Gets the configured process ID\n\t */\n\tpublic get processId(): bigint {\n\t\treturn this[ProcessIdSymbol];\n\t}\n\n\t/**\n\t * Sets the process ID that will be used by default for the {@link generate} method\n\t * @param value The new value, will be coerced to BigInt and masked with `0b11111n`\n\t */\n\tpublic set processId(value: number | bigint) {\n\t\tthis[ProcessIdSymbol] = BigInt(value) & MaximumProcessId;\n\t}\n\n\t/**\n\t * Gets the configured worker ID\n\t */\n\tpublic get workerId(): bigint {\n\t\treturn this[WorkerIdSymbol];\n\t}\n\n\t/**\n\t * Sets the worker ID that will be used by default for the {@link generate} method\n\t * @param value The new value, will be coerced to BigInt and masked with `0b11111n`\n\t */\n\tpublic set workerId(value: number | bigint) {\n\t\tthis[WorkerIdSymbol] = BigInt(value) & MaximumWorkerId;\n\t}\n\n\t/**\n\t * Generates a snowflake given an epoch and optionally a timestamp\n\t * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}\n\t *\n\t * **note** when `increment` is not provided it defaults to the private `increment` of the instance\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).generate();\n\t * ```\n\t * @returns A unique snowflake\n\t */\n\tpublic generate({\n\t\tincrement,\n\t\ttimestamp = Date.now(),\n\t\tworkerId = this[WorkerIdSymbol],\n\t\tprocessId = this[ProcessIdSymbol]\n\t}: SnowflakeGenerateOptions = {}) {\n\t\tif (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());\n\t\telse if (typeof timestamp === 'number') timestamp = BigInt(timestamp);\n\t\telse if (typeof timestamp !== 'bigint') {\n\t\t\tthrow new TypeError(`\"timestamp\" argument must be a number, bigint, or Date (received ${typeof timestamp})`);\n\t\t}\n\n\t\tif (typeof increment !== 'bigint') {\n\t\t\tincrement = this[IncrementSymbol];\n\t\t\tthis[IncrementSymbol] = (increment + 1n) & MaximumIncrement;\n\t\t}\n\n\t\t// timestamp, workerId, processId, increment\n\t\treturn (\n\t\t\t((timestamp - this[EpochSymbol]) << 22n) |\n\t\t\t((workerId & MaximumWorkerId) << 17n) |\n\t\t\t((processId & MaximumProcessId) << 12n) |\n\t\t\t(increment & MaximumIncrement)\n\t\t);\n\t}\n\n\t/**\n\t * Deconstructs a snowflake given a snowflake ID\n\t * @param id the snowflake to deconstruct\n\t * @returns a deconstructed snowflake\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n\t * ```\n\t */\n\tpublic deconstruct(id: string | bigint): DeconstructedSnowflake {\n\t\tconst bigIntId = BigInt(id);\n\t\tconst epoch = this[EpochSymbol];\n\t\treturn {\n\t\t\tid: bigIntId,\n\t\t\ttimestamp: (bigIntId >> 22n) + epoch,\n\t\t\tworkerId: (bigIntId >> 17n) & MaximumWorkerId,\n\t\t\tprocessId: (bigIntId >> 12n) & MaximumProcessId,\n\t\t\tincrement: bigIntId & MaximumIncrement,\n\t\t\tepoch\n\t\t};\n\t}\n\n\t/**\n\t * Retrieves the timestamp field's value from a snowflake.\n\t * @param id The snowflake to get the timestamp value from.\n\t * @returns The UNIX timestamp that is stored in `id`.\n\t */\n\tpublic timestampFrom(id: string | bigint): number {\n\t\treturn Number((BigInt(id) >> 22n) + this[EpochSymbol]);\n\t}\n\n\t/**\n\t * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n\t * snowflake in sort order.\n\t * @param a The first snowflake to compare.\n\t * @param b The second snowflake to compare.\n\t * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n\t * @example Sort snowflakes in ascending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => Snowflake.compare(a, b)));\n\t * // → ['254360814063058944', '737141877803057244', '1056191128120082432'];\n\t * ```\n\t * @example Sort snowflakes in descending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));\n\t * // → ['1056191128120082432', '737141877803057244', '254360814063058944'];\n\t * ```\n\t */\n\tpublic static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1 {\n\t\tconst typeA = typeof a;\n\t\treturn typeA === typeof b\n\t\t\t? typeA === 'string'\n\t\t\t\t? cmpString(a as string, b as string)\n\t\t\t\t: cmpBigInt(a as bigint, b as bigint)\n\t\t\t: cmpBigInt(BigInt(a), BigInt(b));\n\t}\n}\n\n/** @internal */\nfunction cmpBigInt(a: bigint, b: bigint) {\n\treturn a === b ? 0 : a < b ? -1 : 1;\n}\n\n/** @internal */\nfunction cmpString(a: string, b: string) {\n\treturn a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;\n}\n\n/**\n * Options for Snowflake#generate\n */\nexport interface SnowflakeGenerateOptions {\n\t/**\n\t * Timestamp or date of the snowflake to generate\n\t * @default Date.now()\n\t */\n\ttimestamp?: number | bigint | Date;\n\n\t/**\n\t * The increment to use\n\t * @default 0n\n\t * @remark keep in mind that this bigint is auto-incremented between generate calls\n\t */\n\tincrement?: bigint;\n\n\t/**\n\t * The worker ID to use, will be truncated to 5 bits (0-31)\n\t * @default 0n\n\t */\n\tworkerId?: bigint;\n\n\t/**\n\t * The process ID to use, will be truncated to 5 bits (0-31)\n\t * @default 1n\n\t */\n\tprocessId?: bigint;\n}\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n\t/**\n\t * The id in BigInt form\n\t */\n\tid: bigint;\n\n\t/**\n\t * The timestamp stored in the snowflake\n\t */\n\ttimestamp: bigint;\n\n\t/**\n\t * The worker id stored in the snowflake\n\t */\n\tworkerId: bigint;\n\n\t/**\n\t * The process id stored in the snowflake\n\t */\n\tprocessId: bigint;\n\n\t/**\n\t * The increment stored in the snowflake\n\t */\n\tincrement: bigint;\n\n\t/**\n\t * The epoch to use in the snowflake\n\t */\n\tepoch: bigint;\n}\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Discord's snowflake epoch\n *\n * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}\n */\nexport const DiscordSnowflake = new Snowflake(1420070400000n);\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Twitter's snowflake epoch\n *\n * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}\n */\nexport const TwitterSnowflake = new Snowflake(1288834974657n);\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/dist/index.js b/node_modules/@sapphire/snowflake/dist/index.js index fd76743..4cfad2a 100644 --- a/node_modules/@sapphire/snowflake/dist/index.js +++ b/node_modules/@sapphire/snowflake/dist/index.js @@ -7,48 +7,98 @@ 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 IncrementSymbol = Symbol("@sapphire/snowflake.increment"); +var EpochSymbol = Symbol("@sapphire/snowflake.epoch"); +var ProcessIdSymbol = Symbol("@sapphire/snowflake.processId"); +var WorkerIdSymbol = Symbol("@sapphire/snowflake.workerId"); +var MaximumWorkerId = 0b11111n; +var MaximumProcessId = 0b11111n; +var MaximumIncrement = 0b111111111111n; +var _a, _b, _c, _d; var Snowflake = class { + /** + * @param epoch the epoch to use + */ constructor(epoch) { + /** + * Alias for {@link deconstruct} + */ + // eslint-disable-next-line @typescript-eslint/unbound-method __publicField(this, "decode", this.deconstruct); - __privateAdd(this, _increment, 0n); - __privateAdd(this, _epoch, void 0); - __privateSet(this, _epoch, BigInt(epoch instanceof Date ? epoch.getTime() : epoch)); + /** + * Internal reference of the epoch passed in the constructor + * @internal + */ + __publicField(this, _a); + /** + * Internal incrementor for generating snowflakes + * @internal + */ + __publicField(this, _b, 0n); + /** + * The process ID that will be used by default in the generate method + * @internal + */ + __publicField(this, _c, 1n); + /** + * The worker ID that will be used by default in the generate method + * @internal + */ + __publicField(this, _d, 0n); + this[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch); } + /** + * The epoch for this snowflake + */ get epoch() { - return __privateGet(this, _epoch); + return this[EpochSymbol]; } - generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId } = {}) { + /** + * Gets the configured process ID + */ + get processId() { + return this[ProcessIdSymbol]; + } + /** + * Sets the process ID that will be used by default for the {@link generate} method + * @param value The new value, will be coerced to BigInt and masked with `0b11111n` + */ + set processId(value) { + this[ProcessIdSymbol] = BigInt(value) & MaximumProcessId; + } + /** + * Gets the configured worker ID + */ + get workerId() { + return this[WorkerIdSymbol]; + } + /** + * Sets the worker ID that will be used by default for the {@link generate} method + * @param value The new value, will be coerced to BigInt and masked with `0b11111n` + */ + set workerId(value) { + this[WorkerIdSymbol] = BigInt(value) & MaximumWorkerId; + } + /** + * 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 = Date.now(), + workerId = this[WorkerIdSymbol], + processId = this[ProcessIdSymbol] + } = {}) { if (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime()); else if (typeof timestamp === "number") @@ -56,43 +106,76 @@ var Snowflake = class { 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); + if (typeof increment !== "bigint") { + increment = this[IncrementSymbol]; + this[IncrementSymbol] = increment + 1n & MaximumIncrement; } - return timestamp - __privateGet(this, _epoch) << 22n | (workerId & 0b11111n) << 17n | (processId & 0b11111n) << 12n | increment; + return timestamp - this[EpochSymbol] << 22n | (workerId & MaximumWorkerId) << 17n | (processId & MaximumProcessId) << 12n | increment & MaximumIncrement; } + /** + * 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) { const bigIntId = BigInt(id); + const epoch = this[EpochSymbol]; return { id: bigIntId, - timestamp: (bigIntId >> 22n) + __privateGet(this, _epoch), - workerId: bigIntId >> 17n & 0b11111n, - processId: bigIntId >> 12n & 0b11111n, - increment: bigIntId & 0b111111111111n, - epoch: __privateGet(this, _epoch) + timestamp: (bigIntId >> 22n) + epoch, + workerId: bigIntId >> 17n & MaximumWorkerId, + processId: bigIntId >> 12n & MaximumProcessId, + increment: bigIntId & MaximumIncrement, + epoch }; } + /** + * 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) { - return Number((BigInt(id) >> 22n) + __privateGet(this, _epoch)); + return Number((BigInt(id) >> 22n) + this[EpochSymbol]); } + /** + * 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, 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; + const typeA = typeof a; + return typeA === typeof b ? typeA === "string" ? cmpString(a, b) : cmpBigInt(a, b) : cmpBigInt(BigInt(a), BigInt(b)); } }; __name(Snowflake, "Snowflake"); -_increment = new WeakMap(); -_epoch = new WeakMap(); +_a = EpochSymbol, _b = IncrementSymbol, _c = ProcessIdSymbol, _d = WorkerIdSymbol; +function cmpBigInt(a, b) { + return a === b ? 0 : a < b ? -1 : 1; +} +__name(cmpBigInt, "cmpBigInt"); +function cmpString(a, b) { + return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1; +} +__name(cmpString, "cmpString"); // src/lib/DiscordSnowflake.ts var DiscordSnowflake = new Snowflake(1420070400000n); @@ -101,6 +184,9 @@ var DiscordSnowflake = new Snowflake(1420070400000n); var TwitterSnowflake = new Snowflake(1288834974657n); exports.DiscordSnowflake = DiscordSnowflake; +exports.MaximumIncrement = MaximumIncrement; +exports.MaximumProcessId = MaximumProcessId; +exports.MaximumWorkerId = MaximumWorkerId; exports.Snowflake = Snowflake; exports.TwitterSnowflake = TwitterSnowflake; //# sourceMappingURL=out.js.map diff --git a/node_modules/@sapphire/snowflake/dist/index.js.map b/node_modules/@sapphire/snowflake/dist/index.js.map index 3a05a29..4204534 100644 --- a/node_modules/@sapphire/snowflake/dist/index.js.map +++ b/node_modules/@sapphire/snowflake/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/lib/Snowflake.ts","../src/lib/DiscordSnowflake.ts","../src/lib/TwitterSnowflake.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAM,YAAY;AAClB,IAAM,WAAW;AADjB;AAgBO,IAAM,YAAN,MAAgB;AAAA,EAsBf,YAAY,OAA+B;AAjBlD,wBAAO,UAAS,KAAK;AAMrB,mCAAa;AAMb;AAMC,uBAAK,QAAS,OAAO,iBAAiB,OAAO,MAAM,QAAQ,IAAI,KAAK;AAAA,EACrE;AAAA,EAKA,IAAW,QAAgB;AAC1B,WAAO,mBAAK;AAAA,EACb;AAAA,EAcO,SAAS,EAAE,WAAW,YAAY,KAAK,IAAI,GAAG,WAAW,UAAU,YAAY,UAAU,IAA8B,CAAC,GAAG;AACjI,QAAI,qBAAqB;AAAM,kBAAY,OAAO,UAAU,QAAQ,CAAC;AAAA,aAC5D,OAAO,cAAc;AAAU,kBAAY,OAAO,SAAS;AAAA,aAC3D,OAAO,cAAc,UAAU;AACvC,YAAM,IAAI,UAAU,oEAAoE,OAAO,YAAY;AAAA,IAC5G;AAEA,QAAI,OAAO,cAAc,YAAY,aAAa;AAAO,kBAAY;AAAA,SAChE;AACJ,kBAAY,uBAAK,YAAL;AACZ,UAAI,mBAAK,eAAc;AAAO,2BAAK,YAAa;AAAA,IACjD;AAGA,WAAS,YAAY,mBAAK,WAAW,OAAS,WAAW,aAAa,OAAS,YAAY,aAAa,MAAO;AAAA,EAChH;AAAA,EAYO,YAAY,IAA6C;AAC/D,UAAM,WAAW,OAAO,EAAE;AAC1B,WAAO;AAAA,MACN,IAAI;AAAA,MACJ,YAAY,YAAY,OAAO,mBAAK;AAAA,MACpC,UAAW,YAAY,MAAO;AAAA,MAC9B,WAAY,YAAY,MAAO;AAAA,MAC/B,WAAW,WAAW;AAAA,MACtB,OAAO,mBAAK;AAAA,IACb;AAAA,EACD;AAAA,EAOO,cAAc,IAA6B;AACjD,WAAO,QAAQ,OAAO,EAAE,KAAK,OAAO,mBAAK,OAAM;AAAA,EAChD;AAAA,EAqBA,OAAc,QAAQ,GAAoB,GAAgC;AACzE,QAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU;AACnD,UAAI,OAAO,MAAM;AAAU,YAAI,OAAO,CAAC;AAAA,eAC9B,OAAO,MAAM;AAAU,YAAI,OAAO,CAAC;AAC5C,aAAO,MAAM,IAAI,IAAI,IAAI,IAAI,KAAK;AAAA,IACnC;AAEA,WAAO,MAAM,IAAI,IAAI,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,IAAI,IAAI,IAAI,KAAK;AAAA,EACxF;AACD;AAzHa;AAWZ;AAMA;;;AC1BM,IAAM,mBAAmB,IAAI,UAAU,cAAc;;;ACArD,IAAM,mBAAmB,IAAI,UAAU,cAAc","sourcesContent":["const ProcessId = 1n;\nconst WorkerId = 0n;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n */\nexport class Snowflake {\n\t/**\n\t * Alias for {@link deconstruct}\n\t */\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\tpublic decode = this.deconstruct;\n\n\t/**\n\t * Internal incrementor for generating snowflakes\n\t * @internal\n\t */\n\t#increment = 0n;\n\n\t/**\n\t * Internal reference of the epoch passed in the constructor\n\t * @internal\n\t */\n\t#epoch: bigint;\n\n\t/**\n\t * @param epoch the epoch to use\n\t */\n\tpublic constructor(epoch: number | bigint | Date) {\n\t\tthis.#epoch = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);\n\t}\n\n\t/**\n\t * The epoch for this snowflake.\n\t */\n\tpublic get epoch(): bigint {\n\t\treturn this.#epoch;\n\t}\n\n\t/**\n\t * Generates a snowflake given an epoch and optionally a timestamp\n\t * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}\n\t *\n\t * **note** when `increment` is not provided it defaults to the private `increment` of the instance\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).generate();\n\t * ```\n\t * @returns A unique snowflake\n\t */\n\tpublic generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId }: SnowflakeGenerateOptions = {}) {\n\t\tif (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());\n\t\telse if (typeof timestamp === 'number') timestamp = BigInt(timestamp);\n\t\telse if (typeof timestamp !== 'bigint') {\n\t\t\tthrow new TypeError(`\"timestamp\" argument must be a number, bigint, or Date (received ${typeof timestamp})`);\n\t\t}\n\n\t\tif (typeof increment === 'bigint' && increment >= 4095n) increment = 0n;\n\t\telse {\n\t\t\tincrement = this.#increment++;\n\t\t\tif (this.#increment >= 4095n) this.#increment = 0n;\n\t\t}\n\n\t\t// timestamp, workerId, processId, increment\n\t\treturn ((timestamp - this.#epoch) << 22n) | ((workerId & 0b11111n) << 17n) | ((processId & 0b11111n) << 12n) | increment;\n\t}\n\n\t/**\n\t * Deconstructs a snowflake given a snowflake ID\n\t * @param id the snowflake to deconstruct\n\t * @returns a deconstructed snowflake\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n\t * ```\n\t */\n\tpublic deconstruct(id: string | bigint): DeconstructedSnowflake {\n\t\tconst bigIntId = BigInt(id);\n\t\treturn {\n\t\t\tid: bigIntId,\n\t\t\ttimestamp: (bigIntId >> 22n) + this.#epoch,\n\t\t\tworkerId: (bigIntId >> 17n) & 0b11111n,\n\t\t\tprocessId: (bigIntId >> 12n) & 0b11111n,\n\t\t\tincrement: bigIntId & 0b111111111111n,\n\t\t\tepoch: this.#epoch\n\t\t};\n\t}\n\n\t/**\n\t * Retrieves the timestamp field's value from a snowflake.\n\t * @param id The snowflake to get the timestamp value from.\n\t * @returns The UNIX timestamp that is stored in `id`.\n\t */\n\tpublic timestampFrom(id: string | bigint): number {\n\t\treturn Number((BigInt(id) >> 22n) + this.#epoch);\n\t}\n\n\t/**\n\t * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n\t * snowflake in sort order.\n\t * @param a The first snowflake to compare.\n\t * @param b The second snowflake to compare.\n\t * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n\t * @example Sort snowflakes in ascending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => Snowflake.compare(a, b)));\n\t * // → ['254360814063058944', '737141877803057244', '1056191128120082432'];\n\t * ```\n\t * @example Sort snowflakes in descending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));\n\t * // → ['1056191128120082432', '737141877803057244', '254360814063058944'];\n\t * ```\n\t */\n\tpublic static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1 {\n\t\tif (typeof a === 'bigint' || typeof b === 'bigint') {\n\t\t\tif (typeof a === 'string') a = BigInt(a);\n\t\t\telse if (typeof b === 'string') b = BigInt(b);\n\t\t\treturn a === b ? 0 : a < b ? -1 : 1;\n\t\t}\n\n\t\treturn a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;\n\t}\n}\n\n/**\n * Options for Snowflake#generate\n */\nexport interface SnowflakeGenerateOptions {\n\t/**\n\t * Timestamp or date of the snowflake to generate\n\t * @default Date.now()\n\t */\n\ttimestamp?: number | bigint | Date;\n\n\t/**\n\t * The increment to use\n\t * @default 0n\n\t * @remark keep in mind that this bigint is auto-incremented between generate calls\n\t */\n\tincrement?: bigint;\n\n\t/**\n\t * The worker ID to use, will be truncated to 5 bits (0-31)\n\t * @default 0n\n\t */\n\tworkerId?: bigint;\n\n\t/**\n\t * The process ID to use, will be truncated to 5 bits (0-31)\n\t * @default 1n\n\t */\n\tprocessId?: bigint;\n}\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n\t/**\n\t * The id in BigInt form\n\t */\n\tid: bigint;\n\n\t/**\n\t * The timestamp stored in the snowflake\n\t */\n\ttimestamp: bigint;\n\n\t/**\n\t * The worker id stored in the snowflake\n\t */\n\tworkerId: bigint;\n\n\t/**\n\t * The process id stored in the snowflake\n\t */\n\tprocessId: bigint;\n\n\t/**\n\t * The increment stored in the snowflake\n\t */\n\tincrement: bigint;\n\n\t/**\n\t * The epoch to use in the snowflake\n\t */\n\tepoch: bigint;\n}\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Discord's snowflake epoch\n *\n * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}\n */\nexport const DiscordSnowflake = new Snowflake(1420070400000n);\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Twitter's snowflake epoch\n *\n * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}\n */\nexport const TwitterSnowflake = new Snowflake(1288834974657n);\n"]} \ No newline at end of file +{"version":3,"sources":["../src/lib/Snowflake.ts","../src/lib/DiscordSnowflake.ts","../src/lib/TwitterSnowflake.ts"],"names":[],"mappings":";;;;;;;;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AA,EAClC;AACD;AA5Ka;AAWM,kBAMT,sBAMA,sBAMA;AAkJV,SAAS,UAAU,GAAW,GAAW;AACxC,SAAO,MAAM,IAAI,IAAI,IAAI,IAAI,KAAK;AACnC;AAFS;AAKT,SAAS,UAAU,GAAW,GAAW;AACxC,SAAO,MAAM,IAAI,IAAI,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,IAAI,IAAI,IAAI,KAAK;AACxF;AAFS;;;AC9MF,IAAM,mBAAmB,IAAI,UAAU,cAAc;;;ACArD,IAAM,mBAAmB,IAAI,UAAU,cAAc","sourcesContent":["const IncrementSymbol = Symbol('@sapphire/snowflake.increment');\nconst EpochSymbol = Symbol('@sapphire/snowflake.epoch');\nconst ProcessIdSymbol = Symbol('@sapphire/snowflake.processId');\nconst WorkerIdSymbol = Symbol('@sapphire/snowflake.workerId');\n\n/**\n * The maximum value the `workerId` field accepts in snowflakes.\n */\nexport const MaximumWorkerId = 0b11111n;\n\n/**\n * The maximum value the `processId` field accepts in snowflakes.\n */\nexport const MaximumProcessId = 0b11111n;\n\n/**\n * The maximum value the `increment` field accepts in snowflakes.\n */\nexport const MaximumIncrement = 0b111111111111n;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n */\nexport class Snowflake {\n\t/**\n\t * Alias for {@link deconstruct}\n\t */\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\tpublic decode = this.deconstruct;\n\n\t/**\n\t * Internal reference of the epoch passed in the constructor\n\t * @internal\n\t */\n\tprivate readonly [EpochSymbol]: bigint;\n\n\t/**\n\t * Internal incrementor for generating snowflakes\n\t * @internal\n\t */\n\tprivate [IncrementSymbol] = 0n;\n\n\t/**\n\t * The process ID that will be used by default in the generate method\n\t * @internal\n\t */\n\tprivate [ProcessIdSymbol] = 1n;\n\n\t/**\n\t * The worker ID that will be used by default in the generate method\n\t * @internal\n\t */\n\tprivate [WorkerIdSymbol] = 0n;\n\n\t/**\n\t * @param epoch the epoch to use\n\t */\n\tpublic constructor(epoch: number | bigint | Date) {\n\t\tthis[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);\n\t}\n\n\t/**\n\t * The epoch for this snowflake\n\t */\n\tpublic get epoch(): bigint {\n\t\treturn this[EpochSymbol];\n\t}\n\n\t/**\n\t * Gets the configured process ID\n\t */\n\tpublic get processId(): bigint {\n\t\treturn this[ProcessIdSymbol];\n\t}\n\n\t/**\n\t * Sets the process ID that will be used by default for the {@link generate} method\n\t * @param value The new value, will be coerced to BigInt and masked with `0b11111n`\n\t */\n\tpublic set processId(value: number | bigint) {\n\t\tthis[ProcessIdSymbol] = BigInt(value) & MaximumProcessId;\n\t}\n\n\t/**\n\t * Gets the configured worker ID\n\t */\n\tpublic get workerId(): bigint {\n\t\treturn this[WorkerIdSymbol];\n\t}\n\n\t/**\n\t * Sets the worker ID that will be used by default for the {@link generate} method\n\t * @param value The new value, will be coerced to BigInt and masked with `0b11111n`\n\t */\n\tpublic set workerId(value: number | bigint) {\n\t\tthis[WorkerIdSymbol] = BigInt(value) & MaximumWorkerId;\n\t}\n\n\t/**\n\t * Generates a snowflake given an epoch and optionally a timestamp\n\t * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}\n\t *\n\t * **note** when `increment` is not provided it defaults to the private `increment` of the instance\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).generate();\n\t * ```\n\t * @returns A unique snowflake\n\t */\n\tpublic generate({\n\t\tincrement,\n\t\ttimestamp = Date.now(),\n\t\tworkerId = this[WorkerIdSymbol],\n\t\tprocessId = this[ProcessIdSymbol]\n\t}: SnowflakeGenerateOptions = {}) {\n\t\tif (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());\n\t\telse if (typeof timestamp === 'number') timestamp = BigInt(timestamp);\n\t\telse if (typeof timestamp !== 'bigint') {\n\t\t\tthrow new TypeError(`\"timestamp\" argument must be a number, bigint, or Date (received ${typeof timestamp})`);\n\t\t}\n\n\t\tif (typeof increment !== 'bigint') {\n\t\t\tincrement = this[IncrementSymbol];\n\t\t\tthis[IncrementSymbol] = (increment + 1n) & MaximumIncrement;\n\t\t}\n\n\t\t// timestamp, workerId, processId, increment\n\t\treturn (\n\t\t\t((timestamp - this[EpochSymbol]) << 22n) |\n\t\t\t((workerId & MaximumWorkerId) << 17n) |\n\t\t\t((processId & MaximumProcessId) << 12n) |\n\t\t\t(increment & MaximumIncrement)\n\t\t);\n\t}\n\n\t/**\n\t * Deconstructs a snowflake given a snowflake ID\n\t * @param id the snowflake to deconstruct\n\t * @returns a deconstructed snowflake\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n\t * ```\n\t */\n\tpublic deconstruct(id: string | bigint): DeconstructedSnowflake {\n\t\tconst bigIntId = BigInt(id);\n\t\tconst epoch = this[EpochSymbol];\n\t\treturn {\n\t\t\tid: bigIntId,\n\t\t\ttimestamp: (bigIntId >> 22n) + epoch,\n\t\t\tworkerId: (bigIntId >> 17n) & MaximumWorkerId,\n\t\t\tprocessId: (bigIntId >> 12n) & MaximumProcessId,\n\t\t\tincrement: bigIntId & MaximumIncrement,\n\t\t\tepoch\n\t\t};\n\t}\n\n\t/**\n\t * Retrieves the timestamp field's value from a snowflake.\n\t * @param id The snowflake to get the timestamp value from.\n\t * @returns The UNIX timestamp that is stored in `id`.\n\t */\n\tpublic timestampFrom(id: string | bigint): number {\n\t\treturn Number((BigInt(id) >> 22n) + this[EpochSymbol]);\n\t}\n\n\t/**\n\t * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n\t * snowflake in sort order.\n\t * @param a The first snowflake to compare.\n\t * @param b The second snowflake to compare.\n\t * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n\t * @example Sort snowflakes in ascending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => Snowflake.compare(a, b)));\n\t * // → ['254360814063058944', '737141877803057244', '1056191128120082432'];\n\t * ```\n\t * @example Sort snowflakes in descending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));\n\t * // → ['1056191128120082432', '737141877803057244', '254360814063058944'];\n\t * ```\n\t */\n\tpublic static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1 {\n\t\tconst typeA = typeof a;\n\t\treturn typeA === typeof b\n\t\t\t? typeA === 'string'\n\t\t\t\t? cmpString(a as string, b as string)\n\t\t\t\t: cmpBigInt(a as bigint, b as bigint)\n\t\t\t: cmpBigInt(BigInt(a), BigInt(b));\n\t}\n}\n\n/** @internal */\nfunction cmpBigInt(a: bigint, b: bigint) {\n\treturn a === b ? 0 : a < b ? -1 : 1;\n}\n\n/** @internal */\nfunction cmpString(a: string, b: string) {\n\treturn a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;\n}\n\n/**\n * Options for Snowflake#generate\n */\nexport interface SnowflakeGenerateOptions {\n\t/**\n\t * Timestamp or date of the snowflake to generate\n\t * @default Date.now()\n\t */\n\ttimestamp?: number | bigint | Date;\n\n\t/**\n\t * The increment to use\n\t * @default 0n\n\t * @remark keep in mind that this bigint is auto-incremented between generate calls\n\t */\n\tincrement?: bigint;\n\n\t/**\n\t * The worker ID to use, will be truncated to 5 bits (0-31)\n\t * @default 0n\n\t */\n\tworkerId?: bigint;\n\n\t/**\n\t * The process ID to use, will be truncated to 5 bits (0-31)\n\t * @default 1n\n\t */\n\tprocessId?: bigint;\n}\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n\t/**\n\t * The id in BigInt form\n\t */\n\tid: bigint;\n\n\t/**\n\t * The timestamp stored in the snowflake\n\t */\n\ttimestamp: bigint;\n\n\t/**\n\t * The worker id stored in the snowflake\n\t */\n\tworkerId: bigint;\n\n\t/**\n\t * The process id stored in the snowflake\n\t */\n\tprocessId: bigint;\n\n\t/**\n\t * The increment stored in the snowflake\n\t */\n\tincrement: bigint;\n\n\t/**\n\t * The epoch to use in the snowflake\n\t */\n\tepoch: bigint;\n}\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Discord's snowflake epoch\n *\n * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}\n */\nexport const DiscordSnowflake = new Snowflake(1420070400000n);\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Twitter's snowflake epoch\n *\n * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}\n */\nexport const TwitterSnowflake = new Snowflake(1288834974657n);\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/dist/index.mjs b/node_modules/@sapphire/snowflake/dist/index.mjs index cdef2f9..7cfbfd7 100644 --- a/node_modules/@sapphire/snowflake/dist/index.mjs +++ b/node_modules/@sapphire/snowflake/dist/index.mjs @@ -5,48 +5,98 @@ 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 IncrementSymbol = Symbol("@sapphire/snowflake.increment"); +var EpochSymbol = Symbol("@sapphire/snowflake.epoch"); +var ProcessIdSymbol = Symbol("@sapphire/snowflake.processId"); +var WorkerIdSymbol = Symbol("@sapphire/snowflake.workerId"); +var MaximumWorkerId = 0b11111n; +var MaximumProcessId = 0b11111n; +var MaximumIncrement = 0b111111111111n; +var _a, _b, _c, _d; var Snowflake = class { + /** + * @param epoch the epoch to use + */ constructor(epoch) { + /** + * Alias for {@link deconstruct} + */ + // eslint-disable-next-line @typescript-eslint/unbound-method __publicField(this, "decode", this.deconstruct); - __privateAdd(this, _increment, 0n); - __privateAdd(this, _epoch, void 0); - __privateSet(this, _epoch, BigInt(epoch instanceof Date ? epoch.getTime() : epoch)); + /** + * Internal reference of the epoch passed in the constructor + * @internal + */ + __publicField(this, _a); + /** + * Internal incrementor for generating snowflakes + * @internal + */ + __publicField(this, _b, 0n); + /** + * The process ID that will be used by default in the generate method + * @internal + */ + __publicField(this, _c, 1n); + /** + * The worker ID that will be used by default in the generate method + * @internal + */ + __publicField(this, _d, 0n); + this[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch); } + /** + * The epoch for this snowflake + */ get epoch() { - return __privateGet(this, _epoch); + return this[EpochSymbol]; } - generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId } = {}) { + /** + * Gets the configured process ID + */ + get processId() { + return this[ProcessIdSymbol]; + } + /** + * Sets the process ID that will be used by default for the {@link generate} method + * @param value The new value, will be coerced to BigInt and masked with `0b11111n` + */ + set processId(value) { + this[ProcessIdSymbol] = BigInt(value) & MaximumProcessId; + } + /** + * Gets the configured worker ID + */ + get workerId() { + return this[WorkerIdSymbol]; + } + /** + * Sets the worker ID that will be used by default for the {@link generate} method + * @param value The new value, will be coerced to BigInt and masked with `0b11111n` + */ + set workerId(value) { + this[WorkerIdSymbol] = BigInt(value) & MaximumWorkerId; + } + /** + * 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 = Date.now(), + workerId = this[WorkerIdSymbol], + processId = this[ProcessIdSymbol] + } = {}) { if (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime()); else if (typeof timestamp === "number") @@ -54,43 +104,76 @@ var Snowflake = class { 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); + if (typeof increment !== "bigint") { + increment = this[IncrementSymbol]; + this[IncrementSymbol] = increment + 1n & MaximumIncrement; } - return timestamp - __privateGet(this, _epoch) << 22n | (workerId & 0b11111n) << 17n | (processId & 0b11111n) << 12n | increment; + return timestamp - this[EpochSymbol] << 22n | (workerId & MaximumWorkerId) << 17n | (processId & MaximumProcessId) << 12n | increment & MaximumIncrement; } + /** + * 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) { const bigIntId = BigInt(id); + const epoch = this[EpochSymbol]; return { id: bigIntId, - timestamp: (bigIntId >> 22n) + __privateGet(this, _epoch), - workerId: bigIntId >> 17n & 0b11111n, - processId: bigIntId >> 12n & 0b11111n, - increment: bigIntId & 0b111111111111n, - epoch: __privateGet(this, _epoch) + timestamp: (bigIntId >> 22n) + epoch, + workerId: bigIntId >> 17n & MaximumWorkerId, + processId: bigIntId >> 12n & MaximumProcessId, + increment: bigIntId & MaximumIncrement, + epoch }; } + /** + * 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) { - return Number((BigInt(id) >> 22n) + __privateGet(this, _epoch)); + return Number((BigInt(id) >> 22n) + this[EpochSymbol]); } + /** + * 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, 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; + const typeA = typeof a; + return typeA === typeof b ? typeA === "string" ? cmpString(a, b) : cmpBigInt(a, b) : cmpBigInt(BigInt(a), BigInt(b)); } }; __name(Snowflake, "Snowflake"); -_increment = new WeakMap(); -_epoch = new WeakMap(); +_a = EpochSymbol, _b = IncrementSymbol, _c = ProcessIdSymbol, _d = WorkerIdSymbol; +function cmpBigInt(a, b) { + return a === b ? 0 : a < b ? -1 : 1; +} +__name(cmpBigInt, "cmpBigInt"); +function cmpString(a, b) { + return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1; +} +__name(cmpString, "cmpString"); // src/lib/DiscordSnowflake.ts var DiscordSnowflake = new Snowflake(1420070400000n); @@ -98,6 +181,6 @@ var DiscordSnowflake = new Snowflake(1420070400000n); // src/lib/TwitterSnowflake.ts var TwitterSnowflake = new Snowflake(1288834974657n); -export { DiscordSnowflake, Snowflake, TwitterSnowflake }; +export { DiscordSnowflake, MaximumIncrement, MaximumProcessId, MaximumWorkerId, Snowflake, TwitterSnowflake }; //# sourceMappingURL=out.js.map //# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/dist/index.mjs.map b/node_modules/@sapphire/snowflake/dist/index.mjs.map index 3a05a29..4204534 100644 --- a/node_modules/@sapphire/snowflake/dist/index.mjs.map +++ b/node_modules/@sapphire/snowflake/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/lib/Snowflake.ts","../src/lib/DiscordSnowflake.ts","../src/lib/TwitterSnowflake.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAM,YAAY;AAClB,IAAM,WAAW;AADjB;AAgBO,IAAM,YAAN,MAAgB;AAAA,EAsBf,YAAY,OAA+B;AAjBlD,wBAAO,UAAS,KAAK;AAMrB,mCAAa;AAMb;AAMC,uBAAK,QAAS,OAAO,iBAAiB,OAAO,MAAM,QAAQ,IAAI,KAAK;AAAA,EACrE;AAAA,EAKA,IAAW,QAAgB;AAC1B,WAAO,mBAAK;AAAA,EACb;AAAA,EAcO,SAAS,EAA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Ha;AAWZ;AAMA;;;AC1BM,IAAM,mBAAmB,IAAI,UAAU,cAAc;;;ACArD,IAAM,mBAAmB,IAAI,UAAU,cAAc","sourcesContent":["const ProcessId = 1n;\nconst WorkerId = 0n;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n */\nexport class Snowflake {\n\t/**\n\t * Alias for {@link deconstruct}\n\t */\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\tpublic decode = this.deconstruct;\n\n\t/**\n\t * Internal incrementor for generating snowflakes\n\t * @internal\n\t */\n\t#increment = 0n;\n\n\t/**\n\t * Internal reference of the epoch passed in the constructor\n\t * @internal\n\t */\n\t#epoch: bigint;\n\n\t/**\n\t * @param epoch the epoch to use\n\t */\n\tpublic constructor(epoch: number | bigint | Date) {\n\t\tthis.#epoch = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);\n\t}\n\n\t/**\n\t * The epoch for this snowflake.\n\t */\n\tpublic get epoch(): bigint {\n\t\treturn this.#epoch;\n\t}\n\n\t/**\n\t * Generates a snowflake given an epoch and optionally a timestamp\n\t * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}\n\t *\n\t * **note** when `increment` is not provided it defaults to the private `increment` of the instance\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).generate();\n\t * ```\n\t * @returns A unique snowflake\n\t */\n\tpublic generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId }: SnowflakeGenerateOptions = {}) {\n\t\tif (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());\n\t\telse if (typeof timestamp === 'number') timestamp = BigInt(timestamp);\n\t\telse if (typeof timestamp !== 'bigint') {\n\t\t\tthrow new TypeError(`\"timestamp\" argument must be a number, bigint, or Date (received ${typeof timestamp})`);\n\t\t}\n\n\t\tif (typeof increment === 'bigint' && increment >= 4095n) increment = 0n;\n\t\telse {\n\t\t\tincrement = this.#increment++;\n\t\t\tif (this.#increment >= 4095n) this.#increment = 0n;\n\t\t}\n\n\t\t// timestamp, workerId, processId, increment\n\t\treturn ((timestamp - this.#epoch) << 22n) | ((workerId & 0b11111n) << 17n) | ((processId & 0b11111n) << 12n) | increment;\n\t}\n\n\t/**\n\t * Deconstructs a snowflake given a snowflake ID\n\t * @param id the snowflake to deconstruct\n\t * @returns a deconstructed snowflake\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n\t * ```\n\t */\n\tpublic deconstruct(id: string | bigint): DeconstructedSnowflake {\n\t\tconst bigIntId = BigInt(id);\n\t\treturn {\n\t\t\tid: bigIntId,\n\t\t\ttimestamp: (bigIntId >> 22n) + this.#epoch,\n\t\t\tworkerId: (bigIntId >> 17n) & 0b11111n,\n\t\t\tprocessId: (bigIntId >> 12n) & 0b11111n,\n\t\t\tincrement: bigIntId & 0b111111111111n,\n\t\t\tepoch: this.#epoch\n\t\t};\n\t}\n\n\t/**\n\t * Retrieves the timestamp field's value from a snowflake.\n\t * @param id The snowflake to get the timestamp value from.\n\t * @returns The UNIX timestamp that is stored in `id`.\n\t */\n\tpublic timestampFrom(id: string | bigint): number {\n\t\treturn Number((BigInt(id) >> 22n) + this.#epoch);\n\t}\n\n\t/**\n\t * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n\t * snowflake in sort order.\n\t * @param a The first snowflake to compare.\n\t * @param b The second snowflake to compare.\n\t * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n\t * @example Sort snowflakes in ascending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => Snowflake.compare(a, b)));\n\t * // → ['254360814063058944', '737141877803057244', '1056191128120082432'];\n\t * ```\n\t * @example Sort snowflakes in descending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));\n\t * // → ['1056191128120082432', '737141877803057244', '254360814063058944'];\n\t * ```\n\t */\n\tpublic static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1 {\n\t\tif (typeof a === 'bigint' || typeof b === 'bigint') {\n\t\t\tif (typeof a === 'string') a = BigInt(a);\n\t\t\telse if (typeof b === 'string') b = BigInt(b);\n\t\t\treturn a === b ? 0 : a < b ? -1 : 1;\n\t\t}\n\n\t\treturn a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;\n\t}\n}\n\n/**\n * Options for Snowflake#generate\n */\nexport interface SnowflakeGenerateOptions {\n\t/**\n\t * Timestamp or date of the snowflake to generate\n\t * @default Date.now()\n\t */\n\ttimestamp?: number | bigint | Date;\n\n\t/**\n\t * The increment to use\n\t * @default 0n\n\t * @remark keep in mind that this bigint is auto-incremented between generate calls\n\t */\n\tincrement?: bigint;\n\n\t/**\n\t * The worker ID to use, will be truncated to 5 bits (0-31)\n\t * @default 0n\n\t */\n\tworkerId?: bigint;\n\n\t/**\n\t * The process ID to use, will be truncated to 5 bits (0-31)\n\t * @default 1n\n\t */\n\tprocessId?: bigint;\n}\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n\t/**\n\t * The id in BigInt form\n\t */\n\tid: bigint;\n\n\t/**\n\t * The timestamp stored in the snowflake\n\t */\n\ttimestamp: bigint;\n\n\t/**\n\t * The worker id stored in the snowflake\n\t */\n\tworkerId: bigint;\n\n\t/**\n\t * The process id stored in the snowflake\n\t */\n\tprocessId: bigint;\n\n\t/**\n\t * The increment stored in the snowflake\n\t */\n\tincrement: bigint;\n\n\t/**\n\t * The epoch to use in the snowflake\n\t */\n\tepoch: bigint;\n}\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Discord's snowflake epoch\n *\n * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}\n */\nexport const DiscordSnowflake = new Snowflake(1420070400000n);\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Twitter's snowflake epoch\n *\n * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}\n */\nexport const TwitterSnowflake = new Snowflake(1288834974657n);\n"]} \ No newline at end of file +{"version":3,"sources":["../src/lib/Snowflake.ts","../src/lib/DiscordSnowflake.ts","../src/lib/TwitterSnowflake.ts"],"names":[],"mappings":";;;;;;;;;AAAA,IAAM,kBAAkB,OAAO,+BAA+B;AAC9D,IAAM,cAAc,OAAO,2BAA2B;AACtD,IAAM,kBAAkB,OAAO,+BAA+B;AAC9D,IAAM,iBAAiB,OAAO,8BAA8B;AAKrD,IAAM,kBAAkB;AAKxB,IAAM,mBAAmB;AAKzB,IAAM,mBAAmB;AAlBhC;AAiCO,IAAM,YAAN,MAAgB;AAAA;AAAA;AAAA;AAAA,EAkCf,YAAY,OAA+B;AA7BlD;AAAA;AAAA;AAAA;AAAA,wBAAO,UAAS,KAAK;AAMrB;AAAA;AAAA;AAAA;AAAA,wBAAkB;AAMlB;AAAA;AAAA;AAAA;AAAA,wBAAS,IAAmB;AAM5B;AAAA;AAAA;AAAA;AAAA,wBAAS,IAAmB;AAM5B;AAAA;AAAA;AAAA;AAAA,wBAAS,IAAkB;AAM1B,SAAK,WAAW,IAAI,OAAO,iBAAiB,OAAO,MAAM,QAAQ,IAAI,KAAK;AAA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QAAQ,KAAK,WAAW;AAC9B,WAAO;AAAA,MACN,IAAI;AAAA,MACJ,YAAY,YAAY,OAAO;AAAA,MAC/B,UAAW,YAAY,MAAO;AAAA,MAC9B,WAAY,YAAY,MAAO;AAAA,MAC/B,WAAW,WAAW;AAAA,MACtB;AAAA,IACD;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,cAAc,IAA6B;AACjD,WAAO,QAAQ,OAAO,EAAE,KAAK,OAAO,KAAK,WAAW,CAAC;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBA,OAAc,QAAQ,GAAoB,GAAgC;AACzE,UAAM,QAAQ,OAAO;AACrB,WAAO,UAAU,OAAO,IACrB,UAAU,WACT,UAAU,GAAa,CAAW,IAClC,UAAU,GAAa,CAAW,IACnC,UAAU,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC;AAAA,EAClC;AACD;AA5Ka;AAWM,kBAMT,sBAMA,sBAMA;AAkJV,SAAS,UAAU,GAAW,GAAW;AACxC,SAAO,MAAM,IAAI,IAAI,IAAI,IAAI,KAAK;AACnC;AAFS;AAKT,SAAS,UAAU,GAAW,GAAW;AACxC,SAAO,MAAM,IAAI,IAAI,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,IAAI,IAAI,IAAI,KAAK;AACxF;AAFS;;;AC9MF,IAAM,mBAAmB,IAAI,UAAU,cAAc;;;ACArD,IAAM,mBAAmB,IAAI,UAAU,cAAc","sourcesContent":["const IncrementSymbol = Symbol('@sapphire/snowflake.increment');\nconst EpochSymbol = Symbol('@sapphire/snowflake.epoch');\nconst ProcessIdSymbol = Symbol('@sapphire/snowflake.processId');\nconst WorkerIdSymbol = Symbol('@sapphire/snowflake.workerId');\n\n/**\n * The maximum value the `workerId` field accepts in snowflakes.\n */\nexport const MaximumWorkerId = 0b11111n;\n\n/**\n * The maximum value the `processId` field accepts in snowflakes.\n */\nexport const MaximumProcessId = 0b11111n;\n\n/**\n * The maximum value the `increment` field accepts in snowflakes.\n */\nexport const MaximumIncrement = 0b111111111111n;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n */\nexport class Snowflake {\n\t/**\n\t * Alias for {@link deconstruct}\n\t */\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\tpublic decode = this.deconstruct;\n\n\t/**\n\t * Internal reference of the epoch passed in the constructor\n\t * @internal\n\t */\n\tprivate readonly [EpochSymbol]: bigint;\n\n\t/**\n\t * Internal incrementor for generating snowflakes\n\t * @internal\n\t */\n\tprivate [IncrementSymbol] = 0n;\n\n\t/**\n\t * The process ID that will be used by default in the generate method\n\t * @internal\n\t */\n\tprivate [ProcessIdSymbol] = 1n;\n\n\t/**\n\t * The worker ID that will be used by default in the generate method\n\t * @internal\n\t */\n\tprivate [WorkerIdSymbol] = 0n;\n\n\t/**\n\t * @param epoch the epoch to use\n\t */\n\tpublic constructor(epoch: number | bigint | Date) {\n\t\tthis[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);\n\t}\n\n\t/**\n\t * The epoch for this snowflake\n\t */\n\tpublic get epoch(): bigint {\n\t\treturn this[EpochSymbol];\n\t}\n\n\t/**\n\t * Gets the configured process ID\n\t */\n\tpublic get processId(): bigint {\n\t\treturn this[ProcessIdSymbol];\n\t}\n\n\t/**\n\t * Sets the process ID that will be used by default for the {@link generate} method\n\t * @param value The new value, will be coerced to BigInt and masked with `0b11111n`\n\t */\n\tpublic set processId(value: number | bigint) {\n\t\tthis[ProcessIdSymbol] = BigInt(value) & MaximumProcessId;\n\t}\n\n\t/**\n\t * Gets the configured worker ID\n\t */\n\tpublic get workerId(): bigint {\n\t\treturn this[WorkerIdSymbol];\n\t}\n\n\t/**\n\t * Sets the worker ID that will be used by default for the {@link generate} method\n\t * @param value The new value, will be coerced to BigInt and masked with `0b11111n`\n\t */\n\tpublic set workerId(value: number | bigint) {\n\t\tthis[WorkerIdSymbol] = BigInt(value) & MaximumWorkerId;\n\t}\n\n\t/**\n\t * Generates a snowflake given an epoch and optionally a timestamp\n\t * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}\n\t *\n\t * **note** when `increment` is not provided it defaults to the private `increment` of the instance\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).generate();\n\t * ```\n\t * @returns A unique snowflake\n\t */\n\tpublic generate({\n\t\tincrement,\n\t\ttimestamp = Date.now(),\n\t\tworkerId = this[WorkerIdSymbol],\n\t\tprocessId = this[ProcessIdSymbol]\n\t}: SnowflakeGenerateOptions = {}) {\n\t\tif (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());\n\t\telse if (typeof timestamp === 'number') timestamp = BigInt(timestamp);\n\t\telse if (typeof timestamp !== 'bigint') {\n\t\t\tthrow new TypeError(`\"timestamp\" argument must be a number, bigint, or Date (received ${typeof timestamp})`);\n\t\t}\n\n\t\tif (typeof increment !== 'bigint') {\n\t\t\tincrement = this[IncrementSymbol];\n\t\t\tthis[IncrementSymbol] = (increment + 1n) & MaximumIncrement;\n\t\t}\n\n\t\t// timestamp, workerId, processId, increment\n\t\treturn (\n\t\t\t((timestamp - this[EpochSymbol]) << 22n) |\n\t\t\t((workerId & MaximumWorkerId) << 17n) |\n\t\t\t((processId & MaximumProcessId) << 12n) |\n\t\t\t(increment & MaximumIncrement)\n\t\t);\n\t}\n\n\t/**\n\t * Deconstructs a snowflake given a snowflake ID\n\t * @param id the snowflake to deconstruct\n\t * @returns a deconstructed snowflake\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n\t * ```\n\t */\n\tpublic deconstruct(id: string | bigint): DeconstructedSnowflake {\n\t\tconst bigIntId = BigInt(id);\n\t\tconst epoch = this[EpochSymbol];\n\t\treturn {\n\t\t\tid: bigIntId,\n\t\t\ttimestamp: (bigIntId >> 22n) + epoch,\n\t\t\tworkerId: (bigIntId >> 17n) & MaximumWorkerId,\n\t\t\tprocessId: (bigIntId >> 12n) & MaximumProcessId,\n\t\t\tincrement: bigIntId & MaximumIncrement,\n\t\t\tepoch\n\t\t};\n\t}\n\n\t/**\n\t * Retrieves the timestamp field's value from a snowflake.\n\t * @param id The snowflake to get the timestamp value from.\n\t * @returns The UNIX timestamp that is stored in `id`.\n\t */\n\tpublic timestampFrom(id: string | bigint): number {\n\t\treturn Number((BigInt(id) >> 22n) + this[EpochSymbol]);\n\t}\n\n\t/**\n\t * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n\t * snowflake in sort order.\n\t * @param a The first snowflake to compare.\n\t * @param b The second snowflake to compare.\n\t * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n\t * @example Sort snowflakes in ascending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => Snowflake.compare(a, b)));\n\t * // → ['254360814063058944', '737141877803057244', '1056191128120082432'];\n\t * ```\n\t * @example Sort snowflakes in descending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));\n\t * // → ['1056191128120082432', '737141877803057244', '254360814063058944'];\n\t * ```\n\t */\n\tpublic static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1 {\n\t\tconst typeA = typeof a;\n\t\treturn typeA === typeof b\n\t\t\t? typeA === 'string'\n\t\t\t\t? cmpString(a as string, b as string)\n\t\t\t\t: cmpBigInt(a as bigint, b as bigint)\n\t\t\t: cmpBigInt(BigInt(a), BigInt(b));\n\t}\n}\n\n/** @internal */\nfunction cmpBigInt(a: bigint, b: bigint) {\n\treturn a === b ? 0 : a < b ? -1 : 1;\n}\n\n/** @internal */\nfunction cmpString(a: string, b: string) {\n\treturn a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;\n}\n\n/**\n * Options for Snowflake#generate\n */\nexport interface SnowflakeGenerateOptions {\n\t/**\n\t * Timestamp or date of the snowflake to generate\n\t * @default Date.now()\n\t */\n\ttimestamp?: number | bigint | Date;\n\n\t/**\n\t * The increment to use\n\t * @default 0n\n\t * @remark keep in mind that this bigint is auto-incremented between generate calls\n\t */\n\tincrement?: bigint;\n\n\t/**\n\t * The worker ID to use, will be truncated to 5 bits (0-31)\n\t * @default 0n\n\t */\n\tworkerId?: bigint;\n\n\t/**\n\t * The process ID to use, will be truncated to 5 bits (0-31)\n\t * @default 1n\n\t */\n\tprocessId?: bigint;\n}\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n\t/**\n\t * The id in BigInt form\n\t */\n\tid: bigint;\n\n\t/**\n\t * The timestamp stored in the snowflake\n\t */\n\ttimestamp: bigint;\n\n\t/**\n\t * The worker id stored in the snowflake\n\t */\n\tworkerId: bigint;\n\n\t/**\n\t * The process id stored in the snowflake\n\t */\n\tprocessId: bigint;\n\n\t/**\n\t * The increment stored in the snowflake\n\t */\n\tincrement: bigint;\n\n\t/**\n\t * The epoch to use in the snowflake\n\t */\n\tepoch: bigint;\n}\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Discord's snowflake epoch\n *\n * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}\n */\nexport const DiscordSnowflake = new Snowflake(1420070400000n);\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Twitter's snowflake epoch\n *\n * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}\n */\nexport const TwitterSnowflake = new Snowflake(1288834974657n);\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/package.json b/node_modules/@sapphire/snowflake/package.json index de47d22..da16195 100644 --- a/node_modules/@sapphire/snowflake/package.json +++ b/node_modules/@sapphire/snowflake/package.json @@ -1,6 +1,6 @@ { "name": "@sapphire/snowflake", - "version": "3.4.0", + "version": "3.5.1", "description": "Deconstructs and generates snowflake IDs using BigInts", "author": "@sapphire", "license": "MIT", @@ -56,12 +56,12 @@ "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" + "@favware/cliff-jumper": "^2.0.0", + "@vitest/coverage-c8": "^0.31.0", + "tsup": "^6.7.0", + "typedoc": "^0.24.7", + "typedoc-json-parser": "^7.4.0", + "typescript": "^5.0.4", + "vitest": "^0.31.0" } } \ No newline at end of file diff --git a/node_modules/@types/node/README.md b/node_modules/@types/node/README.md index 38c7b0c..7ca1474 100644 --- a/node_modules/@types/node/README.md +++ b/node_modules/@types/node/README.md @@ -8,7 +8,7 @@ This package contains type definitions for Node.js (https://nodejs.org/). Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. ### Additional Details - * Last updated: Mon, 26 Dec 2022 17:32:37 GMT + * Last updated: Tue, 13 Jun 2023 02:32:48 GMT * Dependencies: none * Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require`, `structuredClone` diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts index e8595e6..e309252 100644 --- a/node_modules/@types/node/assert.d.ts +++ b/node_modules/@types/node/assert.d.ts @@ -1,7 +1,7 @@ /** - * The `assert` module provides a set of assertion functions for verifying + * The `node: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) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/assert.js) */ declare module 'assert' { /** @@ -12,14 +12,28 @@ declare module 'assert' { 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. + * Indicates the failure of an assertion. All errors thrown by the `node:assert`module will be instances of the `AssertionError` class. */ class AssertionError extends Error { + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ expected: unknown; + /** + * Set to the passed in operator value. + */ operator: string; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ code: 'ERR_ASSERTION'; constructor(options?: { /** If provided, the error message is set to this value. */ @@ -36,9 +50,10 @@ declare module 'assert' { }); } /** - * This feature is currently experimental and behavior might still change. + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. * @since v14.2.0, v12.19.0 - * @experimental + * @deprecated Deprecated */ class CallTracker { /** @@ -47,7 +62,7 @@ declare module 'assert' { * error. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); @@ -78,12 +93,11 @@ declare module 'assert' { * callsfunc(1, 2, 3); * * assert.deepStrictEqual(tracker.getCalls(callsfunc), - * [{ thisArg: this, arguments: [1, 2, 3 ] }]); + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); * ``` - * * @since v18.8.0, v16.18.0 - * @params fn - * @returns An Array with the calls to a tracked function. + * @param fn + * @return An Array with all the calls to a tracked function. */ getCalls(fn: Function): CallTrackerCall[]; /** @@ -91,21 +105,19 @@ declare module 'assert' { * the functions that have not been called the expected number of times. * * ```js - * import assert from 'assert'; + * import assert from 'node: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(); + * console.log(tracker.report()); * // [ * // { * // message: 'Expected the func function to be executed 2 time(s) but was @@ -118,7 +130,7 @@ declare module 'assert' { * // ] * ``` * @since v14.2.0, v12.19.0 - * @return of objects containing information about the wrapper functions returned by `calls`. + * @return An Array of objects containing information about the wrapper functions returned by `calls`. */ report(): CallTrackerReportInformation[]; /** @@ -136,12 +148,11 @@ declare module 'assert' { * * callsfunc(); * // Tracker was called once - * tracker.getCalls(callsfunc).length === 1; + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); * * tracker.reset(callsfunc); - * tracker.getCalls(callsfunc).length === 0; + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); * ``` - * * @since v18.8.0, v16.18.0 * @param fn a tracked function to reset. */ @@ -151,7 +162,7 @@ declare module 'assert' { * have not been called the expected number of times. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); @@ -193,7 +204,7 @@ declare module 'assert' { * it will be thrown instead of the `AssertionError`. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.fail(); * // AssertionError [ERR_ASSERTION]: Failed @@ -231,7 +242,7 @@ declare module 'assert' { * thrown in a file! See below for further details. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.ok(true); * // OK @@ -266,7 +277,7 @@ declare module 'assert' { * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * // Using `assert()` works the same: * assert(0); @@ -291,7 +302,7 @@ declare module 'assert' { * and treated as being identical if both sides are `NaN`. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * assert.equal(1, 1); * // OK, 1 == 1 @@ -324,7 +335,7 @@ declare module 'assert' { * specially handled and treated as being identical if both sides are `NaN`. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * assert.notEqual(1, 2); * // OK @@ -371,24 +382,24 @@ declare module 'assert' { * Tests for any deep inequality. Opposite of {@link deepEqual}. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * const obj1 = { * a: { - * b: 1 - * } + * b: 1, + * }, * }; * const obj2 = { * a: { - * b: 2 - * } + * b: 2, + * }, * }; * const obj3 = { * a: { - * b: 1 - * } + * b: 1, + * }, * }; - * const obj4 = Object.create(obj1); + * const obj4 = { __proto__: obj1 }; * * assert.notDeepEqual(obj1, obj1); * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } @@ -414,7 +425,7 @@ declare module 'assert' { * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.strictEqual(1, 2); * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: @@ -452,7 +463,7 @@ declare module 'assert' { * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.notStrictEqual(1, 2); * // OK @@ -483,7 +494,7 @@ declare module 'assert' { * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); * // OK @@ -514,14 +525,14 @@ declare module 'assert' { * Custom validation object/error instance: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * const err = new TypeError('Wrong value'); * err.code = 404; * err.foo = 'bar'; * err.info = { * nested: true, - * baz: 'text' + * baz: 'text', * }; * err.reg = /abc/i; * @@ -534,16 +545,16 @@ declare module 'assert' { * message: 'Wrong value', * info: { * nested: true, - * baz: 'text' - * } + * 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( + * assert.throws( * () => { * throw err; * }, @@ -557,17 +568,17 @@ declare module 'assert' { * info: { * nested: true, * // It is not possible to use regular expressions for nested properties! - * baz: 'text' + * 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 - * } + * reg: /abc/i, + * }, * ); * * // Fails due to the different `message` and `name` properties: - * throws( + * assert.throws( * () => { * const otherErr = new Error('Not found'); * // Copy all enumerable properties from `err` to `otherErr`. @@ -578,20 +589,20 @@ declare module 'assert' { * }, * // The error's `message` and `name` properties will also be checked when using * // an error as validation object. - * err + * err, * ); * ``` * * Validate instanceof using constructor: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.throws( * () => { * throw new Error('Wrong value'); * }, - * Error + * Error, * ); * ``` * @@ -601,13 +612,13 @@ declare module 'assert' { * therefore also include the error name. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.throws( * () => { * throw new Error('Wrong value'); * }, - * /^Error: Wrong value$/ + * /^Error: Wrong value$/, * ); * ``` * @@ -617,7 +628,7 @@ declare module 'assert' { * It will otherwise fail with an `AssertionError`. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.throws( * () => { @@ -633,7 +644,7 @@ declare module 'assert' { * // possible. * return true; * }, - * 'unexpected error' + * 'unexpected error', * ); * ``` * @@ -643,7 +654,7 @@ declare module 'assert' { * a string as the second argument gets considered: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * function throwingFirst() { * throw new Error('First'); @@ -699,20 +710,20 @@ declare module 'assert' { * 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 + * [`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'; + * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, - * SyntaxError + * SyntaxError, * ); * ``` * @@ -720,27 +731,27 @@ declare module 'assert' { * 'Got unwanted exception...': * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, - * TypeError + * 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'; + * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, * /Wrong value/, - * 'Whoops' + * 'Whoops', * ); * // Throws: AssertionError: Got unwanted exception: Whoops * ``` @@ -754,7 +765,7 @@ declare module 'assert' { * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.ifError(null); * // OK @@ -800,7 +811,7 @@ declare module 'assert' { * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * await assert.rejects( * async () => { @@ -808,13 +819,13 @@ declare module 'assert' { * }, * { * name: 'TypeError', - * message: 'Wrong value' - * } + * message: 'Wrong value', + * }, * ); * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * await assert.rejects( * async () => { @@ -824,16 +835,16 @@ declare module 'assert' { * assert.strictEqual(err.name, 'TypeError'); * assert.strictEqual(err.message, 'Wrong value'); * return true; - * } + * }, * ); * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.rejects( * Promise.reject(new Error('Wrong value')), - * Error + * Error, * ).then(() => { * // ... * }); @@ -863,24 +874,24 @@ declare module 'assert' { * 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 + * [`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'; + * import assert from 'node:assert/strict'; * * await assert.doesNotReject( * async () => { * throw new TypeError('Wrong value'); * }, - * SyntaxError + * SyntaxError, * ); * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) * .then(() => { @@ -895,7 +906,7 @@ declare module 'assert' { * Expects the `string` input to match the regular expression. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.match('I will fail', /pass/); * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... @@ -918,7 +929,7 @@ declare module 'assert' { * Expects the `string` input not to match the regular expression. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotMatch('I will fail', /fail/); * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts index 0bf4739..e994f02 100644 --- a/node_modules/@types/node/async_hooks.d.ts +++ b/node_modules/@types/node/async_hooks.d.ts @@ -1,17 +1,24 @@ /** - * The `async_hooks` module provides an API to track asynchronous resources. It - * can be accessed using: + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * `AsyncLocalStorage` tracks async context + * * `process.getActiveResourcesInfo()` tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: * * ```js - * import async_hooks from 'async_hooks'; + * import async_hooks from 'node:async_hooks'; * ``` * @experimental - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/async_hooks.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js) */ declare module 'async_hooks' { /** * ```js - * import { executionAsyncId } from 'async_hooks'; + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; * * console.log(executionAsyncId()); // 1 - bootstrap * fs.open(path, 'r', (err, fd) => { @@ -51,8 +58,8 @@ declare module 'async_hooks' { * but having an object representing the top-level can be helpful. * * ```js - * import { open } from 'fs'; - * import { executionAsyncId, executionAsyncResource } from 'async_hooks'; + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; * * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} * open(new URL(import.meta.url), 'r', (err, fd) => { @@ -64,11 +71,11 @@ declare module 'async_hooks' { * use of a tracking `Map` to store the metadata: * * ```js - * import { createServer } from 'http'; + * import { createServer } from 'node:http'; * import { * executionAsyncId, * executionAsyncResource, - * createHook + * createHook, * } from 'async_hooks'; * const sym = Symbol('state'); // Private symbol to avoid pollution * @@ -78,7 +85,7 @@ declare module 'async_hooks' { * if (cr) { * resource[sym] = cr[sym]; * } - * } + * }, * }).enable(); * * const server = createServer((req, res) => { @@ -167,11 +174,11 @@ declare module 'async_hooks' { * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. * * ```js - * import { createHook } from 'async_hooks'; + * import { createHook } from 'node:async_hooks'; * * const asyncHook = createHook({ * init(asyncId, type, triggerAsyncId, resource) { }, - * destroy(asyncId) { } + * destroy(asyncId) { }, * }); * ``` * @@ -223,13 +230,13 @@ declare module 'async_hooks' { * The following is an overview of the `AsyncResource` API. * * ```js - * import { AsyncResource, executionAsyncId } from 'async_hooks'; + * import { AsyncResource, executionAsyncId } from 'node: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 } + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, * ); * * // Run a function in the execution context of the resource. This will @@ -263,33 +270,17 @@ declare module 'async_hooks' { constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); /** * Binds the given function to the current execution context. - * - * The returned function will have an `asyncResource` property referencing - * the `AsyncResource` to which the function is bound. * @since v14.8.0, v12.19.0 * @param fn The function to bind to the current execution context. * @param type An optional name to associate with the underlying `AsyncResource`. */ - static bind any, ThisArg>( - fn: Func, - type?: string, - thisArg?: ThisArg - ): Func & { - asyncResource: AsyncResource; - }; + static bind any, ThisArg>(fn: Func, type?: string, thisArg?: ThisArg): Func; /** * Binds the given function to execute to this `AsyncResource`'s scope. - * - * The returned function will have an `asyncResource` property referencing - * the `AsyncResource` to which the function is bound. * @since v14.8.0, v12.19.0 * @param fn The function to bind to the current `AsyncResource`. */ - bind any>( - fn: Func - ): Func & { - asyncResource: AsyncResource; - }; + bind any>(fn: Func): Func; /** * Call the provided function with the provided arguments in the execution context * of the async resource. This will establish the context, trigger the AsyncHooks @@ -322,17 +313,17 @@ declare module 'async_hooks' { /** * 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. + * While you can create your own implementation on top of the `node: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'; + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; * * const asyncLocalStorage = new AsyncLocalStorage(); * @@ -368,6 +359,44 @@ declare module 'async_hooks' { * @since v13.10.0, v12.17.0 */ class AsyncLocalStorage { + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @experimental + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @experimental + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; /** * Disables the instance of `AsyncLocalStorage`. All subsequent calls * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts index 5ec326d..86694b0 100644 --- a/node_modules/@types/node/buffer.d.ts +++ b/node_modules/@types/node/buffer.d.ts @@ -10,7 +10,7 @@ * recommended to explicitly reference it via an import or require statement. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Creates a zero-filled Buffer of length 10. * const buf1 = Buffer.alloc(10); @@ -41,11 +41,29 @@ * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. * const buf7 = Buffer.from('tést', 'latin1'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/buffer.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/buffer.js) */ declare module 'buffer' { import { BinaryLike } from 'node:crypto'; import { ReadableStream as WebReadableStream } from 'node:stream/web'; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; export const INSPECT_MAX_BYTES: number; export const kMaxLength: number; export const kStringMaxLength: number; @@ -67,7 +85,7 @@ declare module 'buffer' { * sequence cannot be adequately represented in the target encoding. For instance: * * ```js - * import { Buffer, transcode } from 'buffer'; + * import { Buffer, transcode } from 'node:buffer'; * * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); * console.log(newBuf.toString('ascii')); @@ -158,22 +176,62 @@ declare module 'buffer' { */ text(): Promise; /** - * Returns a new (WHATWG) `ReadableStream` that allows the content of the `Blob` to be read. + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. * @since v16.7.0 */ stream(): WebReadableStream; } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `require('node:os').EOL`. + */ + endings?: 'native' | 'transparent'; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } export import atob = globalThis.atob; export import btoa = globalThis.btoa; - import { Blob as NodeBlob } from 'buffer'; // This conditional type will be the existing global Blob in a browser, or // the copy below in a Node environment. - type __Blob = typeof globalThis extends { onmessage: any, Blob: infer T } - ? T : NodeBlob; + type __Blob = typeof globalThis extends { onmessage: any; Blob: infer T } ? T : NodeBlob; global { + namespace NodeJS { + export { BufferEncoding }; + } // Buffer class - type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; + type BufferEncoding = + | 'ascii' + | 'utf8' + | 'utf-8' + | 'utf16le' + | 'ucs2' + | 'ucs-2' + | 'base64' + | 'base64url' + | 'latin1' + | 'binary' + | 'hex'; type WithImplicitCoercion = | T | { @@ -235,19 +293,27 @@ declare module 'buffer' { * Array entries outside that range will be truncated to fit into it. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); * ``` * + * If `array` is an `Array`\-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. + * * A `TypeError` will be thrown if `array` is not an `Array` or another type * appropriate for `Buffer.from()` variants. * * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. * @since v5.10.0 */ - from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; /** * Creates a new Buffer using the passed {data} * @param data data to create a new Buffer @@ -265,7 +331,7 @@ declare module 'buffer' { | { [Symbol.toPrimitive](hint: 'string'): string; }, - encoding?: BufferEncoding + encoding?: BufferEncoding, ): Buffer; /** * Creates a new Buffer using the passed {data} @@ -276,7 +342,7 @@ declare module 'buffer' { * Returns `true` if `obj` is a `Buffer`, `false` otherwise. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * Buffer.isBuffer(Buffer.alloc(10)); // true * Buffer.isBuffer(Buffer.from('foo')); // true @@ -292,7 +358,7 @@ declare module 'buffer' { * or `false` otherwise. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * console.log(Buffer.isEncoding('utf8')); * // Prints: true @@ -321,7 +387,7 @@ declare module 'buffer' { * string. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const str = '\u00bd + \u00bc = \u00be'; * @@ -339,7 +405,10 @@ declare module 'buffer' { * @param [encoding='utf8'] If `string` is a string, this is its encoding. * @return The number of bytes contained within `string`. */ - byteLength(string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; /** * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. * @@ -353,7 +422,7 @@ declare module 'buffer' { * truncated to `totalLength`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create a single `Buffer` from a list of three `Buffer` instances. * @@ -379,11 +448,28 @@ declare module 'buffer' { * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. */ concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=': 0'] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; /** * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('1234'); * const buf2 = Buffer.from('0123'); @@ -401,7 +487,7 @@ declare module 'buffer' { * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(5); * @@ -409,12 +495,12 @@ declare module 'buffer' { * // Prints: * ``` * - * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. * * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(5, 'a'); * @@ -426,7 +512,7 @@ declare module 'buffer' { * initialized by calling `buf.fill(fill, encoding)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); * @@ -446,13 +532,13 @@ declare module 'buffer' { */ alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; /** - * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. * * The underlying memory for `Buffer` instances created in this way is _not_ * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(10); * @@ -468,9 +554,8 @@ declare module 'buffer' { * A `TypeError` will be thrown if `size` is not a number. * * The `Buffer` module pre-allocates an internal `Buffer` instance of - * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`,`Buffer.from(array)`, `Buffer.concat()`, and the - * deprecated`new Buffer(size)` constructor only when `size` is less than or equal - * to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than or equal to`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). * * Use of this pre-allocated internal memory pool is a key difference between * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. @@ -483,15 +568,15 @@ declare module 'buffer' { */ allocUnsafe(size: number): Buffer; /** - * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. A zero-length `Buffer` is created - * if `size` is 0. + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. * * The underlying memory for `Buffer` instances created in this way is _not_ * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize * such `Buffer` instances with zeroes. * * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, - * allocations under 4 KB are sliced from a single pre-allocated `Buffer`. This + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This * allows applications to avoid the garbage collection overhead of creating many * individually allocated `Buffer` instances. This approach improves both * performance and memory usage by eliminating the need to track and clean up as @@ -503,7 +588,7 @@ declare module 'buffer' { * then copying out the relevant bits. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Need to keep around a few small chunks of memory. * const store = []; @@ -541,7 +626,7 @@ declare module 'buffer' { * written. However, partially encoded characters will not be written. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(256); * @@ -577,7 +662,7 @@ declare module 'buffer' { * as {@link constants.MAX_STRING_LENGTH}. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.allocUnsafe(26); * @@ -614,7 +699,7 @@ declare module 'buffer' { * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); * const json = JSON.stringify(buf); @@ -641,7 +726,7 @@ declare module 'buffer' { * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('ABC'); * const buf2 = Buffer.from('414243', 'hex'); @@ -665,7 +750,7 @@ declare module 'buffer' { * * `-1` is returned if `target` should come _after_`buf` when sorted. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('ABC'); * const buf2 = Buffer.from('BCD'); @@ -689,7 +774,7 @@ declare module 'buffer' { * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); @@ -710,7 +795,13 @@ declare module 'buffer' { * @param [sourceStart=0] The offset within `buf` at which to begin comparison. * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). */ - compare(target: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1; + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; /** * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. * @@ -719,7 +810,7 @@ declare module 'buffer' { * different function arguments. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create two `Buffer` instances. * const buf1 = Buffer.allocUnsafe(26); @@ -740,7 +831,7 @@ declare module 'buffer' { * ``` * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create a `Buffer` and copy data from one region to an overlapping region * // within the same `Buffer`. @@ -773,7 +864,7 @@ declare module 'buffer' { * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -811,7 +902,7 @@ declare module 'buffer' { * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte * // from the original `Buffer`. @@ -838,7 +929,7 @@ declare module 'buffer' { * end of `buf` rather than the beginning. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -865,7 +956,7 @@ declare module 'buffer' { * `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -886,7 +977,7 @@ declare module 'buffer' { * `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -907,7 +998,7 @@ declare module 'buffer' { * This function is also available under the `writeBigUint64BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -931,7 +1022,7 @@ declare module 'buffer' { * Writes `value` to `buf` at the specified `offset` as little-endian * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -960,7 +1051,7 @@ declare module 'buffer' { * This function is also available under the `writeUintLE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -988,7 +1079,7 @@ declare module 'buffer' { * This function is also available under the `writeUintBE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -1014,7 +1105,7 @@ declare module 'buffer' { * when `value` is anything other than a signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -1035,7 +1126,7 @@ declare module 'buffer' { * signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -1057,7 +1148,7 @@ declare module 'buffer' { * This function is also available under the `readBigUint64BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); * @@ -1079,7 +1170,7 @@ declare module 'buffer' { * This function is also available under the `readBigUint64LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); * @@ -1120,7 +1211,7 @@ declare module 'buffer' { * This function is also available under the `readUintLE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1144,7 +1235,7 @@ declare module 'buffer' { * This function is also available under the `readUintBE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1168,7 +1259,7 @@ declare module 'buffer' { * supporting up to 48 bits of accuracy. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1185,7 +1276,7 @@ declare module 'buffer' { * supporting up to 48 bits of accuracy. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1207,7 +1298,7 @@ declare module 'buffer' { * This function is also available under the `readUint8` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, -2]); * @@ -1233,7 +1324,7 @@ declare module 'buffer' { * This function is also available under the `readUint16LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56]); * @@ -1259,7 +1350,7 @@ declare module 'buffer' { * This function is also available under the `readUint16BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56]); * @@ -1283,7 +1374,7 @@ declare module 'buffer' { * This function is also available under the `readUint32LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); * @@ -1307,7 +1398,7 @@ declare module 'buffer' { * This function is also available under the `readUint32BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); * @@ -1329,7 +1420,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([-1, 5]); * @@ -1350,7 +1441,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 5]); * @@ -1369,7 +1460,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 5]); * @@ -1386,7 +1477,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 0, 0, 5]); * @@ -1405,7 +1496,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 0, 0, 5]); * @@ -1420,7 +1511,7 @@ declare module 'buffer' { * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4]); * @@ -1437,7 +1528,7 @@ declare module 'buffer' { * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4]); * @@ -1452,7 +1543,7 @@ declare module 'buffer' { * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); * @@ -1469,7 +1560,7 @@ declare module 'buffer' { * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); * @@ -1486,7 +1577,7 @@ declare module 'buffer' { * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); * @@ -1508,7 +1599,7 @@ declare module 'buffer' { * between UTF-16 little-endian and UTF-16 big-endian: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); * buf.swap16(); // Convert to big-endian UTF-16 text. @@ -1522,7 +1613,7 @@ declare module 'buffer' { * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); * @@ -1548,7 +1639,7 @@ declare module 'buffer' { * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); * @@ -1577,7 +1668,7 @@ declare module 'buffer' { * This function is also available under the `writeUint8` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1607,7 +1698,7 @@ declare module 'buffer' { * This function is also available under the `writeUint16LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1635,7 +1726,7 @@ declare module 'buffer' { * This function is also available under the `writeUint16BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1663,7 +1754,7 @@ declare module 'buffer' { * This function is also available under the `writeUint32LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1690,7 +1781,7 @@ declare module 'buffer' { * This function is also available under the `writeUint32BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1718,7 +1809,7 @@ declare module 'buffer' { * `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(2); * @@ -1741,7 +1832,7 @@ declare module 'buffer' { * The `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(2); * @@ -1763,7 +1854,7 @@ declare module 'buffer' { * The `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(2); * @@ -1785,7 +1876,7 @@ declare module 'buffer' { * The `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1807,7 +1898,7 @@ declare module 'buffer' { * The `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1827,7 +1918,7 @@ declare module 'buffer' { * undefined when `value` is anything other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1847,7 +1938,7 @@ declare module 'buffer' { * undefined when `value` is anything other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1867,7 +1958,7 @@ declare module 'buffer' { * other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -1887,7 +1978,7 @@ declare module 'buffer' { * other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -1907,7 +1998,7 @@ declare module 'buffer' { * the entire `buf` will be filled: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Fill a `Buffer` with the ASCII character 'h'. * @@ -1915,6 +2006,12 @@ declare module 'buffer' { * * console.log(b.toString()); * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: * ``` * * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or @@ -1925,7 +2022,7 @@ declare module 'buffer' { * then only the bytes of that character that fit into `buf` are written: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Fill a `Buffer` with character that takes up two bytes in UTF-8. * @@ -1937,7 +2034,7 @@ declare module 'buffer' { * fill data remains, an exception is thrown: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(5); * @@ -1949,7 +2046,7 @@ declare module 'buffer' { * // Throws an exception. * ``` * @since v0.5.0 - * @param value The value with which to fill `buf`. + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. * @param [offset=0] Number of bytes to skip before starting to fill `buf`. * @param [end=buf.length] Where to stop filling `buf` (not inclusive). * @param [encoding='utf8'] The encoding for `value` if `value` is a string. @@ -1966,7 +2063,7 @@ declare module 'buffer' { * value between `0` and `255`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('this is a buffer'); * @@ -1999,7 +2096,7 @@ declare module 'buffer' { * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const b = Buffer.from('abcdef'); * @@ -2030,7 +2127,7 @@ declare module 'buffer' { * rather than the first occurrence. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('this buffer is a buffer'); * @@ -2065,7 +2162,7 @@ declare module 'buffer' { * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const b = Buffer.from('abcdef'); * @@ -2098,7 +2195,7 @@ declare module 'buffer' { * of `buf`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Log the entire contents of a `Buffer`. * @@ -2122,7 +2219,7 @@ declare module 'buffer' { * Equivalent to `buf.indexOf() !== -1`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('this is a buffer'); * @@ -2152,7 +2249,7 @@ declare module 'buffer' { * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -2175,7 +2272,7 @@ declare module 'buffer' { * called automatically when a `Buffer` is used in a `for..of` statement. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -2218,7 +2315,7 @@ declare module 'buffer' { * **For code running using Node.js APIs, converting between base64-encoded strings** * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** * @since v15.13.0, v14.17.0 - * @deprecated Use `Buffer.from(data, 'base64')` instead. + * @legacy Use `Buffer.from(data, 'base64')` instead. * @param data The Base64-encoded input string. */ function atob(data: string): string; @@ -2234,11 +2331,10 @@ declare module 'buffer' { * **For code running using Node.js APIs, converting between base64-encoded strings** * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** * @since v15.13.0, v14.17.0 - * @deprecated Use `buf.toString('base64')` instead. + * @legacy Use `buf.toString('base64')` instead. * @param data An ASCII (Latin1) string. */ function btoa(data: string): string; - interface Blob extends __Blob {} /** * `Blob` class is a global reference for `require('node:buffer').Blob` diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts index c537d6d..771d39d 100644 --- a/node_modules/@types/node/child_process.d.ts +++ b/node_modules/@types/node/child_process.d.ts @@ -1,10 +1,10 @@ /** - * The `child_process` module provides the ability to spawn subprocesses in + * The `node:child_process` module provides the ability to spawn subprocesses in * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability * is primarily provided by the {@link spawn} function: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const ls = spawn('ls', ['-lh', '/usr']); * * ls.stdout.on('data', (data) => { @@ -44,8 +44,8 @@ * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks * the event loop until the spawned process either exits or is terminated. * - * For convenience, the `child_process` module provides a handful of synchronous - * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on * top of {@link spawn} or {@link spawnSync}. * * * {@link exec}: spawns a shell and runs a command within that @@ -63,7 +63,7 @@ * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, * the synchronous methods can have significant impact on performance due to * stalling the event loop while spawned processes complete. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/child_process.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/child_process.js) */ declare module 'child_process' { import { ObjectEncodingOptions } from 'node:fs'; @@ -94,8 +94,7 @@ declare module 'child_process' { * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will * refer to the same value. * - * The `subprocess.stdin` property can be `undefined` if the child process could - * not be successfully spawned. + * The `subprocess.stdin` property can be `null` or `undefined`if the child process could not be successfully spawned. * @since v0.1.90 */ stdin: Writable | null; @@ -109,7 +108,7 @@ declare module 'child_process' { * refer to the same value. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn('ls'); * @@ -118,8 +117,7 @@ declare module 'child_process' { * }); * ``` * - * The `subprocess.stdout` property can be `null` if the child process could - * not be successfully spawned. + * The `subprocess.stdout` property can be `null` or `undefined`if the child process could not be successfully spawned. * @since v0.1.90 */ stdout: Readable | null; @@ -132,14 +130,13 @@ declare module 'child_process' { * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will * refer to the same value. * - * The `subprocess.stderr` property can be `null` if the child process could - * not be successfully spawned. + * The `subprocess.stderr` property can be `null` or `undefined`if the child process could not be successfully spawned. * @since v0.1.90 */ stderr: Readable | null; /** * The `subprocess.channel` property is a reference to the child's IPC channel. If - * no IPC channel currently exists, this property is `undefined`. + * no IPC channel exists, this property is `undefined`. * @since v7.1.0 */ readonly channel?: Pipe | null | undefined; @@ -154,16 +151,16 @@ declare module 'child_process' { * in the array are `null`. * * ```js - * const assert = require('assert'); - * const fs = require('fs'); - * const child_process = require('child_process'); + * const assert = require('node:assert'); + * const fs = require('node:fs'); + * const child_process = require('node:child_process'); * * const subprocess = child_process.spawn('ls', { * stdio: [ * 0, // Use parent's stdin for child. * 'pipe', // Pipe child's stdout to parent. * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. - * ] + * ], * }); * * assert.strictEqual(subprocess.stdio[0], null); @@ -204,7 +201,7 @@ declare module 'child_process' { * emitted. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const grep = spawn('grep', ['ssh']); * * console.log(`Spawned child pid: ${grep.pid}`); @@ -251,7 +248,7 @@ declare module 'child_process' { * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const grep = spawn('grep', ['ssh']); * * grep.on('close', (code, signal) => { @@ -284,7 +281,7 @@ declare module 'child_process' { * * ```js * 'use strict'; - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn( * 'sh', @@ -294,8 +291,8 @@ declare module 'child_process' { * console.log(process.pid, 'is alive') * }, 500);"`, * ], { - * stdio: ['inherit', 'inherit', 'inherit'] - * } + * stdio: ['inherit', 'inherit', 'inherit'], + * }, * ); * * setTimeout(() => { @@ -317,7 +314,7 @@ declare module 'child_process' { * For example, in the parent script: * * ```js - * const cp = require('child_process'); + * const cp = require('node:child_process'); * const n = cp.fork(`${__dirname}/sub.js`); * * n.on('message', (m) => { @@ -371,10 +368,10 @@ declare module 'child_process' { * a TCP server object to the child process as illustrated in the example below: * * ```js - * const subprocess = require('child_process').fork('subprocess.js'); + * const subprocess = require('node:child_process').fork('subprocess.js'); * * // Open up the server object and send the handle. - * const server = require('net').createServer(); + * const server = require('node:net').createServer(); * server.on('connection', (socket) => { * socket.end('handled by parent'); * }); @@ -398,10 +395,9 @@ declare module 'child_process' { * Once the server is now shared between the parent and child, some connections * can be handled by the parent and some by the child. * - * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on - * a `'message'` event instead of `'connection'` and using `server.bind()` instead - * of `server.listen()`. This is, however, currently only supported on Unix - * platforms. + * While the example above uses a server created using the `node:net` module,`node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using`server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. * * #### Example: sending a socket object * @@ -410,13 +406,13 @@ declare module 'child_process' { * handle connections with "normal" or "special" priority: * * ```js - * const { fork } = require('child_process'); + * const { fork } = require('node:child_process'); * const normal = fork('subprocess.js', ['normal']); * const special = fork('subprocess.js', ['special']); * * // Open up the server and send sockets to child. Use pauseOnConnect to prevent * // the sockets from being read before they are sent to the child process. - * const server = require('net').createServer({ pauseOnConnect: true }); + * const server = require('node:net').createServer({ pauseOnConnect: true }); * server.on('connection', (socket) => { * * // If this is special priority... @@ -482,11 +478,11 @@ declare module 'child_process' { * the child and the parent. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn(process.argv[0], ['child_program.js'], { * detached: true, - * stdio: 'ignore' + * stdio: 'ignore', * }); * * subprocess.unref(); @@ -500,11 +496,11 @@ declare module 'child_process' { * to wait for the child to exit before exiting itself. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn(process.argv[0], ['child_program.js'], { * detached: true, - * stdio: 'ignore' + * stdio: 'ignore', * }); * * subprocess.unref(); @@ -634,6 +630,15 @@ declare module 'child_process' { } interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ stdio?: StdioOptions | undefined; shell?: boolean | string | undefined; windowsVerbatimArguments?: boolean | undefined; @@ -663,7 +668,7 @@ declare module 'child_process' { * ```js * const defaults = { * cwd: undefined, - * env: process.env + * env: process.env, * }; * ``` * @@ -682,7 +687,7 @@ declare module 'child_process' { * exit code: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const ls = spawn('ls', ['-lh', '/usr']); * * ls.stdout.on('data', (data) => { @@ -701,7 +706,7 @@ declare module 'child_process' { * Example: A very elaborate way to run `ps ax | grep ssh` * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const ps = spawn('ps', ['ax']); * const grep = spawn('grep', ['ssh']); * @@ -738,7 +743,7 @@ declare module 'child_process' { * Example of checking for failed `spawn`: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const subprocess = spawn('bad_command'); * * subprocess.on('error', (err) => { @@ -749,14 +754,14 @@ declare module 'child_process' { * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process * title while others (Windows, SunOS) will use `command`. * - * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, - * retrieve it with the`process.argv0` property instead. + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent. Retrieve + * it with the`process.argv0` property instead. * * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const grep = spawn('grep', ['ssh'], { signal }); @@ -815,7 +820,7 @@ declare module 'child_process' { * need to be dealt with accordingly: * * ```js - * const { exec } = require('child_process'); + * const { exec } = require('node:child_process'); * * exec('"/path/to/test file/test.sh" arg1 arg2'); * // Double quotes are used so that the space in the path is not interpreted as @@ -841,7 +846,7 @@ declare module 'child_process' { * encoding, `Buffer` objects will be passed to the callback instead. * * ```js - * const { exec } = require('child_process'); + * const { exec } = require('node:child_process'); * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { * if (error) { * console.error(`exec error: ${error}`); @@ -866,8 +871,8 @@ declare module 'child_process' { * callback, but with two additional properties `stdout` and `stderr`. * * ```js - * const util = require('util'); - * const exec = util.promisify(require('child_process').exec); + * const util = require('node:util'); + * const exec = util.promisify(require('node:child_process').exec); * * async function lsExample() { * const { stdout, stderr } = await exec('ls'); @@ -881,11 +886,11 @@ declare module 'child_process' { * the error passed to the callback will be an `AbortError`: * * ```js - * const { exec } = require('child_process'); + * const { exec } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = exec('grep ssh', { signal }, (error) => { - * console.log(error); // an AbortError + * console.error(error); // an AbortError * }); * controller.abort(); * ``` @@ -984,7 +989,10 @@ declare module 'child_process' { interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { encoding: BufferEncoding; } - type ExecFileException = ExecException & NodeJS.ErrnoException; + type ExecFileException = + & Omit + & Omit + & { code?: string | number | undefined | null }; /** * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified * executable `file` is spawned directly as a new process making it slightly more @@ -995,7 +1003,7 @@ declare module 'child_process' { * supported. * * ```js - * const { execFile } = require('child_process'); + * const { execFile } = require('node:child_process'); * const child = execFile('node', ['--version'], (error, stdout, stderr) => { * if (error) { * throw error; @@ -1018,8 +1026,8 @@ declare module 'child_process' { * callback, but with two additional properties `stdout` and `stderr`. * * ```js - * const util = require('util'); - * const execFile = util.promisify(require('child_process').execFile); + * const util = require('node:util'); + * const execFile = util.promisify(require('node:child_process').execFile); * async function getVersion() { * const { stdout } = await execFile('node', ['--version']); * console.log(stdout); @@ -1035,11 +1043,11 @@ declare module 'child_process' { * the error passed to the callback will be an `AbortError`: * * ```js - * const { execFile } = require('child_process'); + * const { execFile } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = execFile('node', ['--version'], { signal }, (error) => { - * console.log(error); // an AbortError + * console.error(error); // an AbortError * }); * controller.abort(); * ``` @@ -1192,6 +1200,15 @@ declare module 'child_process' { execPath?: string | undefined; execArgv?: string[] | undefined; silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ stdio?: StdioOptions | undefined; detached?: boolean | undefined; windowsVerbatimArguments?: boolean | undefined; @@ -1231,7 +1248,7 @@ declare module 'child_process' { * console.log(`Hello from ${process.argv[2]}!`); * }, 1_000); * } else { - * const { fork } = require('child_process'); + * const { fork } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = fork(__filename, ['child'], { signal }); @@ -1292,6 +1309,15 @@ declare module 'child_process' { function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; interface CommonExecOptions extends CommonOptions { input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ stdio?: StdioOptions | undefined; killSignal?: NodeJS.Signals | number | undefined; maxBuffer?: number | undefined; diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts index 37dbc57..4fa9aef 100644 --- a/node_modules/@types/node/cluster.d.ts +++ b/node_modules/@types/node/cluster.d.ts @@ -8,12 +8,12 @@ * server ports. * * ```js - * import cluster from 'cluster'; - * import http from 'http'; - * import { cpus } from 'os'; - * import process from 'process'; + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; * - * const numCPUs = cpus().length; + * const numCPUs = availableParallelism(); * * if (cluster.isPrimary) { * console.log(`Primary ${process.pid} is running`); @@ -50,12 +50,13 @@ * ``` * * On Windows, it is not yet possible to set up a named pipe server in a worker. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/cluster.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/cluster.js) */ declare module 'cluster' { import * as child from 'node:child_process'; import EventEmitter = require('node:events'); import * as net from 'node:net'; + type SerializationType = 'json' | 'advanced'; export interface ClusterSettings { execArgv?: string[] | undefined; // default: process.execArgv exec?: string | undefined; @@ -65,6 +66,9 @@ declare module 'cluster' { uid?: number | undefined; gid?: number | undefined; inspectPort?: number | (() => number) | undefined; + serialization?: SerializationType | undefined; + cwd?: string | undefined; + windowsHide?: boolean | undefined; } export interface Address { address: string; @@ -183,7 +187,7 @@ declare module 'cluster' { * }); * * } else if (cluster.isWorker) { - * const net = require('net'); + * const net = require('node:net'); * const server = net.createServer((socket) => { * // Connections never end * }); @@ -213,12 +217,12 @@ declare module 'cluster' { * because of exiting or being signaled). Otherwise, it returns `false`. * * ```js - * import cluster from 'cluster'; - * import http from 'http'; - * import { cpus } from 'os'; - * import process from 'process'; + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; * - * const numCPUs = cpus().length; + * const numCPUs = availableParallelism(); * * if (cluster.isPrimary) { * console.log(`Primary ${process.pid} is running`); diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts index 16c9137..7e35638 100644 --- a/node_modules/@types/node/console.d.ts +++ b/node_modules/@types/node/console.d.ts @@ -1,11 +1,11 @@ /** - * The `console` module provides a simple debugging console that is similar to the - * JavaScript console mechanism provided by web browsers. + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. * * The module exports two specific components: * - * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. - * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * * A `Console` class with methods such as `console.log()`, `console.error()`, and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('node:console')`. * * _**Warning**_: The global console object's methods are neither consistently * synchronous like the browser APIs they resemble, nor are they consistently @@ -53,7 +53,7 @@ * myConsole.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to err * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/console.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/console.js) */ declare module 'console' { import console = require('node:console'); diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts index 20d960c..3c67801 100644 --- a/node_modules/@types/node/crypto.d.ts +++ b/node_modules/@types/node/crypto.d.ts @@ -1,9 +1,10 @@ /** - * The `crypto` module provides cryptographic functionality that includes a set of - * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. * * ```js - * const { createHmac } = await import('crypto'); + * const { createHmac } = await import('node:crypto'); * * const secret = 'abcdefg'; * const hash = createHmac('sha256', secret) @@ -13,27 +14,27 @@ * // Prints: * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/crypto.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/crypto.js) */ declare module 'crypto' { import * as stream from 'node:stream'; import { PeerCertificate } from 'node:tls'; /** * SPKAC is a Certificate Signing Request mechanism originally implemented by - * Netscape and was specified formally as part of [HTML5's `keygen` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen). + * Netscape and was specified formally as part of HTML5's `keygen` element. * * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects * should not use this element anymore. * - * The `crypto` module provides the `Certificate` class for working with SPKAC + * The `node:crypto` module provides the `Certificate` class for working with SPKAC * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC - * implementation](https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html) internally. + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. * @since v0.11.8 */ class Certificate { /** * ```js - * const { Certificate } = await import('crypto'); + * const { Certificate } = await import('node:crypto'); * const spkac = getSpkacSomehow(); * const challenge = Certificate.exportChallenge(spkac); * console.log(challenge.toString('utf8')); @@ -46,7 +47,7 @@ declare module 'crypto' { static exportChallenge(spkac: BinaryLike): Buffer; /** * ```js - * const { Certificate } = await import('crypto'); + * const { Certificate } = await import('node:crypto'); * const spkac = getSpkacSomehow(); * const publicKey = Certificate.exportPublicKey(spkac); * console.log(publicKey); @@ -59,8 +60,8 @@ declare module 'crypto' { static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; /** * ```js - * import { Buffer } from 'buffer'; - * const { Certificate } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); * * const spkac = getSpkacSomehow(); * console.log(Certificate.verifySpkac(Buffer.from(spkac))); @@ -95,7 +96,7 @@ declare module 'crypto' { verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; } namespace constants { - // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + // https://nodejs.org/dist/latest-v20.x/docs/api/crypto.html#crypto-constants const OPENSSL_VERSION_NUMBER: number; /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ const SSL_OP_ALL: number; @@ -111,18 +112,8 @@ declare module 'crypto' { const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ - const SSL_OP_EPHEMERAL_RSA: number; /** Allows initial connection to servers that do not support RI. */ const SSL_OP_LEGACY_SERVER_CONNECT: number; - const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - const SSL_OP_MICROSOFT_SESS_ID_BUG: number; - /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ - const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - const SSL_OP_NETSCAPE_CA_DN_BUG: number; - const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; /** Instructs OpenSSL to disable support for SSL/TLS compression. */ const SSL_OP_NO_COMPRESSION: number; const SSL_OP_NO_QUERY_MTU: number; @@ -134,16 +125,6 @@ declare module 'crypto' { const SSL_OP_NO_TLSv1: number; const SSL_OP_NO_TLSv1_1: number; const SSL_OP_NO_TLSv1_2: number; - const SSL_OP_PKCS1_CHECK_1: number; - const SSL_OP_PKCS1_CHECK_2: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ - const SSL_OP_SINGLE_DH_USE: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ - const SSL_OP_SINGLE_ECDH_USE: number; - const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - const SSL_OP_TLS_BLOCK_PADDING_BUG: number; - const SSL_OP_TLS_D5_BUG: number; /** Instructs OpenSSL to disable version rollback attack detection. */ const SSL_OP_TLS_ROLLBACK_BUG: number; const ENGINE_METHOD_RSA: number; @@ -161,7 +142,6 @@ declare module 'crypto' { const DH_CHECK_P_NOT_PRIME: number; const DH_UNABLE_TO_CHECK_GENERATOR: number; const DH_NOT_SUITABLE_GENERATOR: number; - const ALPN_ENABLED: number; const RSA_PKCS1_PADDING: number; const RSA_SSLV23_PADDING: number; const RSA_NO_PADDING: number; @@ -206,12 +186,12 @@ declare module 'crypto' { * * ```js * import { - * createReadStream - * } from 'fs'; - * import { argv } from 'process'; + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const filename = argv[2]; * @@ -243,18 +223,20 @@ declare module 'crypto' { * display the available digest algorithms. * * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is - * a `KeyObject`, its type must be `secret`. + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). * * Example: generating the sha256 HMAC of a file * * ```js * import { - * createReadStream - * } from 'fs'; - * import { argv } from 'process'; + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const filename = argv[2]; * @@ -297,8 +279,8 @@ declare module 'crypto' { * * ```js * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -320,9 +302,9 @@ declare module 'crypto' { * Example: Using `Hash` and piped streams: * * ```js - * import { createReadStream } from 'fs'; - * import { stdout } from 'process'; - * const { createHash } = await import('crypto'); + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -334,8 +316,8 @@ declare module 'crypto' { * * ```js * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -362,8 +344,8 @@ declare module 'crypto' { * ```js * // Calculate a rolling hash. * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -422,8 +404,8 @@ declare module 'crypto' { * * ```js * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const hmac = createHmac('sha256', 'a secret'); * @@ -445,11 +427,11 @@ declare module 'crypto' { * Example: Using `Hmac` and piped streams: * * ```js - * import { createReadStream } from 'fs'; - * import { stdout } from 'process'; + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const hmac = createHmac('sha256', 'a secret'); * @@ -461,8 +443,8 @@ declare module 'crypto' { * * ```js * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const hmac = createHmac('sha256', 'a secret'); * @@ -575,13 +557,13 @@ declare module 'crypto' { * Example: Converting a `CryptoKey` instance to a `KeyObject`: * * ```js - * const { webcrypto, KeyObject } = await import('crypto'); - * const { subtle } = webcrypto; + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; * * const key = await subtle.generateKey({ * name: 'HMAC', * hash: 'SHA-256', - * length: 256 + * length: 256, * }, true, ['sign', 'verify']); * * const keyObject = KeyObject.from(key); @@ -698,14 +680,18 @@ declare module 'crypto' { * The `password` is used to derive the cipher key and initialization vector (IV). * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * * The implementation of `crypto.createCipher()` derives keys using the OpenSSL - * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one * iteration, and no salt. The lack of salt allows dictionary attacks as the same * password always creates the same key. The low iteration count and * non-cryptographically secure hash algorithm allow passwords to be tested very * rapidly. * - * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that * developers derive a key and IV on * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when @@ -773,8 +759,8 @@ declare module 'crypto' { * const { * scrypt, * randomFill, - * createCipheriv - * } = await import('crypto'); + * createCipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -808,17 +794,17 @@ declare module 'crypto' { * import { * createReadStream, * createWriteStream, - * } from 'fs'; + * } from 'node:fs'; * * import { - * pipeline - * } from 'stream'; + * pipeline, + * } from 'node:stream'; * * const { * scrypt, * randomFill, - * createCipheriv - * } = await import('crypto'); + * createCipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -849,8 +835,8 @@ declare module 'crypto' { * const { * scrypt, * randomFill, - * createCipheriv - * } = await import('crypto'); + * createCipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -955,14 +941,18 @@ declare module 'crypto' { * authentication tag in bytes, see `CCM mode`. * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL - * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one * iteration, and no salt. The lack of salt allows dictionary attacks as the same * password always creates the same key. The low iteration count and * non-cryptographically secure hash algorithm allow passwords to be tested very * rapidly. * - * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that * developers derive a key and IV on * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. * @since v0.1.94 @@ -1023,11 +1013,11 @@ declare module 'crypto' { * Example: Using `Decipher` objects as streams: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { * scryptSync, - * createDecipheriv - * } = await import('crypto'); + * createDecipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -1042,6 +1032,7 @@ declare module 'crypto' { * * let decrypted = ''; * decipher.on('readable', () => { + * let chunk; * while (null !== (chunk = decipher.read())) { * decrypted += chunk.toString('utf8'); * } @@ -1064,12 +1055,12 @@ declare module 'crypto' { * import { * createReadStream, * createWriteStream, - * } from 'fs'; - * import { Buffer } from 'buffer'; + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; * const { * scryptSync, - * createDecipheriv - * } = await import('crypto'); + * createDecipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -1089,11 +1080,11 @@ declare module 'crypto' { * Example: Using the `decipher.update()` and `decipher.final()` methods: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { * scryptSync, - * createDecipheriv - * } = await import('crypto'); + * createDecipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -1190,25 +1181,30 @@ declare module 'crypto' { format?: KeyFormat | undefined; type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined; passphrase?: string | Buffer | undefined; + encoding?: string | undefined; } interface PublicKeyInput { key: string | Buffer; format?: KeyFormat | undefined; type?: 'pkcs1' | 'spki' | undefined; + encoding?: string | undefined; } /** * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. * * ```js * const { - * generateKey - * } = await import('crypto'); + * generateKey, + * } = await import('node:crypto'); * - * generateKey('hmac', { length: 64 }, (err, key) => { + * generateKey('hmac', { length: 512 }, (err, key) => { * if (err) throw err; * console.log(key.export().toString('hex')); // 46e..........620 * }); * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. * @since v15.0.0 * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. */ @@ -1224,12 +1220,15 @@ declare module 'crypto' { * * ```js * const { - * generateKeySync - * } = await import('crypto'); + * generateKeySync, + * } = await import('node:crypto'); * - * const key = generateKeySync('hmac', { length: 64 }); + * const key = generateKeySync('hmac', { length: 512 }); * console.log(key.export().toString('hex')); // e89..........41e * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. * @since v15.0.0 * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. */ @@ -1291,7 +1290,7 @@ declare module 'crypto' { type DSAEncoding = 'der' | 'ieee-p1363'; interface SigningOptions { /** - * @See crypto.constants.RSA_PKCS1_PADDING + * @see crypto.constants.RSA_PKCS1_PADDING */ padding?: number | undefined; saltLength?: number | undefined; @@ -1305,6 +1304,7 @@ declare module 'crypto' { interface VerifyKeyObjectInput extends SigningOptions { key: KeyObject; } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} type KeyLike = string | Buffer | KeyObject; /** * The `Sign` class is a utility for generating signatures. It can be used in one @@ -1324,11 +1324,11 @@ declare module 'crypto' { * const { * generateKeyPairSync, * createSign, - * createVerify - * } = await import('crypto'); + * createVerify, + * } = await import('node:crypto'); * * const { privateKey, publicKey } = generateKeyPairSync('ec', { - * namedCurve: 'sect239k1' + * namedCurve: 'sect239k1', * }); * * const sign = createSign('SHA256'); @@ -1349,8 +1349,8 @@ declare module 'crypto' { * const { * generateKeyPairSync, * createSign, - * createVerify - * } = await import('crypto'); + * createVerify, + * } = await import('node:crypto'); * * const { privateKey, publicKey } = generateKeyPairSync('rsa', { * modulusLength: 2048, @@ -1459,8 +1459,8 @@ declare module 'crypto' { * be passed instead of a public key. * @since v0.1.92 */ - verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; - verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, signature: NodeJS.ArrayBufferView): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; } /** * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an @@ -1490,11 +1490,11 @@ declare module 'crypto' { * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * const { - * createDiffieHellman - * } = await import('crypto'); + * createDiffieHellman, + * } = await import('node:crypto'); * * // Generate Alice's keys... * const alice = createDiffieHellman(2048); @@ -1600,7 +1600,7 @@ declare module 'crypto' { * A bit field containing any warnings and/or errors resulting from a check * performed during initialization of the `DiffieHellman` object. * - * The following values are valid for this property (as defined in `constants`module): + * The following values are valid for this property (as defined in `node:constants` module): * * * `DH_CHECK_P_NOT_SAFE_PRIME` * * `DH_CHECK_P_NOT_PRIME` @@ -1635,16 +1635,16 @@ declare module 'crypto' { */ const DiffieHellmanGroup: DiffieHellmanGroupConstructor; interface DiffieHellmanGroupConstructor { - new(name: string): DiffieHellmanGroup; + new (name: string): DiffieHellmanGroup; (name: string): DiffieHellmanGroup; readonly prototype: DiffieHellmanGroup; } type DiffieHellmanGroup = Omit; /** * Creates a predefined `DiffieHellmanGroup` key exchange object. The - * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, - * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The - * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing * the keys (with `diffieHellman.setPublicKey()`, for example). The * advantage of using this method is that the parties do not have to * generate nor exchange a group modulus beforehand, saving both processor @@ -1654,8 +1654,8 @@ declare module 'crypto' { * * ```js * const { - * getDiffieHellman - * } = await import('crypto'); + * getDiffieHellman, + * } = await import('node:crypto'); * const alice = getDiffieHellman('modp14'); * const bob = getDiffieHellman('modp14'); * @@ -1685,9 +1685,6 @@ declare module 'crypto' { * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be * thrown if any of the input arguments specify invalid values or types. * - * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, - * please specify a `digest` explicitly. - * * The `iterations` argument must be a number set as high as possible. The * higher the number of iterations, the more secure the derived key will be, * but will take a longer amount of time to complete. @@ -1699,8 +1696,8 @@ declare module 'crypto' { * * ```js * const { - * pbkdf2 - * } = await import('crypto'); + * pbkdf2, + * } = await import('node:crypto'); * * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { * if (err) throw err; @@ -1708,18 +1705,6 @@ declare module 'crypto' { * }); * ``` * - * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been - * deprecated and use should be avoided. - * - * ```js - * import crypto from 'crypto'; - * crypto.DEFAULT_ENCODING = 'hex'; - * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { - * if (err) throw err; - * console.log(derivedKey); // '3745e48...aa39b34' - * }); - * ``` - * * An array of supported digest functions can be retrieved using {@link getHashes}. * * This API uses libuv's threadpool, which can have surprising and @@ -1735,9 +1720,6 @@ declare module 'crypto' { * If an error occurs an `Error` will be thrown, otherwise the derived key will be * returned as a `Buffer`. * - * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, - * please specify a `digest` explicitly. - * * The `iterations` argument must be a number set as high as possible. The * higher the number of iterations, the more secure the derived key will be, * but will take a longer amount of time to complete. @@ -1749,23 +1731,13 @@ declare module 'crypto' { * * ```js * const { - * pbkdf2Sync - * } = await import('crypto'); + * pbkdf2Sync, + * } = await import('node:crypto'); * * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); * console.log(key.toString('hex')); // '3745e48...08d59ae' * ``` * - * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use - * should be avoided. - * - * ```js - * import crypto from 'crypto'; - * crypto.DEFAULT_ENCODING = 'hex'; - * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); - * console.log(key); // '3745e48...aa39b34' - * ``` - * * An array of supported digest functions can be retrieved using {@link getHashes}. * @since v0.9.3 */ @@ -1781,8 +1753,8 @@ declare module 'crypto' { * ```js * // Asynchronous * const { - * randomBytes - * } = await import('crypto'); + * randomBytes, + * } = await import('node:crypto'); * * randomBytes(256, (err, buf) => { * if (err) throw err; @@ -1797,8 +1769,8 @@ declare module 'crypto' { * ```js * // Synchronous * const { - * randomBytes - * } = await import('crypto'); + * randomBytes, + * } = await import('node:crypto'); * * const buf = randomBytes(256); * console.log( @@ -1830,7 +1802,7 @@ declare module 'crypto' { * Return a random integer `n` such that `min <= n < max`. This * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). * - * The range (`max - min`) must be less than 2^48. `min` and `max` must + * The range (`max - min`) must be less than 248. `min` and `max` must * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). * * If the `callback` function is not provided, the random integer is @@ -1839,8 +1811,8 @@ declare module 'crypto' { * ```js * // Asynchronous * const { - * randomInt - * } = await import('crypto'); + * randomInt, + * } = await import('node:crypto'); * * randomInt(3, (err, n) => { * if (err) throw err; @@ -1851,8 +1823,8 @@ declare module 'crypto' { * ```js * // Synchronous * const { - * randomInt - * } = await import('crypto'); + * randomInt, + * } = await import('node:crypto'); * * const n = randomInt(3); * console.log(`Random number chosen from (0, 1, 2): ${n}`); @@ -1861,8 +1833,8 @@ declare module 'crypto' { * ```js * // With `min` argument * const { - * randomInt - * } = await import('crypto'); + * randomInt, + * } = await import('node:crypto'); * * const n = randomInt(1, 7); * console.log(`The dice rolled: ${n}`); @@ -1880,8 +1852,8 @@ declare module 'crypto' { * Synchronous version of {@link randomFill}. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFillSync } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); * * const buf = Buffer.alloc(10); * console.log(randomFillSync(buf).toString('hex')); @@ -1897,8 +1869,8 @@ declare module 'crypto' { * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFillSync } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); * * const a = new Uint32Array(10); * console.log(Buffer.from(randomFillSync(a).buffer, @@ -1926,8 +1898,8 @@ declare module 'crypto' { * If the `callback` function is not provided, an error will be thrown. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFill } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); * * const buf = Buffer.alloc(10); * randomFill(buf, (err, buf) => { @@ -1956,8 +1928,8 @@ declare module 'crypto' { * distribution and have no meaningful lower or upper bounds. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFill } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); * * const a = new Uint32Array(10); * randomFill(a, (err, buf) => { @@ -2023,8 +1995,8 @@ declare module 'crypto' { * * ```js * const { - * scrypt - * } = await import('crypto'); + * scrypt, + * } = await import('node:crypto'); * * // Using the factory defaults. * scrypt('password', 'salt', 64, (err, derivedKey) => { @@ -2059,8 +2031,8 @@ declare module 'crypto' { * * ```js * const { - * scryptSync - * } = await import('crypto'); + * scryptSync, + * } = await import('node:crypto'); * // Using the factory defaults. * * const key1 = scryptSync('password', 'salt', 64); @@ -2131,8 +2103,8 @@ declare module 'crypto' { /** * ```js * const { - * getCiphers - * } = await import('crypto'); + * getCiphers, + * } = await import('node:crypto'); * * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] * ``` @@ -2143,8 +2115,8 @@ declare module 'crypto' { /** * ```js * const { - * getCurves - * } = await import('crypto'); + * getCurves, + * } = await import('node:crypto'); * * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] * ``` @@ -2158,7 +2130,8 @@ declare module 'crypto' { */ function getFips(): 1 | 0; /** - * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available. + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. * @since v10.0.0 * @param bool `true` to enable FIPS mode. */ @@ -2166,8 +2139,8 @@ declare module 'crypto' { /** * ```js * const { - * getHashes - * } = await import('crypto'); + * getHashes, + * } = await import('node:crypto'); * * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] * ``` @@ -2182,11 +2155,11 @@ declare module 'crypto' { * Instances of the `ECDH` class can be created using the {@link createECDH} function. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * const { - * createECDH - * } = await import('crypto'); + * createECDH, + * } = await import('node:crypto'); * * // Generate Alice's keys... * const alice = createECDH('secp521r1'); @@ -2227,8 +2200,8 @@ declare module 'crypto' { * ```js * const { * createECDH, - * ECDH - * } = await import('crypto'); + * ECDH, + * } = await import('node:crypto'); * * const ecdh = createECDH('secp256k1'); * ecdh.generateKeys(); @@ -2306,7 +2279,7 @@ declare module 'crypto' { * If `encoding` is specified, a string is returned; otherwise a `Buffer` is * returned. * @since v0.11.14 - * @param [encoding] The `encoding` of the return value. + * @param encoding The `encoding` of the return value. * @param [format='uncompressed'] * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. */ @@ -2335,8 +2308,10 @@ declare module 'crypto' { */ function createECDH(curveName: string): ECDH; /** - * This function is based on a constant-time algorithm. - * Returns true if `a` is equal to `b`, without leaking timing information that + * This function compares the underlying bytes that represent the given`ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that * would allow an attacker to guess one of the values. This is suitable for * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). * @@ -2348,14 +2323,16 @@ declare module 'crypto' { * entry, such as `Uint16Array`, the result will be computed using the platform * byte order. * + * **When both of the inputs are `Float32Array`s or`Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor`Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code * is timing-safe. Care should be taken to ensure that the surrounding code does * not introduce timing vulnerabilities. * @since v6.6.0 */ function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; - /** @deprecated since v10.0.0 */ - const DEFAULT_ENCODING: BufferEncoding; type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; type KeyFormat = 'pem' | 'der' | 'jwk'; interface BasePrivateKeyEncodingOptions { @@ -2553,8 +2530,8 @@ declare module 'crypto' { * * ```js * const { - * generateKeyPairSync - * } = await import('crypto'); + * generateKeyPairSync, + * } = await import('node:crypto'); * * const { * publicKey, @@ -2563,14 +2540,14 @@ declare module 'crypto' { * modulusLength: 4096, * publicKeyEncoding: { * type: 'spki', - * format: 'pem' + * format: 'pem', * }, * privateKeyEncoding: { * type: 'pkcs8', * format: 'pem', * cipher: 'aes-256-cbc', - * passphrase: 'top secret' - * } + * passphrase: 'top secret', + * }, * }); * ``` * @@ -2632,21 +2609,21 @@ declare module 'crypto' { * * ```js * const { - * generateKeyPair - * } = await import('crypto'); + * generateKeyPair, + * } = await import('node:crypto'); * * generateKeyPair('rsa', { * modulusLength: 4096, * publicKeyEncoding: { * type: 'spki', - * format: 'pem' + * format: 'pem', * }, * privateKeyEncoding: { * type: 'pkcs8', * format: 'pem', * cipher: 'aes-256-cbc', - * passphrase: 'top secret' - * } + * passphrase: 'top secret', + * }, * }, (err, publicKey, privateKey) => { * // Handle errors and use the generated key pair. * }); @@ -2968,11 +2945,16 @@ declare module 'crypto' { * If the `callback` function is provided this function uses libuv's threadpool. * @since v12.0.0 */ - function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; function verify( algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, - key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, signature: NodeJS.ArrayBufferView, callback: (error: Error | null, result: boolean) => void ): void; @@ -3042,10 +3024,10 @@ declare module 'crypto' { * of the input arguments specify invalid values or types. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { - * hkdf - * } = await import('crypto'); + * hkdf, + * } = await import('node:crypto'); * * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { * if (err) throw err; @@ -3054,7 +3036,7 @@ declare module 'crypto' { * ``` * @since v15.0.0 * @param digest The digest algorithm to use. - * @param ikm The input keying material. It must be at least one byte in length. + * @param ikm The input keying material. Must be provided but can be zero-length. * @param salt The salt value. Must be provided but can be zero-length. * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` @@ -3071,17 +3053,17 @@ declare module 'crypto' { * types, or if the derived key cannot be generated. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { - * hkdfSync - * } = await import('crypto'); + * hkdfSync, + * } = await import('node:crypto'); * * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' * ``` * @since v15.0.0 * @param digest The digest algorithm to use. - * @param ikm The input keying material. It must be at least one byte in length. + * @param ikm The input keying material. Must be provided but can be zero-length. * @param salt The salt value. Must be provided but can be zero-length. * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` @@ -3121,12 +3103,13 @@ declare module 'crypto' { */ disableEntropyCache?: boolean | undefined; } + type UUID = `${string}-${string}-${string}-${string}-${string}`; /** * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a * cryptographic pseudorandom number generator. * @since v15.6.0, v14.17.0 */ - function randomUUID(options?: RandomUUIDOptions): string; + function randomUUID(options?: RandomUUIDOptions): UUID; interface X509CheckOptions { /** * @default 'always' @@ -3154,7 +3137,7 @@ declare module 'crypto' { * its information. * * ```js - * const { X509Certificate } = await import('crypto'); + * const { X509Certificate } = await import('node:crypto'); * * const x509 = new X509Certificate('{... pem encoded cert ...}'); * @@ -3184,23 +3167,53 @@ declare module 'crypto' { readonly fingerprint256: string; /** * The SHA-512 fingerprint of this certificate. - * @since v16.14.0 + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 */ - readonly fingerprint512: string; + readonly fingerprint512: string; /** * The complete subject of this certificate. * @since v15.6.0 */ readonly subject: string; /** - * The subject alternative name specified for this certificate or `undefined` - * if not available. + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. * @since v15.6.0 */ readonly subjectAltName: string | undefined; /** - * The information access content of this certificate or `undefined` if not - * available. + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. * @since v15.6.0 */ readonly infoAccess: string | undefined; @@ -3444,36 +3457,29 @@ declare module 'crypto' { * * `engine` could be either an id or a path to the engine's shared library. * - * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. - * The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`is a bit field taking one of or a mix of the following flags (defined in`crypto.constants`): * - * - `crypto.constants.ENGINE_METHOD_RSA` - * - `crypto.constants.ENGINE_METHOD_DSA` - * - `crypto.constants.ENGINE_METHOD_DH` - * - `crypto.constants.ENGINE_METHOD_RAND` - * - `crypto.constants.ENGINE_METHOD_EC` - * - `crypto.constants.ENGINE_METHOD_CIPHERS` - * - `crypto.constants.ENGINE_METHOD_DIGESTS` - * - `crypto.constants.ENGINE_METHOD_PKEY_METHS` - * - `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` - * - `crypto.constants.ENGINE_METHOD_ALL` - * - `crypto.constants.ENGINE_METHOD_NONE` - * - * The flags below are deprecated in OpenSSL-1.1.0. - * - * - `crypto.constants.ENGINE_METHOD_ECDH` - * - `crypto.constants.ENGINE_METHOD_ECDSA` - * - `crypto.constants.ENGINE_METHOD_STORE` + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` * @since v0.11.11 - * @param [flags=crypto.constants.ENGINE_METHOD_ALL] + * @param flags */ function setEngine(engine: string, flags?: number): void; /** - * A convenient alias for `crypto.webcrypto.getRandomValues()`. - * This implementation is not compliant with the Web Crypto spec, - * to write web-compatible code use `crypto.webcrypto.getRandomValues()` instead. + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. * @since v17.4.0 - * @returns Returns `typedArray`. + * @return Returns `typedArray`. */ function getRandomValues(typedArray: T): T; /** @@ -3638,7 +3644,7 @@ declare module 'crypto' { * The UUID is generated using a cryptographic pseudorandom number generator. * @since v16.7.0 */ - randomUUID(): string; + randomUUID(): UUID; CryptoKey: CryptoKeyConstructor; } // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts index 247328d..02d7106 100644 --- a/node_modules/@types/node/dgram.d.ts +++ b/node_modules/@types/node/dgram.d.ts @@ -1,13 +1,13 @@ /** - * The `dgram` module provides an implementation of UDP datagram sockets. + * The `node:dgram` module provides an implementation of UDP datagram sockets. * * ```js - * import dgram from 'dgram'; + * import dgram from 'node:dgram'; * * const server = dgram.createSocket('udp4'); * * server.on('error', (err) => { - * console.log(`server error:\n${err.stack}`); + * console.error(`server error:\n${err.stack}`); * server.close(); * }); * @@ -23,7 +23,7 @@ * 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) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dgram.js) */ declare module 'dgram' { import { AddressInfo } from 'node:net'; @@ -98,8 +98,8 @@ declare module 'dgram' { * 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'; + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; * * if (cluster.isPrimary) { * cluster.fork(); // Works ok. @@ -116,7 +116,7 @@ declare module 'dgram' { 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. + * 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 @@ -142,12 +142,12 @@ declare module 'dgram' { * Example of a UDP server listening on port 41234: * * ```js - * import dgram from 'dgram'; + * import dgram from 'node:dgram'; * * const server = dgram.createSocket('udp4'); * * server.on('error', (err) => { - * console.log(`server error:\n${err.stack}`); + * console.error(`server error:\n${err.stack}`); * server.close(); * }); * @@ -284,8 +284,8 @@ declare module 'dgram' { * Example of sending a UDP packet to a port on `localhost`; * * ```js - * import dgram from 'dgram'; - * import { Buffer } from 'buffer'; + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; * * const message = Buffer.from('Some bytes'); * const client = dgram.createSocket('udp4'); @@ -297,8 +297,8 @@ declare module 'dgram' { * 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'; + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('Some '); * const buf2 = Buffer.from('bytes'); @@ -316,8 +316,8 @@ declare module 'dgram' { * Example of sending a UDP packet using a socket connected to a port on`localhost`: * * ```js - * import dgram from 'dgram'; - * import { Buffer } from 'buffer'; + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; * * const message = Buffer.from('Some bytes'); * const client = dgram.createSocket('udp4'); diff --git a/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/@types/node/diagnostics_channel.d.ts index 3dcaa03..5f19b20 100644 --- a/node_modules/@types/node/diagnostics_channel.d.ts +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -1,11 +1,11 @@ /** - * The `diagnostics_channel` module provides an API to create named channels + * The `node: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'; + * import diagnostics_channel from 'node:diagnostics_channel'; * ``` * * It is intended that a module writer wanting to report diagnostics messages @@ -19,8 +19,8 @@ * 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) + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js) */ declare module 'diagnostics_channel' { /** @@ -31,7 +31,7 @@ declare module 'diagnostics_channel' { * performance-sensitive code. * * ```js - * import diagnostics_channel from 'diagnostics_channel'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * if (diagnostics_channel.hasSubscribers('my-channel')) { * // There are subscribers, prepare and publish message @@ -43,12 +43,12 @@ declare module 'diagnostics_channel' { */ function hasSubscribers(name: string | symbol): boolean; /** - * This is the primary entry-point for anyone wanting to interact with a named + * This is the primary entry-point for anyone wanting to publish to 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'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * ``` @@ -58,9 +58,46 @@ declare module 'diagnostics_channel' { */ 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 'node: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 {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node: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 + * @return `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 + * pipeline. It is used 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 @@ -77,7 +114,7 @@ declare module 'diagnostics_channel' { * performance-sensitive code. * * ```js - * import diagnostics_channel from 'diagnostics_channel'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * @@ -90,17 +127,16 @@ declare module 'diagnostics_channel' { 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. + * 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'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * * channel.publish({ - * some: 'message' + * some: 'message', * }); * ``` * @since v15.1.0, v14.17.0 @@ -113,7 +149,7 @@ declare module 'diagnostics_channel' { * errors thrown in the message handler will trigger an `'uncaughtException'`. * * ```js - * import diagnostics_channel from 'diagnostics_channel'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * @@ -122,6 +158,7 @@ declare module 'diagnostics_channel' { * }); * ``` * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} * @param onMessage The handler to receive channel messages */ subscribe(onMessage: ChannelListener): void; @@ -129,7 +166,7 @@ declare module 'diagnostics_channel' { * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. * * ```js - * import diagnostics_channel from 'diagnostics_channel'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * @@ -142,6 +179,7 @@ declare module 'diagnostics_channel' { * channel.unsubscribe(onMessage); * ``` * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} * @param onMessage The previous subscribed handler to remove * @return `true` if the handler was found, `false` otherwise. */ diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts index 305367b..db3febc 100644 --- a/node_modules/@types/node/dns.d.ts +++ b/node_modules/@types/node/dns.d.ts @@ -1,5 +1,5 @@ /** - * The `dns` module enables name resolution. For example, use it to look up IP + * The `node:dns` module enables name resolution. For example, use it to look up IP * addresses of host names. * * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the @@ -9,7 +9,7 @@ * system do, use {@link lookup}. * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * * dns.lookup('example.org', (err, address, family) => { * console.log('address: %j family: IPv%s', address, family); @@ -17,13 +17,13 @@ * // address: "93.184.216.34" family: IPv4 * ``` * - * All other functions in the `dns` module connect to an actual DNS server to + * All other functions in the `node:dns` module connect to an actual DNS server to * perform name resolution. They will always use the network to perform DNS * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform * DNS queries, bypassing other name-resolution facilities. * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * * dns.resolve4('archive.org', (err, addresses) => { * if (err) throw err; @@ -42,7 +42,7 @@ * ``` * * See the `Implementation considerations section` for more information. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/dns.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dns.js) */ declare module 'dns' { import * as dnsPromises from 'node:dns/promises'; @@ -76,8 +76,8 @@ declare module 'dns' { /** * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or * AAAA (IPv6) record. All `option` properties are optional. If `options` is an - * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 - * and IPv6 addresses are both returned if found. + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. * * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the * properties `address` and `family`. @@ -89,14 +89,14 @@ declare module 'dns' { * * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. * The implementation uses an operating system facility that can associate names - * with addresses, and vice versa. This implementation can have subtle but + * with addresses and vice versa. This implementation can have subtle but * important consequences on the behavior of any Node.js program. Please take some * time to consult the `Implementation considerations section` before using`dns.lookup()`. * * Example usage: * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * const options = { * family: 6, * hints: dns.ADDRCONFIG | dns.V4MAPPED, @@ -135,7 +135,7 @@ declare module 'dns' { * On an error, `err` is an `Error` object, where `err.code` is the error code. * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { * console.log(hostname, service); * // Prints: localhost ssh @@ -174,7 +174,7 @@ declare module 'dns' { type: 'AAAA'; } export interface CaaRecord { - critial: number; + critical: number; issue?: string | undefined; issuewild?: string | undefined; iodef?: string | undefined; @@ -291,7 +291,7 @@ declare module 'dns' { function __promisify__(hostname: string, options?: ResolveOptions): Promise; } /** - * Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function * will contain an array of IPv6 addresses. * @since v0.1.16 * @param hostname Host name to resolve. @@ -333,7 +333,7 @@ declare module 'dns' { function __promisify__(hostname: string): Promise; } /** - * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of * objects with the following properties: * * * `flags` @@ -484,6 +484,14 @@ declare module 'dns' { * @since v0.1.16 */ export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + /** + * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + export function getDefaultResultOrder(): 'ipv4first' | 'verbatim'; /** * Sets the IP address and port of servers to be used when performing DNS * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted @@ -535,7 +543,7 @@ declare module 'dns' { * * `ipv4first`: sets default `verbatim` `false`. * * `verbatim`: sets default `verbatim` `true`. * - * The default is `ipv4first` and {@link setDefaultResultOrder} have higher + * The default is `verbatim` and {@link setDefaultResultOrder} have higher * priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default * dns orders in workers. * @since v16.4.0, v14.18.0 @@ -582,7 +590,7 @@ declare module 'dns' { * other resolvers: * * ```js - * const { Resolver } = require('dns'); + * const { Resolver } = require('node:dns'); * const resolver = new Resolver(); * resolver.setServers(['4.4.4.4']); * @@ -592,7 +600,7 @@ declare module 'dns' { * }); * ``` * - * The following methods from the `dns` module are available: + * The following methods from the `node:dns` module are available: * * * `resolver.getServers()` * * `resolver.resolve()` @@ -625,6 +633,7 @@ declare module 'dns' { resolve4: typeof resolve4; resolve6: typeof resolve6; resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; resolveCname: typeof resolveCname; resolveMx: typeof resolveMx; resolveNaptr: typeof resolveNaptr; @@ -639,7 +648,7 @@ declare module 'dns' { * This allows programs to specify outbound interfaces when used on multi-homed * systems. * - * If a v4 or v6 address is not specified, it is set to the default, and the + * If a v4 or v6 address is not specified, it is set to the default and the * operating system will choose a local address automatically. * * The resolver will use the v4 local address when making requests to IPv4 DNS diff --git a/node_modules/@types/node/dns/promises.d.ts b/node_modules/@types/node/dns/promises.d.ts index 77cd807..4c151e4 100644 --- a/node_modules/@types/node/dns/promises.d.ts +++ b/node_modules/@types/node/dns/promises.d.ts @@ -1,7 +1,7 @@ /** * The `dns.promises` API provides an alternative set of asynchronous DNS methods * that return `Promise` objects rather than using callbacks. The API is accessible - * via `require('dns').promises` or `require('dns/promises')`. + * via `require('node:dns').promises` or `require('node:dns/promises')`. * @since v10.6.0 */ declare module 'dns/promises' { @@ -52,7 +52,7 @@ declare module 'dns/promises' { * * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS * protocol. The implementation uses an operating system facility that can - * associate names with addresses, and vice versa. This implementation can have + * associate names with addresses and vice versa. This implementation can have * subtle but important consequences on the behavior of any Node.js program. Please * take some time to consult the `Implementation considerations section` before * using `dnsPromises.lookup()`. @@ -60,7 +60,7 @@ declare module 'dns/promises' { * Example usage: * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * const dnsPromises = dns.promises; * const options = { * family: 6, @@ -96,7 +96,7 @@ declare module 'dns/promises' { * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. * * ```js - * const dnsPromises = require('dns').promises; + * const dnsPromises = require('node:dns').promises; * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { * console.log(result.hostname, result.service); * // Prints: localhost ssh @@ -206,7 +206,7 @@ declare module 'dns/promises' { */ function resolveMx(hostname: string): Promise; /** - * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array * of objects with the following properties: * * * `flags` @@ -337,13 +337,56 @@ declare module 'dns/promises' { * * `ipv4first`: sets default `verbatim` `false`. * * `verbatim`: sets default `verbatim` `true`. * - * The default is `ipv4first` and `dnsPromises.setDefaultResultOrder()` have + * The default is `verbatim` and `dnsPromises.setDefaultResultOrder()` have * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the * default dns orders in workers. * @since v16.4.0, v14.18.0 * @param order must be `'ipv4first'` or `'verbatim'`. */ function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns').promises; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ class Resolver { constructor(options?: ResolverOptions); cancel(): void; @@ -352,6 +395,7 @@ declare module 'dns/promises' { resolve4: typeof resolve4; resolve6: typeof resolve6; resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; resolveCname: typeof resolveCname; resolveMx: typeof resolveMx; resolveNaptr: typeof resolveNaptr; diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts index fafe68a..e49b87f 100644 --- a/node_modules/@types/node/domain.d.ts +++ b/node_modules/@types/node/domain.d.ts @@ -12,7 +12,7 @@ * 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) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/domain.js) */ declare module 'domain' { import EventEmitter = require('node:events'); @@ -56,15 +56,15 @@ declare module 'domain' { exit(): void; /** * Run the supplied function in the context of the domain, implicitly - * binding all event emitters, timers, and lowlevel requests that are + * binding all event emitters, timers, and low-level 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 domain = require('node:domain'); + * const fs = require('node:fs'); * const d = domain.create(); * d.on('error', (er) => { * console.error('Caught error!', er); diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts index 4633df1..29616e1 100644 --- a/node_modules/@types/node/events.d.ts +++ b/node_modules/@types/node/events.d.ts @@ -22,7 +22,7 @@ * the `eventEmitter.emit()` method is used to trigger the event. * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; * * class MyEmitter extends EventEmitter {} * @@ -32,13 +32,12 @@ * }); * myEmitter.emit('event'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/events.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.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 { @@ -69,7 +68,6 @@ declare module 'events' { // */ // removeListener(type: string, listener: EventListener | EventListenerObject): this; // } - interface EventEmitterOptions { /** * Enables automatic capturing of promise rejection. @@ -95,10 +93,10 @@ declare module 'events' { } interface EventEmitter extends NodeJS.EventEmitter {} /** - * The `EventEmitter` class is defined and exposed by the `events` module: + * The `EventEmitter` class is defined and exposed by the `node:events` module: * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; * ``` * * All `EventEmitter`s emit the event `'newListener'` when new listeners are @@ -119,31 +117,28 @@ declare module 'events' { * semantics and does not listen to the `'error'` event. * * ```js - * const { once, EventEmitter } = require('events'); + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; * - * async function run() { - * const ee = new EventEmitter(); + * const ee = new EventEmitter(); * - * process.nextTick(() => { - * ee.emit('myevent', 42); - * }); + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); * - * const [value] = await once(ee, 'myevent'); - * console.log(value); + * const [value] = await once(ee, 'myevent'); + * console.log(value); * - * const err = new Error('kaboom'); - * process.nextTick(() => { - * ee.emit('error', err); - * }); + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); * - * try { - * await once(ee, 'myevent'); - * } catch (err) { - * console.log('error happened', err); - * } + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('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 @@ -151,13 +146,13 @@ declare module 'events' { * special handling: * * ```js - * const { EventEmitter, once } = require('events'); + * import { EventEmitter, once } from 'node:events'; * * const ee = new EventEmitter(); * * once(ee, 'error') * .then(([err]) => console.log('ok', err.message)) - * .catch((err) => console.log('error', err.message)); + * .catch((err) => console.error('error', err.message)); * * ee.emit('error', new Error('boom')); * @@ -167,7 +162,7 @@ declare module 'events' { * An `AbortSignal` can be used to cancel waiting for the event: * * ```js - * const { EventEmitter, once } = require('events'); + * import { EventEmitter, once } from 'node:events'; * * const ee = new EventEmitter(); * const ac = new AbortController(); @@ -195,25 +190,24 @@ declare module 'events' { static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; /** * ```js - * const { on, EventEmitter } = require('events'); + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; * - * (async () => { - * const ee = new EventEmitter(); + * const ee = new EventEmitter(); * - * // Emit later on - * process.nextTick(() => { - * ee.emit('foo', 'bar'); - * ee.emit('foo', 42); - * }); + * // 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 - * })(); + * 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 @@ -224,7 +218,9 @@ declare module 'events' { * An `AbortSignal` can be used to cancel waiting on events: * * ```js - * const { on, EventEmitter } = require('events'); + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * * const ac = new AbortController(); * * (async () => { @@ -256,7 +252,8 @@ declare module 'events' { * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. * * ```js - * const { EventEmitter, listenerCount } = require('events'); + * import { EventEmitter, listenerCount } from 'node:events'; + * * const myEmitter = new EventEmitter(); * myEmitter.on('event', () => {}); * myEmitter.on('event', () => {}); @@ -279,19 +276,19 @@ declare module 'events' { * event target. This is useful for debugging and diagnostic purposes. * * ```js - * const { getEventListeners, EventEmitter } = require('events'); + * import { getEventListeners, EventEmitter } from 'node:events'; * * { * const ee = new EventEmitter(); * const listener = () => console.log('Events are fun'); * ee.on('foo', listener); - * getEventListeners(ee, 'foo'); // [listener] + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] * } * { * const et = new EventTarget(); * const listener = () => console.log('Events are fun'); * et.addEventListener('foo', listener); - * getEventListeners(et, 'foo'); // [listener] + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] * } * ``` * @since v15.2.0, v14.17.0 @@ -299,10 +296,7 @@ declare module 'events' { static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; /** * ```js - * const { - * setMaxListeners, - * EventEmitter - * } = require('events'); + * import { setMaxListeners, EventEmitter } from 'node:events'; * * const target = new EventTarget(); * const emitter = new EventEmitter(); @@ -316,21 +310,63 @@ declare module 'events' { */ 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. + * 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 + * 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. + * @since v13.6.0, v12.17.0 */ static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ static readonly captureRejectionSymbol: unique symbol; /** - * Sets or gets the default captureRejection value for all emitters. + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 */ - // TODO: These should be described using static getter/setter pairs: static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners`property can be used. If this value is not a positive number, a `RangeError`is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_`EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ static defaultMaxListeners: number; } import internal = require('node:events'); @@ -370,6 +406,7 @@ declare module 'events' { * event listener to the beginning of the listeners array. * * ```js + * import { EventEmitter } from 'node:events'; * const myEE = new EventEmitter(); * myEE.on('foo', () => console.log('a')); * myEE.prependListener('foo', () => console.log('b')); @@ -399,6 +436,7 @@ declare module 'events' { * event listener to the beginning of the listeners array. * * ```js + * import { EventEmitter } from 'node:events'; * const myEE = new EventEmitter(); * myEE.once('foo', () => console.log('a')); * myEE.prependOnceListener('foo', () => console.log('b')); @@ -434,6 +472,8 @@ declare module 'events' { * will not remove them from`emit()` in progress. Subsequent events behave as expected. * * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} * const myEmitter = new MyEmitter(); * * const callbackA = () => { @@ -474,6 +514,7 @@ declare module 'events' { * recently added instance. In the example the `once('ping')`listener is removed: * * ```js + * import { EventEmitter } from 'node:events'; * const ee = new EventEmitter(); * * function pong() { @@ -542,6 +583,7 @@ declare module 'events' { * including any wrappers (such as those created by `.once()`). * * ```js + * import { EventEmitter } from 'node:events'; * const emitter = new EventEmitter(); * emitter.once('log', () => console.log('log once')); * @@ -574,7 +616,7 @@ declare module 'events' { * Returns `true` if the event had listeners, `false` otherwise. * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; * const myEmitter = new EventEmitter(); * * // First listener @@ -609,11 +651,14 @@ declare module 'events' { */ emit(eventName: string | symbol, ...args: any[]): boolean; /** - * Returns the number of listeners listening to the event named `eventName`. + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. * @since v3.2.0 * @param eventName The name of the event being listened for + * @param listener The event handler function */ - listenerCount(eventName: string | symbol): number; + listenerCount(eventName: string | symbol, listener?: Function): 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 @@ -653,7 +698,8 @@ declare module 'events' { * listeners. The values in the array are strings or `Symbol`s. * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; + * * const myEE = new EventEmitter(); * myEE.on('foo', () => {}); * myEE.on('bar', () => {}); diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts index 75c53fb..00f1cf3 100644 --- a/node_modules/@types/node/fs.d.ts +++ b/node_modules/@types/node/fs.d.ts @@ -1,22 +1,22 @@ /** - * The `fs` module enables interacting with the file system in a + * The `node:fs` module enables interacting with the file system in a * way modeled on standard POSIX functions. * * To use the promise-based APIs: * * ```js - * import * as fs from 'fs/promises'; + * import * as fs from 'node:fs/promises'; * ``` * * To use the callback and sync APIs: * * ```js - * import * as fs from 'fs'; + * import * as fs from 'node:fs'; * ``` * * All file system operations have synchronous, callback, and promise-based * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/fs.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/fs.js) */ declare module 'fs' { import * as stream from 'node:stream'; @@ -73,7 +73,7 @@ declare module 'fs' { /** * A `fs.Stats` object provides information about a file. * - * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and * their synchronous counterparts are of this type. * If `bigint` in the `options` passed to those methods is true, the numeric values * will be `bigint` instead of `number`, and the object will contain additional @@ -131,6 +131,62 @@ declare module 'fs' { * @since v0.1.21 */ export class Stats {} + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } /** * A representation of a directory entry, which can be a file or a subdirectory * within the directory, as returned by reading from an `fs.Dir`. The @@ -184,6 +240,11 @@ declare module 'fs' { * @since v10.10.0 */ name: string; + /** + * The base path that this `fs.Dirent` object refers to. + * @since v20.1.0 + */ + path: string; } /** * A class representing a directory stream. @@ -191,7 +252,7 @@ declare module 'fs' { * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. * * ```js - * import { opendir } from 'fs/promises'; + * import { opendir } from 'node:fs/promises'; * * try { * const dir = await opendir('./'); @@ -494,7 +555,7 @@ declare module 'fs' { * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). * * ```js - * import { rename } from 'fs'; + * import { rename } from 'node:fs'; * * rename('oldFile.txt', 'newFile.txt', (err) => { * if (err) throw err; @@ -527,7 +588,7 @@ declare module 'fs' { * first argument. In this case, `fs.ftruncate()` is called. * * ```js - * import { truncate } from 'fs'; + * import { truncate } from 'node:fs'; * // Assuming that 'path/file.txt' is a regular file. * truncate('path/file.txt', (err) => { * if (err) throw err; @@ -579,7 +640,7 @@ declare module 'fs' { * file: * * ```js - * import { open, close, ftruncate } from 'fs'; + * import { open, close, ftruncate } from 'node:fs'; * * function closeFd(fd) { * close(fd, (err) => { @@ -736,7 +797,7 @@ declare module 'fs' { * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. * * ```js - * import { chmod } from 'fs'; + * import { chmod } from 'node:fs'; * * chmod('my_file.txt', 0o775, (err) => { * if (err) throw err; @@ -818,7 +879,10 @@ declare module 'fs' { * * In case of an error, the `err.code` will be one of `Common System Errors`. * - * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. * Instead, user code should open/read/write the file directly and handle the * error raised if the file is not available. * @@ -835,7 +899,7 @@ declare module 'fs' { * The next program will check for the stats of the given paths: * * ```js - * import { stat } from 'fs'; + * import { stat } from 'node:fs'; * * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; * @@ -1081,6 +1145,72 @@ declare module 'fs' { ): Promise; function __promisify__(path: PathLike, options?: StatOptions): Promise; } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void + ): void; + export function statfs(path: PathLike, options: StatFsOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + } + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + } + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; /** * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -1114,14 +1244,15 @@ declare module 'fs' { * * The `type` argument is only available on Windows and ignored on other platforms. * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is - * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If - * the `target` does not exist, `'file'` will be used. Windows junction points - * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. * - * Relative targets are relative to the link’s parent directory. + * Relative targets are relative to the link's parent directory. * * ```js - * import { symlink } from 'fs'; + * import { symlink } from 'node:fs'; * * symlink('./mew', './mewtwo', callback); * ``` @@ -1136,6 +1267,7 @@ declare module 'fs' { * └── mewtwo -> ./mew * ``` * @since v0.1.31 + * @param [type='null'] */ export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; /** @@ -1161,6 +1293,7 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link symlink}. * @since v0.1.31 + * @param [type='null'] */ export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; /** @@ -1238,7 +1371,7 @@ declare module 'fs' { */ export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; /** - * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and * symbolic links. * * A canonical pathname is not necessarily unique. Hard links and bind mounts can @@ -1352,7 +1485,7 @@ declare module 'fs' { * possible exception are given to the completion callback. * * ```js - * import { unlink } from 'fs'; + * import { unlink } from 'node:fs'; * // Assuming that 'path/file.txt' is a regular file. * unlink('path/file.txt', (err) => { * if (err) throw err; @@ -1499,18 +1632,19 @@ declare module 'fs' { * * The callback is given a possible exception and, if `recursive` is `true`, the * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was - * created. + * created (for instance, if it was previously created). * * The optional `options` argument can be an integer specifying `mode` (permission * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that * exists results in an error only - * when `recursive` is false. + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. * * ```js - * import { mkdir } from 'fs'; + * import { mkdir } from 'node:fs'; * - * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. - * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { * if (err) throw err; * }); * ``` @@ -1519,7 +1653,7 @@ declare module 'fs' { * result in an error: * * ```js - * import { mkdir } from 'fs'; + * import { mkdir } from 'node:fs'; * * mkdir('/', { recursive: true }, (err) => { * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] @@ -1651,9 +1785,11 @@ declare module 'fs' { * object with an `encoding` property specifying the character encoding to use. * * ```js - * import { mkdtemp } from 'fs'; + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; * - * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { * if (err) throw err; * console.log(directory); * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 @@ -1663,11 +1799,11 @@ declare module 'fs' { * The `fs.mkdtemp()` method will append the six randomly selected characters * directly to the `prefix` string. For instance, given a directory `/tmp`, if the * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator - * (`require('path').sep`). + * (`require('node:path').sep`). * * ```js - * import { tmpdir } from 'os'; - * import { mkdtemp } from 'fs'; + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; * * // The parent directory for the new temporary directory * const tmpDir = tmpdir(); @@ -1682,7 +1818,7 @@ declare module 'fs' { * }); * * // This method is *CORRECT*: - * import { sep } from 'path'; + * import { sep } from 'node:path'; * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { * if (err) throw err; * console.log(directory); @@ -1781,6 +1917,7 @@ declare module 'fs' { | { encoding: BufferEncoding | null; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | BufferEncoding | undefined @@ -1798,6 +1935,7 @@ declare module 'fs' { | { encoding: 'buffer'; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | 'buffer', callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void @@ -1812,6 +1950,7 @@ declare module 'fs' { options: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | undefined @@ -1832,6 +1971,7 @@ declare module 'fs' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; + recursive?: boolean | undefined; }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void ): void; @@ -1847,6 +1987,7 @@ declare module 'fs' { | { encoding: BufferEncoding | null; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | BufferEncoding | null @@ -1863,6 +2004,7 @@ declare module 'fs' { | { encoding: 'buffer'; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } ): Promise; /** @@ -1875,6 +2017,7 @@ declare module 'fs' { options?: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | null @@ -1888,6 +2031,7 @@ declare module 'fs' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; + recursive?: boolean | undefined; } ): Promise; } @@ -1910,6 +2054,7 @@ declare module 'fs' { | { encoding: BufferEncoding | null; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | BufferEncoding | null @@ -1925,6 +2070,7 @@ declare module 'fs' { | { encoding: 'buffer'; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | 'buffer' ): Buffer[]; @@ -1938,6 +2084,7 @@ declare module 'fs' { options?: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | null @@ -1951,6 +2098,7 @@ declare module 'fs' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; + recursive?: boolean | undefined; } ): Dirent[]; /** @@ -2010,7 +2158,6 @@ declare module 'fs' { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - export namespace open { /** * Asynchronous open(2) - open and possibly create a file. @@ -2035,7 +2182,7 @@ declare module 'fs' { * The `atime` and `mtime` arguments follow these rules: * * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. - * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. * @since v0.4.2 */ export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; @@ -2121,6 +2268,9 @@ declare module 'fs' { * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] */ export function write( fd: number, @@ -2225,6 +2375,9 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link write}. * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] * @return The number of bytes written. */ export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; @@ -2330,6 +2483,7 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link read}. * @since v0.1.21 + * @param [position='null'] */ export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number; /** @@ -2341,7 +2495,7 @@ declare module 'fs' { * Asynchronously reads the entire contents of a file. * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * readFile('/etc/passwd', (err, data) => { * if (err) throw err; @@ -2357,7 +2511,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * readFile('/etc/passwd', 'utf8', callback); * ``` @@ -2367,7 +2521,7 @@ declare module 'fs' { * will be returned. * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * // macOS, Linux, and Windows * readFile('', (err, data) => { @@ -2384,7 +2538,7 @@ declare module 'fs' { * request is aborted the callback is called with an `AbortError`: * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * const controller = new AbortController(); * const signal = controller.signal; @@ -2517,7 +2671,7 @@ declare module 'fs' { * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. * * ```js - * import { readFileSync } from 'fs'; + * import { readFileSync } from 'node:fs'; * * // macOS, Linux, and Windows * readFileSync(''); @@ -2588,8 +2742,8 @@ declare module 'fs' { * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js - * import { writeFile } from 'fs'; - * import { Buffer } from 'buffer'; + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; * * const data = new Uint8Array(Buffer.from('Hello Node.js')); * writeFile('message.txt', data, (err) => { @@ -2601,7 +2755,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { writeFile } from 'fs'; + * import { writeFile } from 'node:fs'; * * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); * ``` @@ -2619,8 +2773,8 @@ declare module 'fs' { * to be written. * * ```js - * import { writeFile } from 'fs'; - * import { Buffer } from 'buffer'; + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; * * const controller = new AbortController(); * const { signal } = controller; @@ -2678,7 +2832,7 @@ declare module 'fs' { * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js - * import { appendFile } from 'fs'; + * import { appendFile } from 'node:fs'; * * appendFile('message.txt', 'data to append', (err) => { * if (err) throw err; @@ -2689,7 +2843,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { appendFile } from 'fs'; + * import { appendFile } from 'node:fs'; * * appendFile('message.txt', 'data to append', 'utf8', callback); * ``` @@ -2699,7 +2853,7 @@ declare module 'fs' { * not be closed automatically. * * ```js - * import { open, close, appendFile } from 'fs'; + * import { open, close, appendFile } from 'node:fs'; * * function closeFd(fd) { * close(fd, (err) => { @@ -2754,7 +2908,7 @@ declare module 'fs' { * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js - * import { appendFileSync } from 'fs'; + * import { appendFileSync } from 'node:fs'; * * try { * appendFileSync('message.txt', 'data to append'); @@ -2767,7 +2921,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { appendFileSync } from 'fs'; + * import { appendFileSync } from 'node:fs'; * * appendFileSync('message.txt', 'data to append', 'utf8'); * ``` @@ -2777,7 +2931,7 @@ declare module 'fs' { * not be closed automatically. * * ```js - * import { openSync, closeSync, appendFileSync } from 'fs'; + * import { openSync, closeSync, appendFileSync } from 'node:fs'; * * let fd; * @@ -2859,7 +3013,7 @@ declare module 'fs' { * stat object: * * ```js - * import { watchFile } from 'fs'; + * import { watchFile } from 'node:fs'; * * watchFile('message.text', (curr, prev) => { * console.log(`the current mtime is: ${curr.mtime}`); @@ -2899,7 +3053,7 @@ declare module 'fs' { bigint?: false | undefined; }) | undefined, - listener: (curr: Stats, prev: Stats) => void + listener: StatsListener ): StatWatcher; export function watchFile( filename: PathLike, @@ -2908,13 +3062,13 @@ declare module 'fs' { bigint: true; }) | undefined, - listener: (curr: BigIntStats, prev: BigIntStats) => void + listener: BigIntStatsListener ): StatWatcher; /** * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. */ - export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): StatWatcher; + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; /** * Stop watching for changes on `filename`. If `listener` is specified, only that * particular listener is removed. Otherwise, _all_ listeners are removed, @@ -2927,14 +3081,17 @@ declare module 'fs' { * @since v0.1.31 * @param listener Optional, a listener previously attached using `fs.watchFile()` */ - export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; export interface WatchOptions extends Abortable { encoding?: BufferEncoding | 'buffer' | undefined; persistent?: boolean | undefined; recursive?: boolean | undefined; } export type WatchEventType = 'rename' | 'change'; - export type WatchListener = (event: WatchEventType, filename: T) => void; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; /** * Watch for changes on `filename`, where `filename` is either a file or a * directory. @@ -2992,7 +3149,7 @@ declare module 'fs' { * Then call the `callback` argument with either true or false: * * ```js - * import { exists } from 'fs'; + * import { exists } from 'node:fs'; * * exists('/etc/passwd', (e) => { * console.log(e ? 'it exists' : 'no passwd!'); @@ -3004,7 +3161,7 @@ declare module 'fs' { * has only one boolean parameter. This is one reason `fs.access()` is recommended * instead of `fs.exists()`. * - * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing * so introduces a race condition, since other processes may change the file's * state between the two calls. Instead, user code should open/read/write the * file directly and handle the error raised if the file does not exist. @@ -3012,7 +3169,7 @@ declare module 'fs' { * **write (NOT RECOMMENDED)** * * ```js - * import { exists, open, close } from 'fs'; + * import { exists, open, close } from 'node:fs'; * * exists('myfile', (e) => { * if (e) { @@ -3036,7 +3193,7 @@ declare module 'fs' { * **write (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * open('myfile', 'wx', (err, fd) => { * if (err) { * if (err.code === 'EEXIST') { @@ -3060,7 +3217,7 @@ declare module 'fs' { * **read (NOT RECOMMENDED)** * * ```js - * import { open, close, exists } from 'fs'; + * import { open, close, exists } from 'node:fs'; * * exists('myfile', (e) => { * if (e) { @@ -3084,7 +3241,7 @@ declare module 'fs' { * **read (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * * open('myfile', 'r', (err, fd) => { * if (err) { @@ -3110,7 +3267,7 @@ declare module 'fs' { * file; the "recommended" examples are better because they use the file directly * and handle the error, if any. * - * In general, check for the existence of a file only if the file won’t be + * In general, check for the existence of a file only if the file won't be * used directly, for example when its existence is a signal from another * process. * @since v0.0.2 @@ -3135,7 +3292,7 @@ declare module 'fs' { * Node.js callbacks. `fs.existsSync()` does not use a callback. * * ```js - * import { existsSync } from 'fs'; + * import { existsSync } from 'node:fs'; * * if (existsSync('/etc/passwd')) * console.log('The path exists.'); @@ -3269,7 +3426,7 @@ declare module 'fs' { * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. * * ```js - * import { access, constants } from 'fs'; + * import { access, constants } from 'node:fs'; * * const file = 'package.json'; * @@ -3294,7 +3451,7 @@ declare module 'fs' { * }); * ``` * - * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing * so introduces a race condition, since other processes may change the file's * state between the two calls. Instead, user code should open/read/write the * file directly and handle the error raised if the file is not accessible. @@ -3302,7 +3459,7 @@ declare module 'fs' { * **write (NOT RECOMMENDED)** * * ```js - * import { access, open, close } from 'fs'; + * import { access, open, close } from 'node:fs'; * * access('myfile', (err) => { * if (!err) { @@ -3327,7 +3484,7 @@ declare module 'fs' { * **write (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * * open('myfile', 'wx', (err, fd) => { * if (err) { @@ -3352,7 +3509,7 @@ declare module 'fs' { * **read (NOT RECOMMENDED)** * * ```js - * import { access, open, close } from 'fs'; + * import { access, open, close } from 'node:fs'; * access('myfile', (err) => { * if (err) { * if (err.code === 'ENOENT') { @@ -3380,7 +3537,7 @@ declare module 'fs' { * **read (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * * open('myfile', 'r', (err, fd) => { * if (err) { @@ -3442,7 +3599,7 @@ declare module 'fs' { * the method will return `undefined`. * * ```js - * import { accessSync, constants } from 'fs'; + * import { accessSync, constants } from 'node:fs'; * * try { * accessSync('etc/passwd', constants.R_OK | constants.W_OK); @@ -3472,8 +3629,8 @@ declare module 'fs' { end?: number | undefined; } /** - * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream - * returned by this method has a default `highWaterMark` of 64 kb. + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. * * `options` can include `start` and `end` values to read a range of bytes from * the file instead of the entire file. Both `start` and `end` are inclusive and @@ -3499,7 +3656,7 @@ declare module 'fs' { * also required. * * ```js - * import { createReadStream } from 'fs'; + * import { createReadStream } from 'node:fs'; * * // Create a stream from some character device. * const stream = createReadStream('/dev/input/event0'); @@ -3527,7 +3684,7 @@ declare module 'fs' { * An example to read the last 10 bytes of a file which is 100 bytes long: * * ```js - * import { createReadStream } from 'fs'; + * import { createReadStream } from 'node:fs'; * * createReadStream('sample.txt', { start: 90, end: 99 }); * ``` @@ -3551,7 +3708,7 @@ declare module 'fs' { * By default, the stream will emit a `'close'` event after it has been * destroyed. Set the `emitClose` option to `false` to change this behavior. * - * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev`, and `close`. Overriding `write()`without `writev()` can reduce * performance as some optimizations (`_writev()`) * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. @@ -3606,7 +3763,7 @@ declare module 'fs' { * copy-on-write, then the operation will fail. * * ```js - * import { copyFile, constants } from 'fs'; + * import { copyFile, constants } from 'node:fs'; * * function callback(err) { * if (err) throw err; @@ -3649,7 +3806,7 @@ declare module 'fs' { * copy-on-write, then the operation will fail. * * ```js - * import { copyFileSync, constants } from 'fs'; + * import { copyFileSync, constants } from 'node:fs'; * * // destination.txt will be created or overwritten by default. * copyFileSync('source.txt', 'destination.txt'); @@ -3682,6 +3839,7 @@ declare module 'fs' { * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v12.9.0 + * @param [position='null'] */ export function writev(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; export function writev( @@ -3701,6 +3859,7 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link writev}. * @since v12.9.0 + * @param [position='null'] * @return The number of bytes written. */ export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; @@ -3717,6 +3876,7 @@ declare module 'fs' { * If this method is invoked as its `util.promisify()` ed version, it returns * a promise for an `Object` with `bytesRead` and `buffers` properties. * @since v13.13.0, v12.17.0 + * @param [position='null'] */ export function readv(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; export function readv( @@ -3736,10 +3896,14 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link readv}. * @since v13.13.0, v12.17.0 + * @param [position='null'] * @return The number of bytes read. */ export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; export interface OpenDirOptions { + /** + * @default 'utf8' + */ encoding?: BufferEncoding | undefined; /** * Number of directory entries that are buffered @@ -3748,6 +3912,10 @@ declare module 'fs' { * @default 32 */ bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean; } /** * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). @@ -3810,6 +3978,10 @@ declare module 'fs' { * @default true */ force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; /** * When `true` timestamps from `src` will * be preserved. diff --git a/node_modules/@types/node/fs/promises.d.ts b/node_modules/@types/node/fs/promises.d.ts index aca2fd5..f5f1583 100644 --- a/node_modules/@types/node/fs/promises.d.ts +++ b/node_modules/@types/node/fs/promises.d.ts @@ -14,6 +14,7 @@ declare module 'fs/promises' { import { ReadableStream } from 'node:stream/web'; import { BigIntStats, + BigIntStatsFs, BufferEncodingOption, constants as fsConstants, CopyOptions, @@ -30,7 +31,9 @@ declare module 'fs/promises' { RmDirOptions, RmOptions, StatOptions, + StatFsOptions, Stats, + StatsFs, TimeLike, WatchEventType, WatchOptions, @@ -38,10 +41,9 @@ declare module 'fs/promises' { WriteVResult, } from 'node:fs'; import { Interface as ReadlineInterface } from 'node:readline'; - interface FileChangeInfo { eventType: WatchEventType; - filename: T; + filename: T | null; } interface FlagAndOpenMode { mode?: Mode | undefined; @@ -112,8 +114,8 @@ declare module 'fs/promises' { */ chmod(mode: Mode): Promise; /** - * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream - * returned by this method has a default `highWaterMark` of 64 kb. + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. * * `options` can include `start` and `end` values to read a range of bytes from * the file instead of the entire file. Both `start` and `end` are inclusive and @@ -131,7 +133,7 @@ declare module 'fs/promises' { * destroyed. Set the `emitClose` option to `false` to change this behavior. * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * const fd = await open('/dev/input/event0'); * // Create a stream from some character device. @@ -157,7 +159,7 @@ declare module 'fs/promises' { * An example to read the last 10 bytes of a file which is 100 bytes long: * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * const fd = await open('sample.txt'); * fd.createReadStream({ start: 90, end: 99 }); @@ -196,7 +198,7 @@ declare module 'fs/promises' { * device. The specific implementation is operating system and device specific. * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. * @since v10.0.0 - * @return Fufills with `undefined` upon success. + * @return Fulfills with `undefined` upon success. */ sync(): Promise; /** @@ -217,11 +219,13 @@ declare module 'fs/promises' { /** * Returns a `ReadableStream` that may be used to read the files data. * - * An error will be thrown if this method is called more than once or is called after the `FileHandle` is closed - * or closing. + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. * * ```js - * import { open } from 'node:fs/promises'; + * import { + * open, + * } from 'node:fs/promises'; * * const file = await open('./some/file/to/read'); * @@ -231,8 +235,8 @@ declare module 'fs/promises' { * await file.close(); * ``` * - * While the `ReadableStream` will read the file to completion, it will not close the `FileHandle` automatically. User code must still call the `fileHandle.close()` method. - * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. * @since v17.0.0 * @experimental */ @@ -286,7 +290,8 @@ declare module 'fs/promises' { | null ): Promise; /** - * Convenience method to create a `readline` interface and stream over the file. For example: + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. * * ```js * import { open } from 'node:fs/promises'; @@ -297,9 +302,7 @@ declare module 'fs/promises' { * console.log(line); * } * ``` - * * @since v18.11.0 - * @param options See `filehandle.createReadStream()` for the options. */ readLines(options?: CreateReadStreamOptions): ReadlineInterface; /** @@ -326,7 +329,7 @@ declare module 'fs/promises' { * The following example retains only the first four bytes of the file: * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * let filehandle = null; * try { @@ -353,7 +356,7 @@ declare module 'fs/promises' { utimes(atime: TimeLike, mtime: TimeLike): Promise; /** * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an - * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. * The promise is resolved with no arguments upon success. * @@ -383,10 +386,10 @@ declare module 'fs/promises' { * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v10.0.0 - * @param [offset=0] The start position from within `buffer` where the data to write begins. + * @param offset The start position from within `buffer` where the data to write begins. * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. - * @param position The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. - * See the POSIX pwrite(2) documentation for more detail. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. */ write( buffer: TBuffer, @@ -417,14 +420,14 @@ declare module 'fs/promises' { * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v12.9.0 - * @param position The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current * position. */ writev(buffers: ReadonlyArray, position?: number): Promise; /** * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s * @since v13.13.0, v12.17.0 - * @param position The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. * @return Fulfills upon success an object containing two properties: */ readv(buffers: ReadonlyArray, position?: number): Promise; @@ -433,7 +436,7 @@ declare module 'fs/promises' { * complete. * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * let filehandle; * try { @@ -447,9 +450,7 @@ declare module 'fs/promises' { */ close(): Promise; } - const constants: typeof fsConstants; - /** * Tests a user's permissions for the file or directory specified by `path`. * The `mode` argument is an optional integer that specifies the accessibility @@ -463,8 +464,7 @@ declare module 'fs/promises' { * written by the current process. * * ```js - * import { access } from 'fs/promises'; - * import { constants } from 'fs'; + * import { access, constants } from 'node:fs/promises'; * * try { * await access('/etc/passwd', constants.R_OK | constants.W_OK); @@ -493,14 +493,13 @@ declare module 'fs/promises' { * will be made to remove the destination. * * ```js - * import { constants } from 'fs'; - * import { copyFile } from 'fs/promises'; + * import { copyFile, constants } from 'node:fs/promises'; * * try { * await copyFile('source.txt', 'destination.txt'); * console.log('source.txt was copied to destination.txt'); * } catch { - * console.log('The file could not be copied'); + * console.error('The file could not be copied'); * } * * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. @@ -508,7 +507,7 @@ declare module 'fs/promises' { * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); * console.log('source.txt was copied to destination.txt'); * } catch { - * console.log('The file could not be copied'); + * console.error('The file could not be copied'); * } * ``` * @since v10.0.0 @@ -570,6 +569,19 @@ declare module 'fs/promises' { * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory * that exists results in a * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` * @since v10.0.0 * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. */ @@ -612,7 +624,7 @@ declare module 'fs/promises' { * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. * * ```js - * import { readdir } from 'fs/promises'; + * import { readdir } from 'node:fs/promises'; * * try { * const files = await readdir(path); @@ -630,6 +642,7 @@ declare module 'fs/promises' { options?: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | null @@ -645,6 +658,7 @@ declare module 'fs/promises' { | { encoding: 'buffer'; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | 'buffer' ): Promise; @@ -658,6 +672,7 @@ declare module 'fs/promises' { options?: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | null @@ -671,6 +686,7 @@ declare module 'fs/promises' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; + recursive?: boolean | undefined; } ): Promise; /** @@ -700,11 +716,14 @@ declare module 'fs/promises' { /** * Creates a symbolic link. * - * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path - * to be absolute. When using `'junction'`, the `target` argument will - * automatically be normalized to absolute path. + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. * @since v10.0.0 - * @param [type='file'] + * @param [type='null'] * @return Fulfills with `undefined` upon success. */ function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; @@ -745,6 +764,23 @@ declare module 'fs/promises' { } ): Promise; function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + } + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + } + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; /** * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. * @since v10.0.0 @@ -800,7 +836,7 @@ declare module 'fs/promises' { * * * Values can be either numbers representing Unix epoch time, `Date`s, or a * numeric string like `'123456789.0'`. - * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. * @since v10.0.0 * @return Fulfills with `undefined` upon success. */ @@ -845,10 +881,12 @@ declare module 'fs/promises' { * object with an `encoding` property specifying the character encoding to use. * * ```js - * import { mkdtemp } from 'fs/promises'; + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; * * try { - * await mkdtemp(path.join(os.tmpdir(), 'foo-')); + * await mkdtemp(join(tmpdir(), 'foo-')); * } catch (err) { * console.error(err); * } @@ -857,9 +895,9 @@ declare module 'fs/promises' { * The `fsPromises.mkdtemp()` method will append the six randomly selected * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing * platform-specific path separator - * (`require('path').sep`). + * (`require('node:path').sep`). * @since v10.0.0 - * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + * @return Fulfills with a string containing the file system path of the newly created temporary directory. */ function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** @@ -876,7 +914,7 @@ declare module 'fs/promises' { function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an - * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. * * The `encoding` option is ignored if `data` is a buffer. @@ -899,8 +937,8 @@ declare module 'fs/promises' { * to be written. * * ```js - * import { writeFile } from 'fs/promises'; - * import { Buffer } from 'buffer'; + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; * * try { * const controller = new AbortController(); @@ -963,11 +1001,25 @@ declare module 'fs/promises' { * with an error. On FreeBSD, a representation of the directory's contents will be * returned. * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a * request is aborted the promise returned is rejected with an `AbortError`: * * ```js - * import { readFile } from 'fs/promises'; + * import { readFile } from 'node:fs/promises'; * * try { * const controller = new AbortController(); @@ -1046,7 +1098,7 @@ declare module 'fs/promises' { * Example using async iteration: * * ```js - * import { opendir } from 'fs/promises'; + * import { opendir } from 'node:fs/promises'; * * try { * const dir = await opendir('./'); @@ -1067,7 +1119,7 @@ declare module 'fs/promises' { * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. * * ```js - * const { watch } = require('fs/promises'); + * const { watch } = require('node:fs/promises'); * * const ac = new AbortController(); * const { signal } = ac; diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts index 80fd4cf..7414561 100644 --- a/node_modules/@types/node/globals.d.ts +++ b/node_modules/@types/node/globals.d.ts @@ -53,7 +53,7 @@ interface AbortController { /** * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. */ - abort(): void; + abort(reason?: any): void; } /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ @@ -62,6 +62,9 @@ interface AbortSignal extends EventTarget { * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ readonly aborted: boolean; + readonly reason: any; + onabort: null | ((this: AbortSignal, event: Event) => any); + throwIfAborted(): void; } declare var AbortController: typeof globalThis extends {onmessage: any; AbortController: infer T} @@ -157,7 +160,7 @@ declare namespace NodeJS { /** * Name of the script [if this function was defined in a script] */ - getFileName(): string | null; + getFileName(): string | undefined; /** * Current line number [if this function was defined in a script] diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts index e14de6c..cb50335 100644 --- a/node_modules/@types/node/http.d.ts +++ b/node_modules/@types/node/http.d.ts @@ -1,5 +1,5 @@ /** - * To use the HTTP server and client one must `require('http')`. + * To use the HTTP server and client one must `require('node:http')`. * * The HTTP interfaces in Node.js are designed to support many features * of the protocol which have been traditionally difficult to use. @@ -37,13 +37,14 @@ * 'Host', 'example.com', * 'accepT', '*' ] * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http.js) */ declare module 'http' { import * as stream from 'node:stream'; import { URL } from 'node:url'; - import { TcpSocketConnectOpts, Socket, Server as NetServer, LookupFunction } from 'node:net'; import { LookupOptions } from 'node:dns'; + import { EventEmitter } from 'node:events'; + import { TcpSocketConnectOpts, Socket, Server as NetServer, LookupFunction } from 'node:net'; // incoming headers will never contain number interface IncomingHttpHeaders extends NodeJS.Dict { accept?: string | undefined; @@ -144,6 +145,7 @@ declare module 'http' { socketPath?: string | undefined; timeout?: number | undefined; uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean; } interface ServerOptions< Request extends typeof IncomingMessage = typeof IncomingMessage, @@ -164,6 +166,12 @@ declare module 'http' { * @since v18.0.0 */ requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean; /** * The number of milliseconds of inactivity a server needs to wait for additional incoming data, * after it has finished writing the last response, before a socket will be destroyed. @@ -177,6 +185,13 @@ declare module 'http' { * @default 30000 */ connectionsCheckingInterval?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; /** * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. * Using the insecure parser should be avoided. @@ -322,7 +337,8 @@ declare module 'http' { */ closeAllConnections(): void; /** - * Closes all connections connected to this server which are not sending a request or waiting for a response. + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. * @since v18.2.0 */ closeIdleConnections(): void; @@ -334,15 +350,10 @@ declare module 'http' { addListener(event: 'checkContinue', listener: RequestListener): this; addListener(event: 'checkExpectation', listener: RequestListener): this; addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - addListener( - event: 'connect', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + addListener(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + addListener(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; addListener(event: 'request', listener: RequestListener): this; - addListener( - event: 'upgrade', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + addListener(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; emit(event: string, ...args: any[]): boolean; emit(event: 'close'): boolean; emit(event: 'connection', socket: Socket): boolean; @@ -360,6 +371,7 @@ declare module 'http' { ): boolean; emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; emit(event: 'connect', req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit(event: 'dropRequest', req: InstanceType, socket: stream.Duplex): boolean; emit( event: 'request', req: InstanceType, @@ -375,6 +387,7 @@ declare module 'http' { on(event: 'checkExpectation', listener: RequestListener): this; on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; on(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; on(event: 'request', listener: RequestListener): this; on(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; @@ -385,15 +398,10 @@ declare module 'http' { once(event: 'checkContinue', listener: RequestListener): this; once(event: 'checkExpectation', listener: RequestListener): this; once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - once( - event: 'connect', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + once(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + once(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; once(event: 'request', listener: RequestListener): this; - once( - event: 'upgrade', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + once(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: 'close', listener: () => void): this; prependListener(event: 'connection', listener: (socket: Socket) => void): this; @@ -402,15 +410,10 @@ declare module 'http' { prependListener(event: 'checkContinue', listener: RequestListener): this; prependListener(event: 'checkExpectation', listener: RequestListener): this; prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - prependListener( - event: 'connect', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + prependListener(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; prependListener(event: 'request', listener: RequestListener): this; - prependListener( - event: 'upgrade', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + prependListener(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: 'close', listener: () => void): this; prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; @@ -419,19 +422,14 @@ declare module 'http' { prependOnceListener(event: 'checkContinue', listener: RequestListener): this; prependOnceListener(event: 'checkExpectation', listener: RequestListener): this; prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - prependOnceListener( - event: 'connect', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + prependOnceListener(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; prependOnceListener(event: 'request', listener: RequestListener): this; - prependOnceListener( - event: 'upgrade', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + prependOnceListener(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; } /** - * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from - * the perspective of the participants of HTTP transaction. + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. * @since v0.1.17 */ class OutgoingMessage extends stream.Writable { @@ -450,7 +448,7 @@ declare module 'http' { */ readonly headersSent: boolean; /** - * Aliases of `outgoingMessage.socket` + * Alias of `outgoingMessage.socket`. * @since v0.3.0 * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. */ @@ -471,15 +469,33 @@ declare module 'http' { */ setTimeout(msecs: number, callback?: () => void): this; /** - * Sets a single header value for the header object. + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. * @since v0.4.0 * @param name Header name * @param value Header value */ setHeader(name: string, value: number | string | ReadonlyArray): this; /** - * Gets the value of HTTP header with the given name. If such a name doesn't - * exist in message, it will be `undefined`. + * Append a single header value for the header object. + * + * If the value is an array, this is equivalent of calling this method multiple + * times. + * + * If there were no previous value for the header, this is equivalent of calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | ReadonlyArray): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. * @since v0.4.0 * @param name Name of header */ @@ -492,8 +508,8 @@ declare module 'http' { * values. All header names are lowercase. * * The object returned by the `outgoingMessage.getHeaders()` method does - * not prototypically inherit from the JavaScript Object. This means that - * typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, * and others are not defined and will not work. * * ```js @@ -507,8 +523,8 @@ declare module 'http' { */ getHeaders(): OutgoingHttpHeaders; /** - * Returns an array of names of headers of the outgoing outgoingMessage. All - * names are lowercase. + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. * @since v7.7.0 */ getHeaderNames(): string[]; @@ -535,11 +551,11 @@ declare module 'http' { /** * Adds HTTP trailers (headers but at the end of the message) to the message. * - * Trailers are **only** be emitted if the message is chunked encoded. If not, - * the trailer will be silently discarded. + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. * * HTTP requires the `Trailer` header to be sent to emit trailers, - * with a list of header fields in its value, e.g. + * with a list of header field names in its value, e.g. * * ```js * message.writeHead(200, { 'Content-Type': 'text/plain', @@ -555,7 +571,7 @@ declare module 'http' { */ addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; /** - * Compulsorily flushes the message headers + * Flushes the message headers. * * For efficiency reason, Node.js normally buffers the message headers * until `outgoingMessage.end()` is called or the first chunk of message data @@ -563,7 +579,7 @@ declare module 'http' { * packet. * * It is usually desired (it saves a TCP round-trip), but not when the first - * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the message. * @since v1.6.0 */ flushHeaders(): void; @@ -603,6 +619,13 @@ declare module 'http' { * @since v0.11.8 */ statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length`header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; constructor(req: Request); assignSocket(socket: Socket): void; detachSocket(socket: Socket): void; @@ -619,7 +642,7 @@ declare module 'http' { * early hints message. The optional `callback` argument will be called when * the response message has been written. * - * Example: + * **Example** * * ```js * const earlyHintsLink = '; rel=preload; as=style'; @@ -633,15 +656,14 @@ declare module 'http' { * ]; * response.writeEarlyHints({ * 'link': earlyHintsLinks, - * 'x-trace-id': 'id for diagnostics' + * 'x-trace-id': 'id for diagnostics', * }); * * const earlyHintsCallback = () => console.log('early hints message sent'); * response.writeEarlyHints({ - * 'link': earlyHintsLinks + * 'link': earlyHintsLinks, * }, earlyHintsCallback); * ``` - * * @since v18.11.0 * @param hints An object containing the values of headers * @param callback Will be called when the response message has been written @@ -665,7 +687,7 @@ declare module 'http' { * response * .writeHead(200, { * 'Content-Length': Buffer.byteLength(body), - * 'Content-Type': 'text/plain' + * 'Content-Type': 'text/plain', * }) * .end(body); * ``` @@ -696,12 +718,12 @@ declare module 'http' { * }); * ``` * - * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js - * does not check whether `Content-Length` and the length of the body which has + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has * been transmitted are equal or not. * * Attempting to set a header field name or value that contains invalid characters - * will result in a `TypeError` being thrown. + * will result in a \[`Error`\]\[\] being thrown. * @since v0.1.30 */ writeHead( @@ -711,7 +733,7 @@ declare module 'http' { ): this; writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; /** - * Sends an HTTP/1.1 102 Processing message to the client, indicating that + * Sends a HTTP/1.1 102 Processing message to the client, indicating that * the request body should be sent. * @since v10.0.0 */ @@ -750,8 +772,11 @@ declare module 'http' { * * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. * - * Node.js does not check whether Content-Length and the length of the - * body which has been transmitted are equal or not. + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the`Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. * @since v0.1.17 */ class ClientRequest extends OutgoingMessage { @@ -778,7 +803,7 @@ declare module 'http' { * may run into a 'ECONNRESET' error. * * ```js - * const http = require('http'); + * const http = require('node:http'); * * // Server has a 5 seconds keep-alive timeout by default * http @@ -802,7 +827,7 @@ declare module 'http' { * automatic error retry base on it. * * ```js - * const http = require('http'); + * const http = require('node:http'); * const agent = new http.Agent({ keepAlive: true }); * * function retriableRequest() { @@ -881,19 +906,13 @@ declare module 'http' { * @deprecated */ addListener(event: 'abort', listener: () => void): this; - addListener( - event: 'connect', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; addListener(event: 'continue', listener: () => void): this; addListener(event: 'information', listener: (info: InformationEvent) => void): this; addListener(event: 'response', listener: (response: IncomingMessage) => void): this; addListener(event: 'socket', listener: (socket: Socket) => void): this; addListener(event: 'timeout', listener: () => void): this; - addListener( - event: 'upgrade', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; addListener(event: 'close', listener: () => void): this; addListener(event: 'drain', listener: () => void): this; addListener(event: 'error', listener: (err: Error) => void): this; @@ -941,19 +960,13 @@ declare module 'http' { * @deprecated */ prependListener(event: 'abort', listener: () => void): this; - prependListener( - event: 'connect', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; prependListener(event: 'continue', listener: () => void): this; prependListener(event: 'information', listener: (info: InformationEvent) => void): this; prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; prependListener(event: 'socket', listener: (socket: Socket) => void): this; prependListener(event: 'timeout', listener: () => void): this; - prependListener( - event: 'upgrade', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; prependListener(event: 'close', listener: () => void): this; prependListener(event: 'drain', listener: () => void): this; prependListener(event: 'error', listener: (err: Error) => void): this; @@ -965,19 +978,13 @@ declare module 'http' { * @deprecated */ prependOnceListener(event: 'abort', listener: () => void): this; - prependOnceListener( - event: 'connect', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; prependOnceListener(event: 'continue', listener: () => void): this; prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; prependOnceListener(event: 'timeout', listener: () => void): this; - prependOnceListener( - event: 'upgrade', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; prependOnceListener(event: 'close', listener: () => void): this; prependOnceListener(event: 'drain', listener: () => void): this; prependOnceListener(event: 'error', listener: (err: Error) => void): this; @@ -989,7 +996,7 @@ declare module 'http' { /** * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to * access response - * status, headers and data. + * status, headers, and data. * * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to * parse and emit the incoming HTTP headers and payload, as the underlying socket @@ -1027,7 +1034,7 @@ declare module 'http' { * const req = http.request({ * host: '127.0.0.1', * port: 8080, - * method: 'POST' + * method: 'POST', * }, (res) => { * res.resume(); * res.on('end', () => { @@ -1069,7 +1076,7 @@ declare module 'http' { * // { 'user-agent': 'curl/7.22.0', * // host: '127.0.0.1:8000', * // accept: '*' } - * console.log(request.getHeaders()); + * console.log(request.headers); * ``` * * Duplicates in raw headers are handled in the following ways, depending on the @@ -1077,12 +1084,30 @@ declare module 'http' { * * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. * * `set-cookie` is always an array. Duplicates are added to the array. - * * For duplicate `cookie` headers, the values are joined together with '; '. - * * For all other headers, the values are joined together with ', '. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. * @since v0.1.5 */ headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; /** * The raw request/response headers list exactly as they were received. * @@ -1113,6 +1138,13 @@ declare module 'http' { * @since v0.3.0 */ trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; /** * The raw request/response trailer keys and values exactly as they were * received. Only populated at the `'end'` event. @@ -1145,14 +1177,14 @@ declare module 'http' { * To parse the URL into its parts: * * ```js - * new URL(request.url, `http://${request.getHeaders().host}`); + * new URL(request.url, `http://${request.headers.host}`); * ``` * - * When `request.url` is `'/status?name=ryan'` and`request.getHeaders().host` is `'localhost:3000'`: + * When `request.url` is `'/status?name=ryan'` and `request.headers.host` is`'localhost:3000'`: * * ```console * $ node - * > new URL(request.url, `http://${request.getHeaders().host}`) + * > new URL(request.url, `http://${request.headers.host}`) * URL { * href: 'http://localhost:3000/status?name=ryan', * origin: 'http://localhost:3000', @@ -1272,16 +1304,16 @@ declare module 'http' { * hostname: 'localhost', * port: 80, * path: '/', - * agent: false // Create a new agent just for this one request + * agent: false, // Create a new agent just for this one request * }, (res) => { * // Do stuff with response * }); * ``` * @since v0.3.4 */ - class Agent { + class Agent extends EventEmitter { /** - * By default set to 256\. For agents with `keepAlive` enabled, this + * By default set to 256. For agents with `keepAlive` enabled, this * sets the maximum number of sockets that will be left open in the free * state. * @since v0.11.7 @@ -1377,10 +1409,10 @@ declare module 'http' { * upload a file with a POST request, then write to the `ClientRequest` object. * * ```js - * const http = require('http'); + * const http = require('node:http'); * * const postData = JSON.stringify({ - * 'msg': 'Hello World!' + * 'msg': 'Hello World!', * }); * * const options = { @@ -1390,8 +1422,8 @@ declare module 'http' { * method: 'POST', * headers: { * 'Content-Type': 'application/json', - * 'Content-Length': Buffer.byteLength(postData) - * } + * 'Content-Length': Buffer.byteLength(postData), + * }, * }; * * const req = http.request(options, (res) => { @@ -1478,7 +1510,7 @@ declare module 'http' { * * `'data'` any number of times, on the `res` object * * (connection closed here) * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'` * * `'close'` * * `'close'` on the `res` object * @@ -1486,7 +1518,7 @@ declare module 'http' { * events will be emitted in the following order: * * * (`req.destroy()` called here) - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * If `req.destroy()` is called before the connection succeeds, the following @@ -1494,7 +1526,7 @@ declare module 'http' { * * * `'socket'` * * (`req.destroy()` called here) - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * If `req.destroy()` is called after the response is received, the following @@ -1505,7 +1537,7 @@ declare module 'http' { * * `'data'` any number of times, on the `res` object * * (`req.destroy()` called here) * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'error'` on the `res` object with an error with message `'Error: aborted'`and code `'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * `'close'` on the `res` object * @@ -1541,16 +1573,13 @@ declare module 'http' { * Setting the `timeout` option or using the `setTimeout()` function will * not abort the request or do anything besides add a `'timeout'` event. * - * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the - * request itself. + * Passing an `AbortSignal` and then calling `abort()` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`and the `cause`, if one was provided. * @since v0.3.6 */ function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - function request( - url: string | URL, - options: RequestOptions, - callback?: (res: IncomingMessage) => void, - ): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; /** * Since most requests are GET requests without bodies, Node.js provides this * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the @@ -1602,7 +1631,7 @@ declare module 'http' { * const server = http.createServer((req, res) => { * res.writeHead(200, { 'Content-Type': 'application/json' }); * res.end(JSON.stringify({ - * data: 'Hello World!' + * data: 'Hello World!', * })); * }); * @@ -1613,32 +1642,76 @@ declare module 'http' { */ function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - /** - * Performs the low-level validations on the provided name that are done when `res.setHeader(name, value)` is called. - * Passing illegal value as name will result in a TypeError being thrown, identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. - * @param name Header name + * Performs the low-level validations on the provided `name` that are done when`res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * Examples: + * + * Example: + * + * ```js + * const { validateHeaderName } = require('node:http'); + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` * @since v14.3.0 + * @param [label='Header name'] Label for error message. */ function validateHeaderName(name: string): void; /** - * Performs the low-level validations on the provided value that are done when `res.setHeader(name, value)` is called. - * Passing illegal value as value will result in a TypeError being thrown. - * - Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. - * - Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * Performs the low-level validations on the provided `value` that are done when`res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * const { validateHeaderValue } = require('node:http'); + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 * @param name Header name * @param value Header value - * @since v14.3.0 */ function validateHeaderValue(name: string, value: string): void; - /** - * Set the maximum number of idle HTTP parsers. Default: 1000. - * @param count + * Set the maximum number of idle HTTP parsers. * @since v18.8.0, v16.18.0 + * @param [max=1000] */ - function setMaxIdleHTTPParsers(count: number): void; - + function setMaxIdleHTTPParsers(max: number): void; let globalAgent: Agent; /** * Read-only property specifying the maximum allowed size of HTTP headers in bytes. diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts index 0e36826..8005709 100644 --- a/node_modules/@types/node/http2.d.ts +++ b/node_modules/@types/node/http2.d.ts @@ -1,12 +1,12 @@ /** - * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It - * can be accessed using: + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * ``` * @since v8.4.0 - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http2.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http2.js) */ declare module 'http2' { import EventEmitter = require('node:events'); @@ -151,7 +151,7 @@ declare module 'http2' { priority(options: StreamPriorityOptions): void; /** * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const client = http2.connect('http://example.org:8000'); * const { NGHTTP2_CANCEL } = http2.constants; * const req = client.request({ ':path': '/' }); @@ -171,7 +171,7 @@ declare module 'http2' { * trailers can be sent. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond(undefined, { waitForTrailers: true }); @@ -332,7 +332,7 @@ declare module 'http2' { * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond({ ':status': 200 }); @@ -357,7 +357,7 @@ declare module 'http2' { pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; /** * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond({ ':status': 200 }); @@ -365,16 +365,15 @@ declare module 'http2' { * }); * ``` * - * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event - * will be emitted immediately after queuing the last chunk of payload data to be - * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing - * header fields to the peer. + * Initiates a response. When the `options.waitForTrailers` option is set, the`'wantTrailers'` event will be emitted immediately after queuing the last chunk + * of payload data to be sent. The `http2stream.sendTrailers()` method can then be + * used to sent trailing header fields to the peer. * * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond({ ':status': 200 }, { waitForTrailers: true }); @@ -397,8 +396,8 @@ declare module 'http2' { * automatically. * * ```js - * const http2 = require('http2'); - * const fs = require('fs'); + * const http2 = require('node:http2'); + * const fs = require('node:fs'); * * const server = http2.createServer(); * server.on('stream', (stream) => { @@ -408,7 +407,7 @@ declare module 'http2' { * const headers = { * 'content-length': stat.size, * 'last-modified': stat.mtime.toUTCString(), - * 'content-type': 'text/plain; charset=utf-8' + * 'content-type': 'text/plain; charset=utf-8', * }; * stream.respondWithFD(fd, headers); * stream.on('close', () => fs.closeSync(fd)); @@ -439,8 +438,8 @@ declare module 'http2' { * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. * * ```js - * const http2 = require('http2'); - * const fs = require('fs'); + * const http2 = require('node:http2'); + * const fs = require('node:fs'); * * const server = http2.createServer(); * server.on('stream', (stream) => { @@ -450,7 +449,7 @@ declare module 'http2' { * const headers = { * 'content-length': stat.size, * 'last-modified': stat.mtime.toUTCString(), - * 'content-type': 'text/plain; charset=utf-8' + * 'content-type': 'text/plain; charset=utf-8', * }; * stream.respondWithFD(fd, headers, { waitForTrailers: true }); * stream.on('wantTrailers', () => { @@ -482,7 +481,7 @@ declare module 'http2' { * Example using a file path: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * function statCheck(stat, headers) { @@ -500,7 +499,7 @@ declare module 'http2' { * } * } catch (err) { * // Perform actual error handling. - * console.log(err); + * console.error(err); * } * stream.end(); * } @@ -516,7 +515,7 @@ declare module 'http2' { * results to determine if the file has been modified to return an appropriate`304` response: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * function statCheck(stat, headers) { @@ -549,7 +548,7 @@ declare module 'http2' { * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respondWithFile('/some/file', @@ -748,7 +747,7 @@ declare module 'http2' { * the delta. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * const server = http2.createServer(); * const expectedWindowSize = 2 ** 20; @@ -854,11 +853,11 @@ declare module 'http2' { * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const clientSession = http2.connect('https://localhost:1234'); * const { * HTTP2_HEADER_PATH, - * HTTP2_HEADER_STATUS + * HTTP2_HEADER_STATUS, * } = http2.constants; * * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); @@ -928,7 +927,7 @@ declare module 'http2' { * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * const server = http2.createServer(); * server.on('session', (session) => { @@ -969,7 +968,7 @@ declare module 'http2' { * authoritative responses. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const options = getSecureOptionsSomehow(); * const server = http2.createSecureServer(options); * server.on('stream', (stream) => { @@ -995,7 +994,7 @@ declare module 'http2' { * server using the `http2.createSecureServer()` method: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const options = getSecureOptionsSomehow(); * options.origins = ['https://example.com', 'https://example.org']; * const server = http2.createSecureServer(options); @@ -1053,7 +1052,6 @@ declare module 'http2' { */ unknownProtocolTimeout?: number | undefined; selectPadding?(frameLen: number, maxFrameLen: number): number; - createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; } export interface ClientSessionOptions extends SessionOptions { maxReservedRemoteStreams?: number | undefined; @@ -1437,7 +1435,7 @@ declare module 'http2' { */ readonly headersSent: boolean; /** - * A reference to the original HTTP2 request object. + * A reference to the original HTTP2 `request` object. * @since v15.7.0 */ readonly req: Http2ServerRequest; @@ -1458,7 +1456,7 @@ declare module 'http2' { * All other interactions will be routed directly to the socket. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer((req, res) => { * const ip = req.socket.remoteAddress; * const port = req.socket.remotePort; @@ -1641,7 +1639,7 @@ declare module 'http2' { * This sends a chunk of the response body. This method may * be called multiple times to provide successive parts of the body. * - * In the `http` module, the response body is omitted when the + * In the `node:http` module, the response body is omitted when the * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. * * `chunk` can be a string or a buffer. If `chunk` is a string, @@ -1676,7 +1674,7 @@ declare module 'http2' { * The `hints` is an object containing the values of headers to be sent with * early hints message. * - * Example: + * **Example** * * ```js * const earlyHintsLink = '; rel=preload; as=style'; @@ -1690,12 +1688,9 @@ declare module 'http2' { * ]; * response.writeEarlyHints({ * 'link': earlyHintsLinks, - * 'x-trace-id': 'id for diagnostics' * }); * ``` - * * @since v18.11.0 - * @param hints An object containing the values of headers */ writeEarlyHints(hints: Record): void; /** @@ -2028,7 +2023,7 @@ declare module 'http2' { * for use with the `HTTP2-Settings` header field. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * const packed = http2.getPackedSettings({ enablePush: false }); * @@ -2053,7 +2048,7 @@ declare module 'http2' { * with browser clients. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * // Create an unencrypted HTTP/2 server. * // Since there are no browsers known that support @@ -2064,12 +2059,12 @@ declare module 'http2' { * server.on('stream', (stream, headers) => { * stream.respond({ * 'content-type': 'text/html; charset=utf-8', - * ':status': 200 + * ':status': 200, * }); * stream.end('

Hello World

'); * }); * - * server.listen(80); + * server.listen(8000); * ``` * @since v8.4.0 * @param onRequestHandler See `Compatibility API` @@ -2080,12 +2075,12 @@ declare module 'http2' { * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. * * ```js - * const http2 = require('http2'); - * const fs = require('fs'); + * const http2 = require('node:http2'); + * const fs = require('node:fs'); * * const options = { * key: fs.readFileSync('server-key.pem'), - * cert: fs.readFileSync('server-cert.pem') + * cert: fs.readFileSync('server-cert.pem'), * }; * * // Create a secure HTTP/2 server @@ -2094,12 +2089,12 @@ declare module 'http2' { * server.on('stream', (stream, headers) => { * stream.respond({ * 'content-type': 'text/html; charset=utf-8', - * ':status': 200 + * ':status': 200, * }); * stream.end('

Hello World

'); * }); * - * server.listen(80); + * server.listen(8443); * ``` * @since v8.4.0 * @param onRequestHandler See `Compatibility API` @@ -2110,7 +2105,7 @@ declare module 'http2' { * Returns a `ClientHttp2Session` instance. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const client = http2.connect('https://localhost:1234'); * * // Use the client diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts index bda367d..76fca92 100644 --- a/node_modules/@types/node/https.d.ts +++ b/node_modules/@types/node/https.d.ts @@ -1,7 +1,7 @@ /** * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a * separate module. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/https.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/https.js) */ declare module 'https' { import { Duplex } from 'node:stream'; @@ -59,22 +59,9 @@ declare module 'https' { closeIdleConnections(): void; addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - addListener( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - addListener( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - addListener( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; addListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; addListener(event: 'close', listener: () => void): this; @@ -84,29 +71,13 @@ declare module 'https' { addListener(event: 'checkContinue', listener: http.RequestListener): this; addListener(event: 'checkExpectation', listener: http.RequestListener): this; addListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - addListener( - event: 'connect', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + addListener(event: 'connect', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; addListener(event: 'request', listener: http.RequestListener): this; - addListener( - event: 'upgrade', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + addListener(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; emit(event: string, ...args: any[]): boolean; emit(event: 'keylog', line: Buffer, tlsSocket: tls.TLSSocket): boolean; - emit( - event: 'newSession', - sessionId: Buffer, - sessionData: Buffer, - callback: (err: Error, resp: Buffer) => void, - ): boolean; - emit( - event: 'OCSPRequest', - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; emit(event: 'secureConnection', tlsSocket: tls.TLSSocket): boolean; emit(event: 'tlsClientError', err: Error, tlsSocket: tls.TLSSocket): boolean; @@ -117,39 +88,32 @@ declare module 'https' { emit( event: 'checkContinue', req: InstanceType, - res: InstanceType & { req: InstanceType }, + res: InstanceType & { + req: InstanceType; + } ): boolean; emit( event: 'checkExpectation', req: InstanceType, - res: InstanceType & { req: InstanceType }, + res: InstanceType & { + req: InstanceType; + } ): boolean; emit(event: 'clientError', err: Error, socket: Duplex): boolean; emit(event: 'connect', req: InstanceType, socket: Duplex, head: Buffer): boolean; emit( event: 'request', req: InstanceType, - res: InstanceType & { req: InstanceType }, + res: InstanceType & { + req: InstanceType; + } ): boolean; emit(event: 'upgrade', req: InstanceType, socket: Duplex, head: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - on( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - on( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - on( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; on(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; on(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; on(event: 'close', listener: () => void): this; @@ -164,22 +128,9 @@ declare module 'https' { on(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - once( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - once( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - once( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; once(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; once(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; once(event: 'close', listener: () => void): this; @@ -194,22 +145,9 @@ declare module 'https' { once(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - prependListener( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - prependListener( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - prependListener( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; prependListener(event: 'close', listener: () => void): this; @@ -219,33 +157,14 @@ declare module 'https' { prependListener(event: 'checkContinue', listener: http.RequestListener): this; prependListener(event: 'checkExpectation', listener: http.RequestListener): this; prependListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - prependListener( - event: 'connect', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + prependListener(event: 'connect', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; prependListener(event: 'request', listener: http.RequestListener): this; - prependListener( - event: 'upgrade', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + prependListener(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - prependOnceListener( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - prependOnceListener( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - prependOnceListener( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependOnceListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; prependOnceListener(event: 'close', listener: () => void): this; @@ -255,25 +174,19 @@ declare module 'https' { prependOnceListener(event: 'checkContinue', listener: http.RequestListener): this; prependOnceListener(event: 'checkExpectation', listener: http.RequestListener): this; prependOnceListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - prependOnceListener( - event: 'connect', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + prependOnceListener(event: 'connect', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; prependOnceListener(event: 'request', listener: http.RequestListener): this; - prependOnceListener( - event: 'upgrade', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + prependOnceListener(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; } /** * ```js * // curl -k https://localhost:8000/ - * const https = require('https'); - * const fs = require('fs'); + * const https = require('node:https'); + * const fs = require('node:fs'); * * const options = { * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), - * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), * }; * * https.createServer(options, (req, res) => { @@ -285,12 +198,12 @@ declare module 'https' { * Or * * ```js - * const https = require('https'); - * const fs = require('fs'); + * const https = require('node:https'); + * const fs = require('node:fs'); * * const options = { * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), - * passphrase: 'sample' + * passphrase: 'sample', * }; * * https.createServer(options, (req, res) => { @@ -326,13 +239,13 @@ declare module 'https' { * upload a file with a POST request, then write to the `ClientRequest` object. * * ```js - * const https = require('https'); + * const https = require('node:https'); * * const options = { * hostname: 'encrypted.google.com', * port: 443, * path: '/', - * method: 'GET' + * method: 'GET', * }; * * const req = https.request(options, (res) => { @@ -359,7 +272,7 @@ declare module 'https' { * path: '/', * method: 'GET', * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), - * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), * }; * options.agent = new https.Agent(options); * @@ -378,7 +291,7 @@ declare module 'https' { * method: 'GET', * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), - * agent: false + * agent: false, * }; * * const req = https.request(options, (res) => { @@ -399,9 +312,9 @@ declare module 'https' { * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): * * ```js - * const tls = require('tls'); - * const https = require('https'); - * const crypto = require('crypto'); + * const tls = require('node:tls'); + * const https = require('node:https'); + * const crypto = require('node:crypto'); * * function sha256(s) { * return crypto.createHash('sha256').update(s).digest('base64'); @@ -418,7 +331,7 @@ declare module 'https' { * return err; * } * - * // Pin the public key, similar to HPKP pin-sha25 pinning + * // Pin the public key, similar to HPKP pin-sha256 pinning * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; * if (sha256(cert.pubkey) !== pubkey256) { * const msg = 'Certificate verification error: ' + @@ -493,15 +406,8 @@ declare module 'https' { * @since v0.3.6 * @param options Accepts all `options` from `request`, with some differences in default values: */ - function request( - options: RequestOptions | string | URL, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; - function request( - url: string | URL, - options: RequestOptions, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; /** * Like `http.get()` but for HTTPS. * @@ -509,7 +415,7 @@ declare module 'https' { * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. * * ```js - * const https = require('https'); + * const https = require('node:https'); * * https.get('https://encrypted.google.com/', (res) => { * console.log('statusCode:', res.statusCode); @@ -526,15 +432,8 @@ declare module 'https' { * @since v0.3.6 * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. */ - function get( - options: RequestOptions | string | URL, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; - function get( - url: string | URL, - options: RequestOptions, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; let globalAgent: Agent; } declare module 'node:https' { diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts index 9db5f47..f451df6 100644 --- a/node_modules/@types/node/index.d.ts +++ b/node_modules/@types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for non-npm package Node.js 18.11 +// Type definitions for non-npm package Node.js 20.3 // Project: https://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts index eba0b55..48920de 100644 --- a/node_modules/@types/node/inspector.d.ts +++ b/node_modules/@types/node/inspector.d.ts @@ -8,14 +8,21 @@ // tslint:disable:max-line-length /** - * The `inspector` module provides an API for interacting with the V8 inspector. + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. * * It can be accessed using: * * ```js - * const inspector = require('inspector'); + * import * as inspector from 'node:inspector/promises'; * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/inspector.js) + * + * or + * + * ```js + * import * as inspector from 'node:inspector'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/inspector.js) */ declare module 'inspector' { import EventEmitter = require('node:events'); diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts index d83aec9..e884f32 100644 --- a/node_modules/@types/node/module.d.ts +++ b/node_modules/@types/node/module.d.ts @@ -10,9 +10,9 @@ declare module 'module' { * does not add or remove exported names from the `ES Modules`. * * ```js - * const fs = require('fs'); - * const assert = require('assert'); - * const { syncBuiltinESMExports } = require('module'); + * const fs = require('node:fs'); + * const assert = require('node:assert'); + * const { syncBuiltinESMExports } = require('node:module'); * * fs.readFile = newAPI; * @@ -26,7 +26,7 @@ declare module 'module' { * * syncBuiltinESMExports(); * - * import('fs').then((esmFS) => { + * import('node:fs').then((esmFS) => { * // It syncs the existing readFile property with the new value * assert.strictEqual(esmFS.readFile, newAPI); * // readFileSync has been deleted from the required fs @@ -44,6 +44,7 @@ declare module 'module' { * `path` is the resolved path for the file for which a corresponding source map * should be fetched. * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. */ function findSourceMap(path: string, error?: Error): SourceMap; interface SourceMapPayload { @@ -85,6 +86,7 @@ declare module 'module' { static wrap(code: string): string; static createRequire(path: string | URL): NodeRequire; static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; static Module: typeof Module; constructor(id: string, parent?: Module); } diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts index b735538..485a971 100644 --- a/node_modules/@types/node/net.d.ts +++ b/node_modules/@types/node/net.d.ts @@ -1,16 +1,16 @@ /** * > Stability: 2 - Stable * - * The `net` module provides an asynchronous network API for creating stream-based + * The `node:net` module provides an asynchronous network API for creating stream-based * TCP or `IPC` servers ({@link createServer}) and clients * ({@link createConnection}). * * It can be accessed using: * * ```js - * const net = require('net'); + * const net = require('node:net'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/net.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/net.js) */ declare module 'net' { import * as stream from 'node:stream'; @@ -57,6 +57,14 @@ declare module 'net' { noDelay?: boolean | undefined; keepAlive?: boolean | undefined; keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; } interface IpcSocketConnectOpts extends ConnectOpts { path: string; @@ -133,13 +141,10 @@ declare module 'net' { pause(): this; /** * Close the TCP connection by sending an RST packet and destroy the stream. - * If this TCP socket is in connecting status, it will send an RST packet - * and destroy this TCP socket once it is connected. Otherwise, it will call - * `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. If this is not a TCP socket - * (for example, a pipe), calling this method will immediately throw - * an `ERR_INVALID_HANDLE_TYPE` Error. - * @since v18.3.0 - * @return The socket itself. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 */ resetAndDestroy(): this; /** @@ -261,6 +266,12 @@ declare module 'net' { * @since v6.1.0 */ readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; /** * See `writable.destroyed` for further details. */ @@ -279,12 +290,16 @@ declare module 'net' { readonly localPort?: number; /** * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. - * @since v18.8.0 + * @since v18.8.0, v16.18.0 */ readonly localFamily?: string; /** * This property represents the state of the connection as a string. - * @see {https://nodejs.org/api/net.html#socketreadystate} + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. * @since v0.5.0 */ readonly readyState: SocketReadyState; @@ -295,17 +310,20 @@ declare module 'net' { */ readonly remoteAddress?: string | undefined; /** - * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). * @since v0.11.14 */ readonly remoteFamily?: string | undefined; /** - * The numeric representation of the remote port. For example, `80` or `21`. + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). * @since v0.5.10 */ readonly remotePort?: number | undefined; /** - * The socket timeout in milliseconds as set by socket.setTimeout(). It is undefined if a timeout has not been set. + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. * @since v10.7.0 */ readonly timeout?: number | undefined; @@ -486,7 +504,7 @@ declare module 'net' { * ```js * server.on('error', (e) => { * if (e.code === 'EADDRINUSE') { - * console.log('Address in use, retrying...'); + * console.error('Address in use, retrying...'); * setTimeout(() => { * server.close(); * server.listen(PORT, HOST); @@ -708,7 +726,7 @@ declare module 'net' { * on port 8124: * * ```js - * const net = require('net'); + * const net = require('node:net'); * const server = net.createServer((c) => { * // 'connection' listener. * console.log('client connected'); @@ -728,8 +746,8 @@ declare module 'net' { * * Test this by using `telnet`: * - * ```console - * $ telnet localhost 8124 + * ```bash + * telnet localhost 8124 * ``` * * To listen on the socket `/tmp/echo.sock`: @@ -742,8 +760,8 @@ declare module 'net' { * * Use `nc` to connect to a Unix domain socket server: * - * ```console - * $ nc -U /tmp/echo.sock + * ```bash + * nc -U /tmp/echo.sock * ``` * @since v0.5.0 * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. @@ -846,6 +864,7 @@ declare module 'net' { class SocketAddress { constructor(options: SocketAddressInitOptions); /** + * Either \`'ipv4'\` or \`'ipv6'\`. * @since v15.14.0, v14.18.0 */ readonly address: string; diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts index 3c55599..3d20864 100644 --- a/node_modules/@types/node/os.d.ts +++ b/node_modules/@types/node/os.d.ts @@ -1,11 +1,11 @@ /** - * The `os` module provides operating system-related utility methods and + * The `node:os` module provides operating system-related utility methods and * properties. It can be accessed using: * * ```js - * const os = require('os'); + * const os = require('node:os'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/os.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/os.js) */ declare module 'os' { interface CpuInfo { @@ -75,6 +75,7 @@ declare module 'os' { function totalmem(): number; /** * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the`/proc` file system is unavailable. * * The properties included on each object include: * @@ -88,8 +89,8 @@ declare module 'os' { * nice: 0, * sys: 30340, * idle: 1070356870, - * irq: 0 - * } + * irq: 0, + * }, * }, * { * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', @@ -99,8 +100,8 @@ declare module 'os' { * nice: 0, * sys: 26980, * idle: 1071569080, - * irq: 0 - * } + * irq: 0, + * }, * }, * { * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', @@ -110,8 +111,8 @@ declare module 'os' { * nice: 0, * sys: 21750, * idle: 1070919370, - * irq: 0 - * } + * irq: 0, + * }, * }, * { * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', @@ -121,17 +122,28 @@ declare module 'os' { * nice: 0, * sys: 19430, * idle: 1070905480, - * irq: 20 - * } + * irq: 20, + * }, * }, * ] * ``` * * `nice` values are POSIX-only. On Windows, the `nice` values of all processors * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. * @since v0.3.3 */ function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; /** * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. @@ -415,12 +427,11 @@ declare module 'os' { */ function platform(): NodeJS.Platform; /** - * Returns the machine type as a string, such as arm, aarch64, mips, mips64, ppc64, ppc64le, s390, s390x, i386, i686, x86_64. + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,`mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. * - * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). - * On Windows, `RtlGetVersion()` is used, and if it is not available, `GetVersionExW()` will be used. - * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. - * @since v18.9.0 + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 */ function machine(): string; /** diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json index 1570db1..2d3e790 100644 --- a/node_modules/@types/node/package.json +++ b/node_modules/@types/node/package.json @@ -1,6 +1,6 @@ { "name": "@types/node", - "version": "18.11.18", + "version": "20.3.1", "description": "TypeScript definitions for Node.js", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", "license": "MIT", @@ -232,6 +232,6 @@ }, "scripts": {}, "dependencies": {}, - "typesPublisherContentHash": "540ec74ad976942ed4b12e09fd57842adfd77a63a4ea099f15f0602ad707835c", - "typeScriptVersion": "4.2" + "typesPublisherContentHash": "c47aade88cd1332fb7e20ae32636fbd2941ea3e16db2c41f81bc1509e6e8c41f", + "typeScriptVersion": "4.3" } \ No newline at end of file diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts index 1d33f79..723d5da 100644 --- a/node_modules/@types/node/path.d.ts +++ b/node_modules/@types/node/path.d.ts @@ -7,13 +7,13 @@ declare module 'path/win32' { export = path; } /** - * The `path` module provides utilities for working with file and directory paths. - * It can be accessed using: + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: * * ```js - * const path = require('path'); + * const path = require('node:path'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/path.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/path.js) */ declare module 'path' { namespace path { diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts index 5c0b228..c090e1d 100644 --- a/node_modules/@types/node/perf_hooks.d.ts +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -7,9 +7,10 @@ * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) * * [Performance Timeline](https://w3c.github.io/performance-timeline/) * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) * * ```js - * const { PerformanceObserver, performance } = require('perf_hooks'); + * const { PerformanceObserver, performance } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((items) => { * console.log(items.getEntries()[0].duration); @@ -26,7 +27,7 @@ * performance.measure('A to B', 'A', 'B'); * }); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/perf_hooks.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/perf_hooks.js) */ declare module 'perf_hooks' { import { AsyncResource } from 'node:async_hooks'; @@ -46,6 +47,7 @@ declare module 'perf_hooks' { readonly flags?: number | undefined; } /** + * The constructor of this class is not exposed to users directly. * @since v8.5.0 */ class PerformanceEntry { @@ -87,10 +89,20 @@ declare module 'perf_hooks' { readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. toJSON(): any; } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ class PerformanceMark extends PerformanceEntry { readonly duration: 0; readonly entryType: 'mark'; } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ class PerformanceMeasure extends PerformanceEntry { readonly entryType: 'measure'; } @@ -288,8 +300,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntries()); @@ -330,8 +342,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByName('meow')); @@ -379,8 +391,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByType('mark')); @@ -414,6 +426,9 @@ declare module 'perf_hooks' { getEntriesByType(type: EntryType): PerformanceEntry[]; } type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ class PerformanceObserver extends AsyncResource { constructor(callback: PerformanceObserverCallback); /** @@ -427,8 +442,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((list, observer) => { * // Called once asynchronously. `list` contains three items. @@ -547,11 +562,10 @@ declare module 'perf_hooks' { */ recordDelta(): void; /** - * Adds the values from other to this histogram. + * Adds the values from `other` to this histogram. * @since v17.4.0, v16.14.0 - * @param other Recordable Histogram to combine with */ - add(other: RecordableHistogram): void; + add(other: RecordableHistogram): void; } /** * _This property is an extension by Node.js. It is not available in Web browsers._ @@ -566,7 +580,7 @@ declare module 'perf_hooks' { * detect. * * ```js - * const { monitorEventLoopDelay } = require('perf_hooks'); + * const { monitorEventLoopDelay } = require('node:perf_hooks'); * const h = monitorEventLoopDelay({ resolution: 20 }); * h.enable(); * // Do something. @@ -604,7 +618,6 @@ declare module 'perf_hooks' { * @since v15.9.0, v14.18.0 */ function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; - import { performance as _performance } from 'perf_hooks'; global { /** diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts index 12148f9..f122546 100644 --- a/node_modules/@types/node/process.d.ts +++ b/node_modules/@types/node/process.d.ts @@ -250,7 +250,7 @@ declare module 'process' { * For example, to copy `process.stdin` to `process.stdout`: * * ```js - * import { stdin, stdout } from 'process'; + * import { stdin, stdout } from 'node:process'; * * stdin.pipe(stdout); * ``` @@ -297,7 +297,7 @@ declare module 'process' { * For example, assuming the following script for `process-args.js`: * * ```js - * import { argv } from 'process'; + * import { argv } from 'node:process'; * * // print process.argv * argv.forEach((val, index) => { @@ -307,8 +307,8 @@ declare module 'process' { * * Launching the Node.js process as: * - * ```console - * $ node process-args.js one two=three four + * ```bash + * node process-args.js one two=three four * ``` * * Would generate the output: @@ -344,8 +344,8 @@ declare module 'process' { * the script name. These options are useful in order to spawn child processes with * the same execution environment as the parent. * - * ```console - * $ node --harmony script.js --version + * ```bash + * node --harmony script.js --version * ``` * * Results in `process.execArgv`: @@ -389,7 +389,7 @@ declare module 'process' { * the specified `directory` does not exist). * * ```js - * import { chdir, cwd } from 'process'; + * import { chdir, cwd } from 'node:process'; * * console.log(`Starting directory: ${cwd()}`); * try { @@ -409,7 +409,7 @@ declare module 'process' { * process. * * ```js - * import { cwd } from 'process'; + * import { cwd } from 'node:process'; * * console.log(`Current directory: ${cwd()}`); * ``` @@ -420,7 +420,7 @@ declare module 'process' { * The port used by the Node.js debugger when enabled. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * process.debugPort = 5858; * ``` @@ -432,12 +432,12 @@ declare module 'process' { * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. * * ```js - * import { emitWarning } from 'process'; + * import { emitWarning } from 'node:process'; * * // Emit a warning with a code and additional detail. * emitWarning('Something happened!', { * code: 'MY_WARNING', - * detail: 'This is some additional information' + * detail: 'This is some additional information', * }); * // Emits: * // (node:56338) [MY_WARNING] Warning: Something happened! @@ -447,7 +447,7 @@ declare module 'process' { * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * process.on('warning', (warning) => { * console.warn(warning.name); // 'Warning' @@ -492,14 +492,14 @@ declare module 'process' { * to other `Worker` threads. * In other words, the following example would not work: * - * ```console - * $ node -e 'process.env.foo = "bar"' && echo $foo + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo * ``` * * While the following will: * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.foo = 'bar'; * console.log(env.foo); @@ -510,7 +510,7 @@ declare module 'process' { * throw an error when the value is not a string, number, or boolean. * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.test = null; * console.log(env.test); @@ -523,7 +523,7 @@ declare module 'process' { * Use `delete` to delete a property from `process.env`. * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.TEST = 1; * delete env.TEST; @@ -534,7 +534,7 @@ declare module 'process' { * On Windows operating systems, environment variables are case-insensitive. * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.TEST = 1; * console.log(env.test); @@ -543,7 +543,7 @@ declare module 'process' { * * Unless explicitly specified when creating a `Worker` instance, * each `Worker` thread has its own copy of `process.env`, based on its - * parent thread’s `process.env`, or whatever was specified as the `env` option + * parent thread's `process.env`, or whatever was specified as the `env` option * to the `Worker` constructor. Changes to `process.env` will not be visible * across `Worker` threads, and only the main thread can make changes that * are visible to the operating system or to native add-ons. @@ -560,7 +560,7 @@ declare module 'process' { * To exit with a 'failure' code: * * ```js - * import { exit } from 'process'; + * import { exit } from 'node:process'; * * exit(1); * ``` @@ -579,7 +579,7 @@ declare module 'process' { * truncated and lost: * * ```js - * import { exit } from 'process'; + * import { exit } from 'node:process'; * * // This is an example of what *not* to do: * if (someConditionNotMet()) { @@ -596,7 +596,7 @@ declare module 'process' { * scheduling any additional work for the event loop: * * ```js - * import process from 'process'; + * import process from 'node:process'; * * // How to properly set the exit code while letting * // the process exit gracefully. @@ -613,7 +613,7 @@ declare module 'process' { * In `Worker` threads, this function stops the current thread rather * than the current process. * @since v0.1.13 - * @param [code=0] The exit code. + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. */ exit(code?: number): never; /** @@ -873,7 +873,7 @@ declare module 'process' { * The `process.version` property contains the Node.js version string. * * ```js - * import { version } from 'process'; + * import { version } from 'node:process'; * * console.log(`Version: ${version}`); * // Version: v14.8.0 @@ -890,7 +890,7 @@ declare module 'process' { * to load modules that were compiled against a different module ABI version. * * ```js - * import { versions } from 'process'; + * import { versions } from 'node:process'; * * console.log(versions); * ``` @@ -898,30 +898,39 @@ declare module 'process' { * Will generate an object similar to: * * ```console - * { node: '11.13.0', - * v8: '7.0.276.38-node.18', - * uv: '1.27.0', - * zlib: '1.2.11', - * brotli: '1.0.7', - * ares: '1.15.0', - * modules: '67', - * nghttp2: '1.34.0', - * napi: '4', - * llhttp: '1.1.1', - * openssl: '1.1.1b', - * cldr: '34.0', - * icu: '63.1', - * tz: '2018e', - * unicode: '11.0' } + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } * ``` * @since v0.2.0 */ readonly versions: ProcessVersions; /** - * The `process.config` property returns an `Object` containing the JavaScript - * representation of the configure options used to compile the current Node.js - * executable. This is the same as the `config.gypi` file that was produced when - * running the `./configure` script. + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. * * An example of the possible output looks like: * @@ -943,7 +952,6 @@ declare module 'process' { * node_shared_http_parser: 'false', * node_shared_libuv: 'false', * node_shared_zlib: 'false', - * node_use_dtrace: 'false', * node_use_openssl: 'true', * node_shared_openssl: 'false', * strict_aliasing: 'true', @@ -952,13 +960,6 @@ declare module 'process' { * } * } * ``` - * - * The `process.config` property is **not** read-only and there are existing - * modules in the ecosystem that are known to extend, modify, or entirely replace - * the value of `process.config`. - * - * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made - * read-only in a future release. * @since v0.7.7 */ readonly config: ProcessConfig; @@ -977,7 +978,7 @@ declare module 'process' { * other than kill the target process. * * ```js - * import process, { kill } from 'process'; + * import process, { kill } from 'node:process'; * * process.on('SIGHUP', () => { * console.log('Got SIGHUP signal.'); @@ -1002,7 +1003,7 @@ declare module 'process' { * The `process.pid` property returns the PID of the process. * * ```js - * import { pid } from 'process'; + * import { pid } from 'node:process'; * * console.log(`This process is pid ${pid}`); * ``` @@ -1014,7 +1015,7 @@ declare module 'process' { * current process. * * ```js - * import { ppid } from 'process'; + * import { ppid } from 'node:process'; * * console.log(`The parent process is pid ${ppid}`); * ``` @@ -1044,7 +1045,7 @@ declare module 'process' { * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. * * ```js - * import { arch } from 'process'; + * import { arch } from 'node:process'; * * console.log(`This processor architecture is ${arch}`); * ``` @@ -1066,7 +1067,7 @@ declare module 'process' { * * `'win32'` * * ```js - * import { platform } from 'process'; + * import { platform } from 'node:process'; * * console.log(`This platform is ${platform}`); * ``` @@ -1089,6 +1090,17 @@ declare module 'process' { */ mainModule?: Module | undefined; memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `undefined` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + * @experimental + */ + constrainedMemory(): number | undefined; /** * The `process.cpuUsage()` method returns the user and system CPU time usage of * the current process, in an object with properties `user` and `system`, whose @@ -1100,7 +1112,7 @@ declare module 'process' { * argument to the function, to get a diff reading. * * ```js - * import { cpuUsage } from 'process'; + * import { cpuUsage } from 'node:process'; * * const startUsage = cpuUsage(); * // { user: 38579, system: 6986 } @@ -1124,7 +1136,7 @@ declare module 'process' { * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. * * ```js - * import { nextTick } from 'process'; + * import { nextTick } from 'node:process'; * * console.log('start'); * nextTick(() => { @@ -1142,7 +1154,7 @@ declare module 'process' { * I/O has occurred: * * ```js - * import { nextTick } from 'process'; + * import { nextTick } from 'node:process'; * * function MyThing(options) { * this.setupOptions(options); @@ -1190,7 +1202,7 @@ declare module 'process' { * The following approach is much better: * * ```js - * import { nextTick } from 'process'; + * import { nextTick } from 'node:process'; * * function definitelyAsync(arg, cb) { * if (arg) { @@ -1215,10 +1227,10 @@ declare module 'process' { * ```js * { * name: 'node', - * lts: 'Erbium', - * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', - * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', - * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' * } * ``` * @@ -1322,7 +1334,7 @@ declare module 'process' { * dashes: * * ```js - * import { allowedNodeEnvironmentFlags } from 'process'; + * import { allowedNodeEnvironmentFlags } from 'node:process'; * * allowedNodeEnvironmentFlags.forEach((flag) => { * // -r @@ -1348,7 +1360,7 @@ declare module 'process' { report?: ProcessReport | undefined; /** * ```js - * import { resourceUsage } from 'process'; + * import { resourceUsage } from 'node:process'; * * console.log(resourceUsage()); * /* diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts index 87ebbb9..8927207 100644 --- a/node_modules/@types/node/punycode.d.ts +++ b/node_modules/@types/node/punycode.d.ts @@ -24,7 +24,7 @@ * made available to developers as a convenience. Fixes or other modifications to * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. * @deprecated Since v7.0.0 - Deprecated - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/punycode.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/punycode.js) */ declare module 'punycode' { /** diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts index e118547..e9d087c 100644 --- a/node_modules/@types/node/querystring.d.ts +++ b/node_modules/@types/node/querystring.d.ts @@ -1,15 +1,15 @@ /** - * The `querystring` module provides utilities for parsing and formatting URL + * The `node:querystring` module provides utilities for parsing and formatting URL * query strings. It can be accessed using: * * ```js - * const querystring = require('querystring'); + * const querystring = require('node:querystring'); * ``` * * `querystring` is more performant than `URLSearchParams` but is not a - * standardized API. Use `URLSearchParams` when performance is not critical - * or when compatibility with browser code is desirable. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/querystring.js) + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/querystring.js) */ declare module 'querystring' { interface StringifyOptions { diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts index 6ab64ac..e6f7b0a 100644 --- a/node_modules/@types/node/readline.d.ts +++ b/node_modules/@types/node/readline.d.ts @@ -1,5 +1,5 @@ /** - * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. + * The `node:readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. * * To use the promise-based APIs: * @@ -13,7 +13,7 @@ * import * as readline from 'node:readline'; * ``` * - * The following simple example illustrates the basic use of the `readline` module. + * The following simple example illustrates the basic use of the `node:readline`module. * * ```js * import * as readline from 'node:readline/promises'; @@ -30,12 +30,11 @@ * * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be * received on the `input` stream. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/readline.js) */ declare module 'readline' { import { Abortable, EventEmitter } from 'node:events'; import * as promises from 'node:readline/promises'; - export { promises }; export interface Key { sequence?: string | undefined; @@ -74,7 +73,7 @@ declare module 'readline' { * const showResults = debounce(() => { * console.log( * '\n', - * values.filter((val) => val.startsWith(rl.line)).join(' ') + * values.filter((val) => val.startsWith(rl.line)).join(' '), * ); * }, 300); * process.stdin.on('keypress', (c, k) => { @@ -100,7 +99,7 @@ declare module 'readline' { * > Instances of the `readline.Interface` class are constructed using the * > `readline.createInterface()` method. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor */ protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); /** @@ -109,12 +108,12 @@ declare module 'readline' { * > Instances of the `readline.Interface` class are constructed using the * > `readline.createInterface()` method. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor */ protected constructor(options: ReadLineOptions); /** * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. - * @since v15.3.0 + * @since v15.3.0, v14.17.0 * @return the current prompt string */ getPrompt(): string; @@ -124,13 +123,13 @@ declare module 'readline' { */ setPrompt(prompt: string): void; /** - * The `rl.prompt()` method writes the `readline.Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new * location at which to provide input. * * When called, `rl.prompt()` will resume the `input` stream if it has been * paused. * - * If the `readline.Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * If the `Interface` was created with `output` set to `null` or`undefined` the prompt is not written. * @since v0.1.98 * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. */ @@ -142,12 +141,14 @@ declare module 'readline' { * When called, `rl.question()` will resume the `input` stream if it has been * paused. * - * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. * * The `callback` function passed to `rl.question()` does not follow the typical * pattern of accepting an `Error` object or `null` as the first argument. * The `callback` is called with the provided answer as the only argument. * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * * Example usage: * * ```js @@ -172,25 +173,6 @@ declare module 'readline' { * * setTimeout(() => ac.abort(), 10000); * ``` - * - * If this method is invoked as it's util.promisify()ed version, it returns a - * Promise that fulfills with the answer. If the question is canceled using - * an `AbortController` it will reject with an `AbortError`. - * - * ```js - * const util = require('util'); - * const question = util.promisify(rl.question).bind(rl); - * - * async function questionExample() { - * try { - * const answer = await question('What is you favorite food? '); - * console.log(`Oh, so your favorite food is ${answer}`); - * } catch (err) { - * console.error('Question rejected', err); - * } - * } - * questionExample(); - * ``` * @since v0.3.3 * @param query A statement or query to write to `output`, prepended to the prompt. * @param callback A callback function that is invoked with the user's input in response to the `query`. @@ -201,7 +183,7 @@ declare module 'readline' { * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed * later if necessary. * - * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `readline.Interface` instance. + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `Interface` instance. * @since v0.3.4 */ pause(): this; @@ -211,12 +193,12 @@ declare module 'readline' { */ resume(): this; /** - * The `rl.close()` method closes the `readline.Interface` instance and + * The `rl.close()` method closes the `Interface` instance and * relinquishes control over the `input` and `output` streams. When called, * the `'close'` event will be emitted. * * Calling `rl.close()` does not immediately stop other events (including `'line'`) - * from being emitted by the `readline.Interface` instance. + * from being emitted by the `Interface` instance. * @since v0.1.98 */ close(): void; @@ -231,7 +213,7 @@ declare module 'readline' { * When called, `rl.write()` will resume the `input` stream if it has been * paused. * - * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * If the `Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. * * ```js * rl.write('Delete this!'); @@ -351,10 +333,10 @@ declare module 'readline' { * The `readline.createInterface()` method creates a new `readline.Interface`instance. * * ```js - * const readline = require('readline'); + * const readline = require('node:readline'); * const rl = readline.createInterface({ * input: process.stdin, - * output: process.stdout + * output: process.stdout, * }); * ``` * @@ -373,14 +355,8 @@ declare module 'readline' { * (`process.stdout` does this automatically when it is a TTY). * * When creating a `readline.Interface` using `stdin` as input, the program - * will not terminate until it receives `EOF` (Ctrl+D on - * Linux/macOS, Ctrl+Z followed by Return on - * Windows). - * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: - * - * ```js - * process.stdin.unref(); - * ``` + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. * @since v0.1.98 */ export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; @@ -408,11 +384,11 @@ declare module 'readline' { * implement a small command-line interface: * * ```js - * const readline = require('readline'); + * const readline = require('node:readline'); * const rl = readline.createInterface({ * input: process.stdin, * output: process.stdout, - * prompt: 'OHAI> ' + * prompt: 'OHAI> ', * }); * * rl.prompt(); @@ -440,15 +416,15 @@ declare module 'readline' { * well as a `for await...of` loop: * * ```js - * const fs = require('fs'); - * const readline = require('readline'); + * const fs = require('node:fs'); + * const readline = require('node:readline'); * * async function processLineByLine() { * const fileStream = fs.createReadStream('input.txt'); * * const rl = readline.createInterface({ * input: fileStream, - * crlfDelay: Infinity + * crlfDelay: Infinity, * }); * // Note: we use the crlfDelay option to recognize all instances of CR LF * // ('\r\n') in input.txt as a single line break. @@ -465,12 +441,12 @@ declare module 'readline' { * Alternatively, one could use the `'line'` event: * * ```js - * const fs = require('fs'); - * const readline = require('readline'); + * const fs = require('node:fs'); + * const readline = require('node:readline'); * * const rl = readline.createInterface({ * input: fs.createReadStream('sample.txt'), - * crlfDelay: Infinity + * crlfDelay: Infinity, * }); * * rl.on('line', (line) => { @@ -481,15 +457,15 @@ declare module 'readline' { * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: * * ```js - * const { once } = require('events'); - * const { createReadStream } = require('fs'); - * const { createInterface } = require('readline'); + * const { once } = require('node:events'); + * const { createReadStream } = require('node:fs'); + * const { createInterface } = require('node:readline'); * * (async function processLineByLine() { * try { * const rl = createInterface({ * input: createReadStream('big-file.txt'), - * crlfDelay: Infinity + * crlfDelay: Infinity, * }); * * rl.on('line', (line) => { @@ -539,109 +515,6 @@ declare module 'readline' { /** * The `readline.moveCursor()` method moves the cursor _relative_ to its current * position in a given `TTY` `stream`. - * - * ## Example: Tiny CLI - * - * The following example illustrates the use of `readline.Interface` class to - * implement a small command-line interface: - * - * ```js - * const readline = require('readline'); - * const rl = readline.createInterface({ - * input: process.stdin, - * output: process.stdout, - * prompt: 'OHAI> ' - * }); - * - * rl.prompt(); - * - * rl.on('line', (line) => { - * switch (line.trim()) { - * case 'hello': - * console.log('world!'); - * break; - * default: - * console.log(`Say what? I might have heard '${line.trim()}'`); - * break; - * } - * rl.prompt(); - * }).on('close', () => { - * console.log('Have a great day!'); - * process.exit(0); - * }); - * ``` - * - * ## Example: Read file stream line-by-Line - * - * A common use case for `readline` is to consume an input file one line at a - * time. The easiest way to do so is leveraging the `fs.ReadStream` API as - * well as a `for await...of` loop: - * - * ```js - * const fs = require('fs'); - * const readline = require('readline'); - * - * async function processLineByLine() { - * const fileStream = fs.createReadStream('input.txt'); - * - * const rl = readline.createInterface({ - * input: fileStream, - * crlfDelay: Infinity - * }); - * // Note: we use the crlfDelay option to recognize all instances of CR LF - * // ('\r\n') in input.txt as a single line break. - * - * for await (const line of rl) { - * // Each line in input.txt will be successively available here as `line`. - * console.log(`Line from file: ${line}`); - * } - * } - * - * processLineByLine(); - * ``` - * - * Alternatively, one could use the `'line'` event: - * - * ```js - * const fs = require('fs'); - * const readline = require('readline'); - * - * const rl = readline.createInterface({ - * input: fs.createReadStream('sample.txt'), - * crlfDelay: Infinity - * }); - * - * rl.on('line', (line) => { - * console.log(`Line from file: ${line}`); - * }); - * ``` - * - * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: - * - * ```js - * const { once } = require('events'); - * const { createReadStream } = require('fs'); - * const { createInterface } = require('readline'); - * - * (async function processLineByLine() { - * try { - * const rl = createInterface({ - * input: createReadStream('big-file.txt'), - * crlfDelay: Infinity - * }); - * - * rl.on('line', (line) => { - * // Process the line. - * }); - * - * await once(rl, 'close'); - * - * console.log('File processed.'); - * } catch (err) { - * console.error(err); - * } - * })(); - * ``` * @since v0.7.7 * @param callback Invoked once the operation completes. * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. diff --git a/node_modules/@types/node/readline/promises.d.ts b/node_modules/@types/node/readline/promises.d.ts index 8f9f06f..079fbdf 100644 --- a/node_modules/@types/node/readline/promises.d.ts +++ b/node_modules/@types/node/readline/promises.d.ts @@ -1,23 +1,28 @@ /** - * The `readline/promise` module provides an API for reading lines of input from a Readable stream one line at a time. - * - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline/promises.js) * @since v17.0.0 + * @experimental */ declare module 'readline/promises' { import { Interface as _Interface, ReadLineOptions, Completer, AsyncCompleter, Direction } from 'node:readline'; import { Abortable } from 'node:events'; - + /** + * Instances of the `readlinePromises.Interface` class are constructed using the`readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ class Interface extends _Interface { /** - * The rl.question() method displays the query by writing it to the output, waits for user input to be provided on input, - * then invokes the callback function passing the provided input as the first argument. + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. * - * When called, rl.question() will resume the input stream if it has been paused. + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. * - * If the readlinePromises.Interface was created with output set to null or undefined the query is not written. + * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. * - * If the question is called after rl.close(), it returns a rejected promise. + * If the question is called after `rl.close()`, it returns a rejected promise. * * Example usage: * @@ -26,7 +31,7 @@ declare module 'readline/promises' { * console.log(`Oh, so your favorite food is ${answer}`); * ``` * - * Using an AbortSignal to cancel a question. + * Using an `AbortSignal` to cancel a question. * * ```js * const signal = AbortSignal.timeout(10_000); @@ -38,61 +43,87 @@ declare module 'readline/promises' { * const answer = await rl.question('What is your favorite food? ', { signal }); * console.log(`Oh, so your favorite food is ${answer}`); * ``` - * * @since v17.0.0 - * @param query A statement or query to write to output, prepended to the prompt. + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. */ question(query: string): Promise; question(query: string, options: Abortable): Promise; } - + /** + * @since v17.0.0 + */ class Readline { /** * @param stream A TTY stream. */ - constructor(stream: NodeJS.WritableStream, options?: { autoCommit?: boolean }); + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + } + ); /** - * The `rl.clearLine()` method adds to the internal list of pending action an action that clears current line of the associated `stream` in a specified direction identified by `dir`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this */ clearLine(dir: Direction): this; /** - * The `rl.clearScreenDown()` method adds to the internal list of pending action an action that clears the associated `stream` from the current position of the cursor down. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this */ clearScreenDown(): this; /** - * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * The `rl.commit()` method sends all the pending actions to the associated`stream` and clears the internal list of pending actions. + * @since v17.0.0 */ commit(): Promise; /** - * The `rl.cursorTo()` method adds to the internal list of pending action an action that moves cursor to the specified position in the associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this */ cursorTo(x: number, y?: number): this; /** - * The `rl.moveCursor()` method adds to the internal list of pending action an action that moves the cursor relative to its current position in the associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless autoCommit: true was passed to the constructor. + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this */ moveCursor(dx: number, dy: number): this; /** - * The `rl.rollback()` method clears the internal list of pending actions without sending it to the associated `stream`. + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this */ rollback(): this; } - /** - * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface`instance. * * ```js * const readlinePromises = require('node:readline/promises'); * const rl = readlinePromises.createInterface({ * input: process.stdin, - * output: process.stdout + * output: process.stdout, * }); * ``` * - * Once the `readlinePromises.Interface` instance is created, the most common case is to listen for the `'line'` event: + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: * * ```js * rl.on('line', (line) => { @@ -100,42 +131,13 @@ declare module 'readline/promises' { * }); * ``` * - * If `terminal` is `true` for this instance then the `output` stream will get the best compatibility if it defines an `output.columns` property, - * and emits a `'resize'` event on the `output`, if or when the columns ever change (`process.stdout` does this automatically when it is a TTY). - * - * ## Use of the `completer` function - * - * The `completer` function takes the current line entered by the user as an argument, and returns an `Array` with 2 entries: - * - * - An Array with matching entries for the completion. - * - The substring that was used for the matching. - * - * For instance: `[[substr1, substr2, ...], originalsubstring]`. - * - * ```js - * function completer(line) { - * const completions = '.help .error .exit .quit .q'.split(' '); - * const hits = completions.filter((c) => c.startsWith(line)); - * // Show all completions if none found - * return [hits.length ? hits : completions, line]; - * } - * ``` - * - * The `completer` function can also returns a `Promise`, or be asynchronous: - * - * ```js - * async function completer(linePartial) { - * await someAsyncWork(); - * return [['123'], linePartial]; - * } - * ``` + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 */ - function createInterface( - input: NodeJS.ReadableStream, - output?: NodeJS.WritableStream, - completer?: Completer | AsyncCompleter, - terminal?: boolean, - ): Interface; + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; function createInterface(options: ReadLineOptions): Interface; } declare module 'node:readline/promises' { diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts index be42ccc..c8147ed 100644 --- a/node_modules/@types/node/repl.d.ts +++ b/node_modules/@types/node/repl.d.ts @@ -1,12 +1,12 @@ /** - * The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that - * is available both as a standalone program or includible in other applications. - * It can be accessed using: + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/repl.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/repl.js) */ declare module 'repl' { import { Interface, Completer, AsyncCompleter } from 'node:readline'; @@ -41,8 +41,8 @@ declare module 'repl' { * error with `repl.Recoverable` to indicate the input was incomplete and prompt for * additional lines. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_custom_evaluation_functions */ eval?: REPLEval | undefined; /** @@ -74,13 +74,13 @@ declare module 'repl' { * The function to invoke to format the output of each command before writing to `output`. * Default: a wrapper for `util.inspect`. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_customizing_repl_output */ writer?: REPLWriter | undefined; /** * An optional function used for custom Tab auto completion. * - * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#readline_use_of_the_completer_function */ completer?: Completer | AsyncCompleter | undefined; /** @@ -124,7 +124,7 @@ declare module 'repl' { * or directly using the JavaScript `new` keyword. * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * * const options = { useColors: true }; * @@ -162,33 +162,33 @@ declare module 'repl' { /** * A value indicating whether the REPL is currently in "editor mode". * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_commands_and_special_keys */ readonly editorMode: boolean; /** * A value indicating whether the `_` variable has been assigned. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable */ readonly underscoreAssigned: boolean; /** * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable */ readonly last: any; /** * A value indicating whether the `_error` variable has been assigned. * * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable */ readonly underscoreErrAssigned: boolean; /** * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). * * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable */ readonly lastError: any; /** @@ -240,7 +240,7 @@ declare module 'repl' { * * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_class_replserver */ private constructor(); /** @@ -251,7 +251,7 @@ declare module 'repl' { * The following example shows two new commands added to the REPL instance: * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * * const replServer = repl.start({ prompt: '> ' }); * replServer.defineCommand('sayhello', { @@ -260,7 +260,7 @@ declare module 'repl' { * this.clearBufferedCommand(); * console.log(`Hello, ${name}!`); * this.displayPrompt(); - * } + * }, * }); * replServer.defineCommand('saybye', function saybye() { * console.log('Goodbye!'); @@ -401,7 +401,7 @@ declare module 'repl' { * If `options` is a string, then it specifies the input prompt: * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * * // a Unix style prompt * repl.start('$ '); @@ -412,7 +412,7 @@ declare module 'repl' { /** * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_recoverable_errors */ class Recoverable extends SyntaxError { err: Error; diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts index 711fd9c..7f7b793 100644 --- a/node_modules/@types/node/stream.d.ts +++ b/node_modules/@types/node/stream.d.ts @@ -1,24 +1,24 @@ /** * A stream is an abstract interface for working with streaming data in Node.js. - * The `stream` module provides an API for implementing the stream interface. + * The `node:stream` module provides an API for implementing the stream interface. * * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. * * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. * - * To access the `stream` module: + * To access the `node:stream` module: * * ```js - * const stream = require('stream'); + * const stream = require('node:stream'); * ``` * - * The `stream` module is useful for creating new types of stream instances. It is - * usually not necessary to use the `stream` module to consume streams. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/stream.js) + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/stream.js) */ declare module 'stream' { import { EventEmitter, Abortable } from 'node:events'; - import { Blob as NodeBlob } from "node:buffer"; + import { Blob as NodeBlob } from 'node:buffer'; import * as streamPromises from 'node:stream/promises'; import * as streamConsumers from 'node:stream/consumers'; import * as streamWeb from 'node:stream/web'; @@ -30,6 +30,739 @@ declare module 'stream' { } ): T; } + import Stream = internal.Stream; + import Readable = internal.Readable; + import ReadableOptions = internal.ReadableOptions; + class ReadableBase extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('node:fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('node:string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array`, or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream`module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('node:stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: any) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: any): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'pause'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'resume'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: any) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: any) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: any) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: any) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'data', listener: (chunk: any) => void): this; + removeListener(event: 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'pause', listener: () => void): this; + removeListener(event: 'readable', listener: () => void): this; + removeListener(event: 'resume', listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + import WritableOptions = internal.WritableOptions; + class WritableBase extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('node:fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: Readable) => void): this; + addListener(event: 'unpipe', listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: Readable): boolean; + emit(event: 'unpipe', src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: Readable) => void): this; + on(event: 'unpipe', listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: Readable) => void): this; + once(event: 'unpipe', listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'drain', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'finish', listener: () => void): this; + removeListener(event: 'pipe', listener: (src: Readable) => void): this; + removeListener(event: 'unpipe', listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } namespace internal { class Stream extends internal { constructor(opts?: ReadableOptions); @@ -49,458 +782,19 @@ declare module 'stream' { /** * @since v0.9.4 */ - class Readable extends Stream implements NodeJS.ReadableStream { - /** - * A utility method for creating Readable Streams out of iterators. - */ - static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + class Readable extends ReadableBase { /** * A utility method for creating a `Readable` from a web `ReadableStream`. * @since v17.0.0 * @experimental */ static fromWeb(readableStream: streamWeb.ReadableStream, options?: Pick): Readable; - /** - * Returns whether the stream has been read from or cancelled. - * @since v16.8.0 - */ - static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; /** * A utility method for creating a web `ReadableStream` from a `Readable`. * @since v17.0.0 * @experimental */ static toWeb(streamReadable: Readable): streamWeb.ReadableStream; - /** - * Returns whether the stream was destroyed or errored before emitting `'end'`. - * @since v16.8.0 - * @experimental - */ - readonly readableAborted: boolean; - /** - * Is `true` if it is safe to call `readable.read()`, which means - * the stream has not been destroyed or emitted `'error'` or `'end'`. - * @since v11.4.0 - */ - readable: boolean; - /** - * Returns whether `'data'` has been emitted. - * @since v16.7.0, v14.18.0 - * @experimental - */ - readonly readableDidRead: boolean; - /** - * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. - * @since v12.7.0 - */ - readonly readableEncoding: BufferEncoding | null; - /** - * Becomes `true` when `'end'` event is emitted. - * @since v12.9.0 - */ - readonly readableEnded: boolean; - /** - * This property reflects the current state of a `Readable` stream as described - * in the `Three states` section. - * @since v9.4.0 - */ - readonly readableFlowing: boolean | null; - /** - * Returns the value of `highWaterMark` passed when creating this `Readable`. - * @since v9.3.0 - */ - readonly readableHighWaterMark: number; - /** - * This property contains the number of bytes (or objects) in the queue - * ready to be read. The value provides introspection data regarding - * the status of the `highWaterMark`. - * @since v9.4.0 - */ - readonly readableLength: number; - /** - * Getter for the property `objectMode` of a given `Readable` stream. - * @since v12.3.0 - */ - readonly readableObjectMode: boolean; - /** - * Is `true` after `readable.destroy()` has been called. - * @since v8.0.0 - */ - destroyed: boolean; - /** - * Is true after 'close' has been emitted. - * @since v18.0.0 - */ - readonly closed: boolean; - /** - * Returns error if the stream has been destroyed with an error. - * @since v18.0.0 - */ - readonly errored: Error | null; - constructor(opts?: ReadableOptions); - _construct?(callback: (error?: Error | null) => void): void; - _read(size: number): void; - /** - * The `readable.read()` method reads data out of the internal buffer and - * returns it. If no data is available to be read, `null` is returned. By default, - * the data is returned as a `Buffer` object unless an encoding has been - * specified using the `readable.setEncoding()` method or the stream is operating - * in object mode. - * - * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which - * case all of the data remaining in the internal - * buffer will be returned. - * - * If the `size` argument is not specified, all of the data contained in the - * internal buffer will be returned. - * - * The `size` argument must be less than or equal to 1 GiB. - * - * The `readable.read()` method should only be called on `Readable` streams - * operating in paused mode. In flowing mode, `readable.read()` is called - * automatically until the internal buffer is fully drained. - * - * ```js - * const readable = getReadableStreamSomehow(); - * - * // 'readable' may be triggered multiple times as data is buffered in - * readable.on('readable', () => { - * let chunk; - * console.log('Stream is readable (new data received in buffer)'); - * // Use a loop to make sure we read all currently available data - * while (null !== (chunk = readable.read())) { - * console.log(`Read ${chunk.length} bytes of data...`); - * } - * }); - * - * // 'end' will be triggered once when there is no more data available - * readable.on('end', () => { - * console.log('Reached end of stream.'); - * }); - * ``` - * - * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks - * are not concatenated. A `while` loop is necessary to consume all data - * currently in the buffer. When reading a large file `.read()` may return `null`, - * having consumed all buffered content so far, but there is still more data to - * come not yet buffered. In this case a new `'readable'` event will be emitted - * when there is more data in the buffer. Finally the `'end'` event will be - * emitted when there is no more data to come. - * - * Therefore to read a file's whole contents from a `readable`, it is necessary - * to collect chunks across multiple `'readable'` events: - * - * ```js - * const chunks = []; - * - * readable.on('readable', () => { - * let chunk; - * while (null !== (chunk = readable.read())) { - * chunks.push(chunk); - * } - * }); - * - * readable.on('end', () => { - * const content = chunks.join(''); - * }); - * ``` - * - * A `Readable` stream in object mode will always return a single item from - * a call to `readable.read(size)`, regardless of the value of the`size` argument. - * - * If the `readable.read()` method returns a chunk of data, a `'data'` event will - * also be emitted. - * - * Calling {@link read} after the `'end'` event has - * been emitted will return `null`. No runtime error will be raised. - * @since v0.9.4 - * @param size Optional argument to specify how much data to read. - */ - read(size?: number): any; - /** - * The `readable.setEncoding()` method sets the character encoding for - * data read from the `Readable` stream. - * - * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data - * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the - * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal - * string format. - * - * The `Readable` stream will properly handle multi-byte characters delivered - * through the stream that would otherwise become improperly decoded if simply - * pulled from the stream as `Buffer` objects. - * - * ```js - * const readable = getReadableStreamSomehow(); - * readable.setEncoding('utf8'); - * readable.on('data', (chunk) => { - * assert.equal(typeof chunk, 'string'); - * console.log('Got %d characters of string data:', chunk.length); - * }); - * ``` - * @since v0.9.4 - * @param encoding The encoding to use. - */ - setEncoding(encoding: BufferEncoding): this; - /** - * The `readable.pause()` method will cause a stream in flowing mode to stop - * emitting `'data'` events, switching out of flowing mode. Any data that - * becomes available will remain in the internal buffer. - * - * ```js - * const readable = getReadableStreamSomehow(); - * readable.on('data', (chunk) => { - * console.log(`Received ${chunk.length} bytes of data.`); - * readable.pause(); - * console.log('There will be no additional data for 1 second.'); - * setTimeout(() => { - * console.log('Now data will start flowing again.'); - * readable.resume(); - * }, 1000); - * }); - * ``` - * - * The `readable.pause()` method has no effect if there is a `'readable'`event listener. - * @since v0.9.4 - */ - pause(): this; - /** - * The `readable.resume()` method causes an explicitly paused `Readable` stream to - * resume emitting `'data'` events, switching the stream into flowing mode. - * - * The `readable.resume()` method can be used to fully consume the data from a - * stream without actually processing any of that data: - * - * ```js - * getReadableStreamSomehow() - * .resume() - * .on('end', () => { - * console.log('Reached the end, but did not read anything.'); - * }); - * ``` - * - * The `readable.resume()` method has no effect if there is a `'readable'`event listener. - * @since v0.9.4 - */ - resume(): this; - /** - * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most - * typical cases, there will be no reason to - * use this method directly. - * - * ```js - * const readable = new stream.Readable(); - * - * readable.isPaused(); // === false - * readable.pause(); - * readable.isPaused(); // === true - * readable.resume(); - * readable.isPaused(); // === false - * ``` - * @since v0.11.14 - */ - isPaused(): boolean; - /** - * The `readable.unpipe()` method detaches a `Writable` stream previously attached - * using the {@link pipe} method. - * - * If the `destination` is not specified, then _all_ pipes are detached. - * - * If the `destination` is specified, but no pipe is set up for it, then - * the method does nothing. - * - * ```js - * const fs = require('fs'); - * const readable = getReadableStreamSomehow(); - * const writable = fs.createWriteStream('file.txt'); - * // All the data from readable goes into 'file.txt', - * // but only for the first second. - * readable.pipe(writable); - * setTimeout(() => { - * console.log('Stop writing to file.txt.'); - * readable.unpipe(writable); - * console.log('Manually close the file stream.'); - * writable.end(); - * }, 1000); - * ``` - * @since v0.9.4 - * @param destination Optional specific stream to unpipe - */ - unpipe(destination?: NodeJS.WritableStream): this; - /** - * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the - * same as `readable.push(null)`, after which no more data can be written. The EOF - * signal is put at the end of the buffer and any buffered data will still be - * flushed. - * - * The `readable.unshift()` method pushes a chunk of data back into the internal - * buffer. This is useful in certain situations where a stream is being consumed by - * code that needs to "un-consume" some amount of data that it has optimistically - * pulled out of the source, so that the data can be passed on to some other party. - * - * The `stream.unshift(chunk)` method cannot be called after the `'end'` event - * has been emitted or a runtime error will be thrown. - * - * Developers using `stream.unshift()` often should consider switching to - * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. - * - * ```js - * // Pull off a header delimited by \n\n. - * // Use unshift() if we get too much. - * // Call the callback with (error, header, stream). - * const { StringDecoder } = require('string_decoder'); - * function parseHeader(stream, callback) { - * stream.on('error', callback); - * stream.on('readable', onReadable); - * const decoder = new StringDecoder('utf8'); - * let header = ''; - * function onReadable() { - * let chunk; - * while (null !== (chunk = stream.read())) { - * const str = decoder.write(chunk); - * if (str.includes('\n\n')) { - * // Found the header boundary. - * const split = str.split(/\n\n/); - * header += split.shift(); - * const remaining = split.join('\n\n'); - * const buf = Buffer.from(remaining, 'utf8'); - * stream.removeListener('error', callback); - * // Remove the 'readable' listener before unshifting. - * stream.removeListener('readable', onReadable); - * if (buf.length) - * stream.unshift(buf); - * // Now the body of the message can be read from the stream. - * callback(null, header, stream); - * return; - * } - * // Still reading the header. - * header += str; - * } - * } - * } - * ``` - * - * Unlike {@link push}, `stream.unshift(chunk)` will not - * end the reading process by resetting the internal reading state of the stream. - * This can cause unexpected results if `readable.unshift()` is called during a - * read (i.e. from within a {@link _read} implementation on a - * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, - * however it is best to simply avoid calling `readable.unshift()` while in the - * process of performing a read. - * @since v0.9.11 - * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode - * streams, `chunk` may be any JavaScript value. - * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. - */ - unshift(chunk: any, encoding?: BufferEncoding): void; - /** - * Prior to Node.js 0.10, streams did not implement the entire `stream` module API - * as it is currently defined. (See `Compatibility` for more information.) - * - * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` - * stream that uses - * the old stream as its data source. - * - * It will rarely be necessary to use `readable.wrap()` but the method has been - * provided as a convenience for interacting with older Node.js applications and - * libraries. - * - * ```js - * const { OldReader } = require('./old-api-module.js'); - * const { Readable } = require('stream'); - * const oreader = new OldReader(); - * const myReader = new Readable().wrap(oreader); - * - * myReader.on('readable', () => { - * myReader.read(); // etc. - * }); - * ``` - * @since v0.9.4 - * @param stream An "old style" readable stream - */ - wrap(stream: NodeJS.ReadableStream): this; - push(chunk: any, encoding?: BufferEncoding): boolean; - _destroy(error: Error | null, callback: (error?: Error | null) => void): void; - /** - * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable - * stream will release any internal resources and subsequent calls to `push()`will be ignored. - * - * Once `destroy()` has been called any further calls will be a no-op and no - * further errors except from `_destroy()` may be emitted as `'error'`. - * - * Implementors should not override this method, but instead implement `readable._destroy()`. - * @since v8.0.0 - * @param error Error which will be passed as payload in `'error'` event - */ - destroy(error?: Error): this; - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. end - * 4. error - * 5. pause - * 6. readable - * 7. resume - */ - addListener(event: 'close', listener: () => void): this; - addListener(event: 'data', listener: (chunk: any) => void): this; - addListener(event: 'end', listener: () => void): this; - addListener(event: 'error', listener: (err: Error) => void): this; - addListener(event: 'pause', listener: () => void): this; - addListener(event: 'readable', listener: () => void): this; - addListener(event: 'resume', listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: 'close'): boolean; - emit(event: 'data', chunk: any): boolean; - emit(event: 'end'): boolean; - emit(event: 'error', err: Error): boolean; - emit(event: 'pause'): boolean; - emit(event: 'readable'): boolean; - emit(event: 'resume'): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: 'close', listener: () => void): this; - on(event: 'data', listener: (chunk: any) => void): this; - on(event: 'end', listener: () => void): this; - on(event: 'error', listener: (err: Error) => void): this; - on(event: 'pause', listener: () => void): this; - on(event: 'readable', listener: () => void): this; - on(event: 'resume', listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: 'close', listener: () => void): this; - once(event: 'data', listener: (chunk: any) => void): this; - once(event: 'end', listener: () => void): this; - once(event: 'error', listener: (err: Error) => void): this; - once(event: 'pause', listener: () => void): this; - once(event: 'readable', listener: () => void): this; - once(event: 'resume', listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: 'close', listener: () => void): this; - prependListener(event: 'data', listener: (chunk: any) => void): this; - prependListener(event: 'end', listener: () => void): this; - prependListener(event: 'error', listener: (err: Error) => void): this; - prependListener(event: 'pause', listener: () => void): this; - prependListener(event: 'readable', listener: () => void): this; - prependListener(event: 'resume', listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: 'close', listener: () => void): this; - prependOnceListener(event: 'data', listener: (chunk: any) => void): this; - prependOnceListener(event: 'end', listener: () => void): this; - prependOnceListener(event: 'error', listener: (err: Error) => void): this; - prependOnceListener(event: 'pause', listener: () => void): this; - prependOnceListener(event: 'readable', listener: () => void): this; - prependOnceListener(event: 'resume', listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: 'close', listener: () => void): this; - removeListener(event: 'data', listener: (chunk: any) => void): this; - removeListener(event: 'end', listener: () => void): this; - removeListener(event: 'error', listener: (err: Error) => void): this; - removeListener(event: 'pause', listener: () => void): this; - removeListener(event: 'readable', listener: () => void): this; - removeListener(event: 'resume', listener: () => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - [Symbol.asyncIterator](): AsyncIterableIterator; } interface WritableOptions extends StreamOptions { decodeStrings?: boolean | undefined; @@ -519,7 +813,7 @@ declare module 'stream' { /** * @since v0.9.4 */ - class Writable extends Stream implements NodeJS.WritableStream { + class Writable extends WritableBase { /** * A utility method for creating a `Writable` from a web `WritableStream`. * @since v17.0.0 @@ -532,292 +826,6 @@ declare module 'stream' { * @experimental */ static toWeb(streamWritable: Writable): streamWeb.WritableStream; - /** - * Is `true` if it is safe to call `writable.write()`, which means - * the stream has not been destroyed, errored or ended. - * @since v11.4.0 - */ - readonly writable: boolean; - /** - * Is `true` after `writable.end()` has been called. This property - * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. - * @since v12.9.0 - */ - readonly writableEnded: boolean; - /** - * Is set to `true` immediately before the `'finish'` event is emitted. - * @since v12.6.0 - */ - readonly writableFinished: boolean; - /** - * Return the value of `highWaterMark` passed when creating this `Writable`. - * @since v9.3.0 - */ - readonly writableHighWaterMark: number; - /** - * This property contains the number of bytes (or objects) in the queue - * ready to be written. The value provides introspection data regarding - * the status of the `highWaterMark`. - * @since v9.4.0 - */ - readonly writableLength: number; - /** - * Getter for the property `objectMode` of a given `Writable` stream. - * @since v12.3.0 - */ - readonly writableObjectMode: boolean; - /** - * Number of times `writable.uncork()` needs to be - * called in order to fully uncork the stream. - * @since v13.2.0, v12.16.0 - */ - readonly writableCorked: number; - /** - * Is `true` after `writable.destroy()` has been called. - * @since v8.0.0 - */ - destroyed: boolean; - /** - * Is true after 'close' has been emitted. - * @since v18.0.0 - */ - readonly closed: boolean; - /** - * Returns error if the stream has been destroyed with an error. - * @since v18.0.0 - */ - readonly errored: Error | null; - /** - * Is `true` if the stream's buffer has been full and stream will emit 'drain'. - * @since v15.2.0, v14.17.0 - */ - readonly writableNeedDrain: boolean; - constructor(opts?: WritableOptions); - _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - _writev?( - chunks: Array<{ - chunk: any; - encoding: BufferEncoding; - }>, - callback: (error?: Error | null) => void - ): void; - _construct?(callback: (error?: Error | null) => void): void; - _destroy(error: Error | null, callback: (error?: Error | null) => void): void; - _final(callback: (error?: Error | null) => void): void; - /** - * The `writable.write()` method writes some data to the stream, and calls the - * supplied `callback` once the data has been fully handled. If an error - * occurs, the `callback` will be called with the error as its - * first argument. The `callback` is called asynchronously and before `'error'` is - * emitted. - * - * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. - * If `false` is returned, further attempts to write data to the stream should - * stop until the `'drain'` event is emitted. - * - * While a stream is not draining, calls to `write()` will buffer `chunk`, and - * return false. Once all currently buffered chunks are drained (accepted for - * delivery by the operating system), the `'drain'` event will be emitted. - * Once `write()` returns false, do not write more chunks - * until the `'drain'` event is emitted. While calling `write()` on a stream that - * is not draining is allowed, Node.js will buffer all written chunks until - * maximum memory usage occurs, at which point it will abort unconditionally. - * Even before it aborts, high memory usage will cause poor garbage collector - * performance and high RSS (which is not typically released back to the system, - * even after the memory is no longer required). Since TCP sockets may never - * drain if the remote peer does not read the data, writing a socket that is - * not draining may lead to a remotely exploitable vulnerability. - * - * Writing data while the stream is not draining is particularly - * problematic for a `Transform`, because the `Transform` streams are paused - * by default until they are piped or a `'data'` or `'readable'` event handler - * is added. - * - * If the data to be written can be generated or fetched on demand, it is - * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is - * possible to respect backpressure and avoid memory issues using the `'drain'` event: - * - * ```js - * function write(data, cb) { - * if (!stream.write(data)) { - * stream.once('drain', cb); - * } else { - * process.nextTick(cb); - * } - * } - * - * // Wait for cb to be called before doing any other write. - * write('hello', () => { - * console.log('Write completed, do more writes now.'); - * }); - * ``` - * - * A `Writable` stream in object mode will always ignore the `encoding` argument. - * @since v0.9.4 - * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any - * JavaScript value other than `null`. - * @param [encoding='utf8'] The encoding, if `chunk` is a string. - * @param callback Callback for when this chunk of data is flushed. - * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; - write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; - /** - * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. - * @since v0.11.15 - * @param encoding The new default encoding - */ - setDefaultEncoding(encoding: BufferEncoding): this; - /** - * Calling the `writable.end()` method signals that no more data will be written - * to the `Writable`. The optional `chunk` and `encoding` arguments allow one - * final additional chunk of data to be written immediately before closing the - * stream. - * - * Calling the {@link write} method after calling {@link end} will raise an error. - * - * ```js - * // Write 'hello, ' and then end with 'world!'. - * const fs = require('fs'); - * const file = fs.createWriteStream('example.txt'); - * file.write('hello, '); - * file.end('world!'); - * // Writing more now is not allowed! - * ``` - * @since v0.9.4 - * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any - * JavaScript value other than `null`. - * @param encoding The encoding if `chunk` is a string - * @param callback Callback for when the stream is finished. - */ - end(cb?: () => void): this; - end(chunk: any, cb?: () => void): this; - end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; - /** - * The `writable.cork()` method forces all written data to be buffered in memory. - * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. - * - * The primary intent of `writable.cork()` is to accommodate a situation in which - * several small chunks are written to the stream in rapid succession. Instead of - * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them - * all to `writable._writev()`, if present. This prevents a head-of-line blocking - * situation where data is being buffered while waiting for the first small chunk - * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. - * - * See also: `writable.uncork()`, `writable._writev()`. - * @since v0.11.2 - */ - cork(): void; - /** - * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. - * - * When using `writable.cork()` and `writable.uncork()` to manage the buffering - * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event - * loop phase. - * - * ```js - * stream.cork(); - * stream.write('some '); - * stream.write('data '); - * process.nextTick(() => stream.uncork()); - * ``` - * - * If the `writable.cork()` method is called multiple times on a stream, the - * same number of calls to `writable.uncork()` must be called to flush the buffered - * data. - * - * ```js - * stream.cork(); - * stream.write('some '); - * stream.cork(); - * stream.write('data '); - * process.nextTick(() => { - * stream.uncork(); - * // The data will not be flushed until uncork() is called a second time. - * stream.uncork(); - * }); - * ``` - * - * See also: `writable.cork()`. - * @since v0.11.2 - */ - uncork(): void; - /** - * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable - * stream has ended and subsequent calls to `write()` or `end()` will result in - * an `ERR_STREAM_DESTROYED` error. - * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. - * Use `end()` instead of destroy if data should flush before close, or wait for - * the `'drain'` event before destroying the stream. - * - * Once `destroy()` has been called any further calls will be a no-op and no - * further errors except from `_destroy()` may be emitted as `'error'`. - * - * Implementors should not override this method, - * but instead implement `writable._destroy()`. - * @since v8.0.0 - * @param error Optional, an error to emit with `'error'` event. - */ - destroy(error?: Error): this; - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. drain - * 3. error - * 4. finish - * 5. pipe - * 6. unpipe - */ - addListener(event: 'close', listener: () => void): this; - addListener(event: 'drain', listener: () => void): this; - addListener(event: 'error', listener: (err: Error) => void): this; - addListener(event: 'finish', listener: () => void): this; - addListener(event: 'pipe', listener: (src: Readable) => void): this; - addListener(event: 'unpipe', listener: (src: Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: 'close'): boolean; - emit(event: 'drain'): boolean; - emit(event: 'error', err: Error): boolean; - emit(event: 'finish'): boolean; - emit(event: 'pipe', src: Readable): boolean; - emit(event: 'unpipe', src: Readable): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: 'close', listener: () => void): this; - on(event: 'drain', listener: () => void): this; - on(event: 'error', listener: (err: Error) => void): this; - on(event: 'finish', listener: () => void): this; - on(event: 'pipe', listener: (src: Readable) => void): this; - on(event: 'unpipe', listener: (src: Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: 'close', listener: () => void): this; - once(event: 'drain', listener: () => void): this; - once(event: 'error', listener: (err: Error) => void): this; - once(event: 'finish', listener: () => void): this; - once(event: 'pipe', listener: (src: Readable) => void): this; - once(event: 'unpipe', listener: (src: Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: 'close', listener: () => void): this; - prependListener(event: 'drain', listener: () => void): this; - prependListener(event: 'error', listener: (err: Error) => void): this; - prependListener(event: 'finish', listener: () => void): this; - prependListener(event: 'pipe', listener: (src: Readable) => void): this; - prependListener(event: 'unpipe', listener: (src: Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: 'close', listener: () => void): this; - prependOnceListener(event: 'drain', listener: () => void): this; - prependOnceListener(event: 'error', listener: (err: Error) => void): this; - prependOnceListener(event: 'finish', listener: () => void): this; - prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; - prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: 'close', listener: () => void): this; - removeListener(event: 'drain', listener: () => void): this; - removeListener(event: 'error', listener: (err: Error) => void): this; - removeListener(event: 'finish', listener: () => void): this; - removeListener(event: 'pipe', listener: (src: Readable) => void): this; - removeListener(event: 'unpipe', listener: (src: Readable) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; } interface DuplexOptions extends ReadableOptions, WritableOptions { allowHalfOpen?: boolean | undefined; @@ -850,7 +858,7 @@ declare module 'stream' { * * `crypto streams` * @since v0.9.4 */ - class Duplex extends Readable implements Writable { + class Duplex extends ReadableBase implements WritableBase { readonly writable: boolean; readonly writableEnded: boolean; readonly writableFinished: boolean; @@ -864,7 +872,7 @@ declare module 'stream' { /** * If `false` then the stream will automatically end the writable side when the * readable side ends. Set initially by the `allowHalfOpen` constructor option, - * which defaults to `false`. + * which defaults to `true`. * * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is * emitted. @@ -912,6 +920,126 @@ declare module 'stream' { end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; cork(): void; uncork(): void; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: any) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'pipe', listener: (src: Readable) => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'unpipe', listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: any): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pause'): boolean; + emit(event: 'pipe', src: Readable): boolean; + emit(event: 'readable'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'unpipe', src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: any) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'pipe', listener: (src: Readable) => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'unpipe', listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: any) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'pipe', listener: (src: Readable) => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'unpipe', listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: any) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: Readable) => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: any) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'data', listener: (chunk: any) => void): this; + removeListener(event: 'drain', listener: () => void): this; + removeListener(event: 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'finish', listener: () => void): this; + removeListener(event: 'pause', listener: () => void): this; + removeListener(event: 'pipe', listener: (src: Readable) => void): this; + removeListener(event: 'readable', listener: () => void): this; + removeListener(event: 'resume', listener: () => void): this; + removeListener(event: 'unpipe', listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; } type TransformCallback = (error?: Error | null, data?: any) => void; interface TransformOptions extends DuplexOptions { @@ -953,18 +1081,21 @@ declare module 'stream' { */ class PassThrough extends Transform {} /** + * A stream to attach a signal to. + * * Attaches an AbortSignal to a readable or writeable stream. This lets code * control stream destruction using an `AbortController`. * - * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream, and `controller.error(new + * AbortError())` for webstreams. * * ```js - * const fs = require('fs'); + * const fs = require('node:fs'); * * const controller = new AbortController(); * const read = addAbortSignal( * controller.signal, - * fs.createReadStream(('object.json')) + * fs.createReadStream(('object.json')), * ); * // Later, abort the operation closing the stream * controller.abort(); @@ -977,7 +1108,7 @@ declare module 'stream' { * setTimeout(() => controller.abort(), 10_000); // set a timeout * const stream = addAbortSignal( * controller.signal, - * fs.createReadStream(('object.json')) + * fs.createReadStream(('object.json')), * ); * (async () => { * try { @@ -993,22 +1124,70 @@ declare module 'stream' { * } * })(); * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` * @since v15.4.0 * @param signal A signal representing possible cancellation * @param stream a stream to attach a signal to */ function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `16384` (16 KiB), or `16` for `objectMode`. + * @since v19.9.0 + * @param objectMode + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param objectMode + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; interface FinishedOptions extends Abortable { error?: boolean | undefined; readable?: boolean | undefined; writable?: boolean | undefined; } /** + * A readable and/or writable stream/webstream. + * * A function to get notified when a stream is no longer readable, writable * or has experienced an error or a premature close event. * * ```js - * const { finished } = require('stream'); + * const { finished } = require('node:stream'); + * const fs = require('node:fs'); * * const rs = fs.createReadStream('archive.tar'); * @@ -1026,21 +1205,7 @@ declare module 'stream' { * Especially useful in error handling scenarios where a stream is destroyed * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. * - * The `finished` API provides promise version: - * - * ```js - * const { finished } = require('stream/promises'); - * - * const rs = fs.createReadStream('archive.tar'); - * - * async function run() { - * await finished(rs); - * console.log('Stream is done reading.'); - * } - * - * run().catch(console.error); - * rs.resume(); // Drain the stream. - * ``` + * The `finished` API provides `promise version`. * * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been * invoked. The reason for this is so that unexpected `'error'` events (due to @@ -1080,16 +1245,17 @@ declare module 'stream' { : (err: NodeJS.ErrnoException | null) => void; type PipelinePromise> = S extends PipelineDestinationPromiseFunction ? Promise

: Promise; interface PipelineOptions { - signal: AbortSignal; + signal?: AbortSignal | undefined; + end?: boolean | undefined; } /** * A module method to pipe between streams and generators forwarding errors and * properly cleaning up and provide a callback when the pipeline is complete. * * ```js - * const { pipeline } = require('stream'); - * const fs = require('fs'); - * const zlib = require('zlib'); + * const { pipeline } = require('node:stream'); + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); * * // Use the pipeline API to easily pipe a series of streams * // together and get notified when the pipeline is fully done. @@ -1106,95 +1272,11 @@ declare module 'stream' { * } else { * console.log('Pipeline succeeded.'); * } - * } + * }, * ); * ``` * - * The `pipeline` API provides a promise version, which can also - * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with - * an`AbortError`. - * - * ```js - * const { pipeline } = require('stream/promises'); - * - * async function run() { - * await pipeline( - * fs.createReadStream('archive.tar'), - * zlib.createGzip(), - * fs.createWriteStream('archive.tar.gz') - * ); - * console.log('Pipeline succeeded.'); - * } - * - * run().catch(console.error); - * ``` - * - * To use an `AbortSignal`, pass it inside an options object, - * as the last argument: - * - * ```js - * const { pipeline } = require('stream/promises'); - * - * async function run() { - * const ac = new AbortController(); - * const signal = ac.signal; - * - * setTimeout(() => ac.abort(), 1); - * await pipeline( - * fs.createReadStream('archive.tar'), - * zlib.createGzip(), - * fs.createWriteStream('archive.tar.gz'), - * { signal }, - * ); - * } - * - * run().catch(console.error); // AbortError - * ``` - * - * The `pipeline` API also supports async generators: - * - * ```js - * const { pipeline } = require('stream/promises'); - * const fs = require('fs'); - * - * async function run() { - * await pipeline( - * fs.createReadStream('lowercase.txt'), - * async function* (source, { signal }) { - * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. - * for await (const chunk of source) { - * yield await processChunk(chunk, { signal }); - * } - * }, - * fs.createWriteStream('uppercase.txt') - * ); - * console.log('Pipeline succeeded.'); - * } - * - * run().catch(console.error); - * ``` - * - * Remember to handle the `signal` argument passed into the async generator. - * Especially in the case where the async generator is the source for the - * pipeline (i.e. first argument) or the pipeline will never complete. - * - * ```js - * const { pipeline } = require('stream/promises'); - * const fs = require('fs'); - * - * async function run() { - * await pipeline( - * async function* ({ signal }) { - * await someLongRunningfn({ signal }); - * yield 'asd'; - * }, - * fs.createWriteStream('uppercase.txt') - * ); - * console.log('Pipeline succeeded.'); - * } - * - * run().catch(console.error); - * ``` + * The `pipeline` API provides a `promise version`. * * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: * @@ -1213,9 +1295,9 @@ declare module 'stream' { * See the example below: * * ```js - * const fs = require('fs'); - * const http = require('http'); - * const { pipeline } = require('stream'); + * const fs = require('node:fs'); + * const http = require('node:http'); + * const { pipeline } = require('node:stream'); * * const server = http.createServer((req, res) => { * const fileStream = fs.createReadStream('./fileNotExist.txt'); @@ -1316,19 +1398,18 @@ declare module 'stream' { ref(): void; unref(): void; } - /** * Returns whether the stream has encountered an error. - * @since v17.3.0 + * @since v17.3.0, v16.14.0 + * @experimental */ function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; - /** * Returns whether the stream is readable. - * @since v17.4.0 + * @since v17.4.0, v16.14.0 + * @experimental */ function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; - const promises: typeof streamPromises; const consumers: typeof streamConsumers; } diff --git a/node_modules/@types/node/stream/consumers.d.ts b/node_modules/@types/node/stream/consumers.d.ts index 1ebf12e..2fd9424 100644 --- a/node_modules/@types/node/stream/consumers.d.ts +++ b/node_modules/@types/node/stream/consumers.d.ts @@ -1,5 +1,5 @@ declare module 'stream/consumers' { - import { Blob as NodeBlob } from "node:buffer"; + import { Blob as NodeBlob } from 'node:buffer'; import { Readable } from 'node:stream'; function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts index a585804..a069bb8 100644 --- a/node_modules/@types/node/string_decoder.d.ts +++ b/node_modules/@types/node/string_decoder.d.ts @@ -1,16 +1,16 @@ /** - * The `string_decoder` module provides an API for decoding `Buffer` objects into - * strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 * characters. It can be accessed using: * * ```js - * const { StringDecoder } = require('string_decoder'); + * const { StringDecoder } = require('node:string_decoder'); * ``` * * The following example shows the basic use of the `StringDecoder` class. * * ```js - * const { StringDecoder } = require('string_decoder'); + * const { StringDecoder } = require('node:string_decoder'); * const decoder = new StringDecoder('utf8'); * * const cent = Buffer.from([0xC2, 0xA2]); @@ -29,14 +29,14 @@ * symbol (`€`) are written over three separate operations: * * ```js - * const { StringDecoder } = require('string_decoder'); + * const { StringDecoder } = require('node:string_decoder'); * const decoder = new StringDecoder('utf8'); * * decoder.write(Buffer.from([0xE2])); * decoder.write(Buffer.from([0x82])); * console.log(decoder.end(Buffer.from([0xAC]))); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/string_decoder.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/string_decoder.js) */ declare module 'string_decoder' { class StringDecoder { diff --git a/node_modules/@types/node/test.d.ts b/node_modules/@types/node/test.d.ts index 8e20710..5202454 100644 --- a/node_modules/@types/node/test.d.ts +++ b/node_modules/@types/node/test.d.ts @@ -1,28 +1,112 @@ /** - * The `node:test` module provides a standalone testing module. - * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/test.js) + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the`Promise` rejects, and is considered passing if the `Promise` resolves. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the`test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/test.js) */ declare module 'node:test' { + import { Readable } from 'node:stream'; /** - * Programmatically start the test runner. - * @since v18.9.0 - * @param options Configuration options for running tests. - * @returns A {@link TapStream} that emits events about the test execution. + * ```js + * import { tap } from 'node:test/reporters'; + * import process from 'node:process'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. The following properties are supported: */ - function run(options?: RunOptions): TapStream; - + function run(options?: RunOptions): TestsStream; /** - * The `test()` function is the value imported from the test module. Each invocation of this - * function results in the creation of a test point in the TAP output. + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. * - * The {@link TestContext} object passed to the fn argument can be used to perform actions - * related to the current test. Examples include skipping the test, adding additional TAP - * diagnostic information, or creating subtests. + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. * - * `test()` returns a {@link Promise} that resolves once the test completes. The return value - * can usually be discarded for top level tests. However, the return value from subtests should - * be used to prevent the parent test from finishing first and cancelling the subtest as shown - * in the following example. + * `test()` returns a `Promise` that resolves once the test completes. + * if `test()` is called within a `describe()` block, it resolve immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. * * ```js * test('top level test', async (t) => { @@ -36,90 +120,144 @@ declare module 'node:test' { * }); * }); * ``` - * @since v18.0.0 - * @param name The name of the test, which is displayed when reporting test results. - * Default: The `name` property of fn, or `''` if `fn` does not have a name. - * @param options Configuration options for the test - * @param fn The function under test. The first argument to this function is a - * {@link TestContext} object. If the test uses callbacks, the callback function is - * passed as the second argument. Default: A no-op function. - * @returns A {@link Promise} resolved with `undefined` once the test completes. + * + * The `timeout` option can be used to fail the test if it takes longer than`timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param [name='The name'] The name of the test, which is displayed when reporting test results. + * @param options Configuration options for the test. The following properties are supported: + * @param [fn='A no-op function'] The function under test. The first argument to this function is a {@link TestContext} object. If the test uses callbacks, the callback function is passed as the + * second argument. + * @return Resolved with `undefined` once the test completes, or immediately if the test runs within {@link describe}. */ function test(name?: string, fn?: TestFn): Promise; function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; function test(options?: TestOptions, fn?: TestFn): Promise; function test(fn?: TestFn): Promise; - + namespace test { + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + run, + mock, + test, + skip, + todo, + only + }; + } /** - * @since v18.6.0 - * @param name The name of the suite, which is displayed when reporting suite results. - * Default: The `name` property of fn, or `''` if `fn` does not have a name. - * @param options Configuration options for the suite - * @param fn The function under suite. Default: A no-op function. + * The `describe()` function imported from the `node:test` module. Each + * invocation of this function results in the creation of a Subtest. + * After invocation of top level `describe` functions, + * all top level tests and suites will execute. + * @param [name='The name'] The name of the suite, which is displayed when reporting test results. + * @param options Configuration options for the suite. supports the same options as `test([name][, options][, fn])`. + * @param [fn='A no-op function'] The function under suite declaring all subtests and subsuites. The first argument to this function is a {@link SuiteContext} object. + * @return `undefined`. */ function describe(name?: string, options?: TestOptions, fn?: SuiteFn): void; function describe(name?: string, fn?: SuiteFn): void; function describe(options?: TestOptions, fn?: SuiteFn): void; function describe(fn?: SuiteFn): void; namespace describe { - // Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + /** + * Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + */ function skip(name?: string, options?: TestOptions, fn?: SuiteFn): void; function skip(name?: string, fn?: SuiteFn): void; function skip(options?: TestOptions, fn?: SuiteFn): void; function skip(fn?: SuiteFn): void; - - // Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + /** + * Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + */ function todo(name?: string, options?: TestOptions, fn?: SuiteFn): void; function todo(name?: string, fn?: SuiteFn): void; function todo(options?: TestOptions, fn?: SuiteFn): void; function todo(fn?: SuiteFn): void; + /** + * Shorthand for marking a suite as `only`, same as `describe([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): void; + function only(name?: string, fn?: SuiteFn): void; + function only(options?: TestOptions, fn?: SuiteFn): void; + function only(fn?: SuiteFn): void; } - /** - * @since v18.6.0 - * @param name The name of the test, which is displayed when reporting test results. - * Default: The `name` property of fn, or `''` if `fn` does not have a name. - * @param options Configuration options for the test - * @param fn The function under test. If the test uses callbacks, the callback function is - * passed as the second argument. Default: A no-op function. + * Shorthand for `test()`. + * + * The `it()` function is imported from the `node:test` module. + * @since v18.6.0, v16.17.0 */ - function it(name?: string, options?: TestOptions, fn?: ItFn): void; - function it(name?: string, fn?: ItFn): void; - function it(options?: TestOptions, fn?: ItFn): void; - function it(fn?: ItFn): void; + function it(name?: string, options?: TestOptions, fn?: TestFn): void; + function it(name?: string, fn?: TestFn): void; + function it(options?: TestOptions, fn?: TestFn): void; + function it(fn?: TestFn): void; namespace it { - // Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. - function skip(name?: string, options?: TestOptions, fn?: ItFn): void; - function skip(name?: string, fn?: ItFn): void; - function skip(options?: TestOptions, fn?: ItFn): void; - function skip(fn?: ItFn): void; - - // Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. - function todo(name?: string, options?: TestOptions, fn?: ItFn): void; - function todo(name?: string, fn?: ItFn): void; - function todo(options?: TestOptions, fn?: ItFn): void; - function todo(fn?: ItFn): void; + /** + * Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): void; + function skip(name?: string, fn?: TestFn): void; + function skip(options?: TestOptions, fn?: TestFn): void; + function skip(fn?: TestFn): void; + /** + * Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): void; + function todo(name?: string, fn?: TestFn): void; + function todo(options?: TestOptions, fn?: TestFn): void; + function todo(fn?: TestFn): void; + /** + * Shorthand for marking a test as `only`, same as `it([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): void; + function only(name?: string, fn?: TestFn): void; + function only(options?: TestOptions, fn?: TestFn): void; + function only(fn?: TestFn): void; } - + /** + * Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): void; + function skip(name?: string, fn?: TestFn): void; + function skip(options?: TestOptions, fn?: TestFn): void; + function skip(fn?: TestFn): void; + /** + * Shorthand for marking a test as `TODO`, same as `test([name], { todo: true }[, fn])`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): void; + function todo(name?: string, fn?: TestFn): void; + function todo(options?: TestOptions, fn?: TestFn): void; + function todo(fn?: TestFn): void; + /** + * Shorthand for marking a test as `only`, same as `test([name], { only: true }[, fn])`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): void; + function only(name?: string, fn?: TestFn): void; + function only(options?: TestOptions, fn?: TestFn): void; + function only(fn?: TestFn): void; /** * The type of a function under test. The first argument to this function is a * {@link TestContext} object. If the test uses callbacks, the callback function is passed as * the second argument. */ type TestFn = (t: TestContext, done: (result?: any) => void) => any; - /** * The type of a function under Suite. * If the test uses callbacks, the callback function is passed as an argument */ type SuiteFn = (done: (result?: any) => void) => void; - - /** - * The type of a function under test. - * If the test uses callbacks, the callback function is passed as an argument - */ - type ItFn = (done: (result?: any) => void) => any; - interface RunOptions { /** * If a number is provided, then that many files would run in parallel. @@ -129,132 +267,189 @@ declare module 'node:test' { * @default true */ concurrency?: number | boolean | undefined; - /** * An array containing the list of files to run. * If unspecified, the test runner execution model will be used. */ files?: readonly string[] | undefined; - /** * Allows aborting an in-progress test execution. * @default undefined */ signal?: AbortSignal | undefined; - /** * A number of milliseconds the test will fail after. * If unspecified, subtests inherit this value from their parent. * @default Infinity */ timeout?: number | undefined; - /** * Sets inspector port of test child process. * If a nullish value is provided, each process gets its own port, * incremented from the primary's `process.debugPort`. */ inspectPort?: number | (() => number) | undefined; + /** + * That can be used to only run tests whose name matches the provided pattern. + * Test name patterns are interpreted as JavaScript regular expressions. + * For each test that is executed, any corresponding test hooks, such as `beforeEach()`, are also run. + */ + testNamePatterns?: string | RegExp | string[] | RegExp[]; } - /** - * A successful call of the `run()` method will return a new `TapStream` object, - * streaming a [TAP](https://testanything.org/) output. - * `TapStream` will emit events in the order of the tests' definitions. - * @since v18.9.0 + * A successful call to `run()` method will return a new `TestsStream` object, streaming a series of events representing the execution of the tests.`TestsStream` will emit events, in the + * order of the tests definition + * @since v18.9.0, v16.19.0 */ - interface TapStream extends NodeJS.ReadableStream { - addListener(event: 'test:diagnostic', listener: (message: string) => void): this; + class TestsStream extends Readable implements NodeJS.ReadableStream { + addListener(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; addListener(event: 'test:fail', listener: (data: TestFail) => void): this; addListener(event: 'test:pass', listener: (data: TestPass) => void): this; + addListener(event: 'test:plan', listener: (data: TestPlan) => void): this; + addListener(event: 'test:start', listener: (data: TestStart) => void): this; addListener(event: string, listener: (...args: any[]) => void): this; - emit(event: 'test:diagnostic', message: string): boolean; + emit(event: 'test:diagnostic', data: DiagnosticData): boolean; emit(event: 'test:fail', data: TestFail): boolean; emit(event: 'test:pass', data: TestPass): boolean; + emit(event: 'test:plan', data: TestPlan): boolean; + emit(event: 'test:start', data: TestStart): boolean; emit(event: string | symbol, ...args: any[]): boolean; - on(event: 'test:diagnostic', listener: (message: string) => void): this; + on(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; on(event: 'test:fail', listener: (data: TestFail) => void): this; on(event: 'test:pass', listener: (data: TestPass) => void): this; + on(event: 'test:plan', listener: (data: TestPlan) => void): this; + on(event: 'test:start', listener: (data: TestStart) => void): this; on(event: string, listener: (...args: any[]) => void): this; - once(event: 'test:diagnostic', listener: (message: string) => void): this; + once(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; once(event: 'test:fail', listener: (data: TestFail) => void): this; once(event: 'test:pass', listener: (data: TestPass) => void): this; + once(event: 'test:plan', listener: (data: TestPlan) => void): this; + once(event: 'test:start', listener: (data: TestStart) => void): this; once(event: string, listener: (...args: any[]) => void): this; - prependListener(event: 'test:diagnostic', listener: (message: string) => void): this; + prependListener(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; prependListener(event: 'test:fail', listener: (data: TestFail) => void): this; prependListener(event: 'test:pass', listener: (data: TestPass) => void): this; + prependListener(event: 'test:plan', listener: (data: TestPlan) => void): this; + prependListener(event: 'test:start', listener: (data: TestStart) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: 'test:diagnostic', listener: (message: string) => void): this; + prependOnceListener(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; prependOnceListener(event: 'test:fail', listener: (data: TestFail) => void): this; prependOnceListener(event: 'test:pass', listener: (data: TestPass) => void): this; + prependOnceListener(event: 'test:plan', listener: (data: TestPlan) => void): this; + prependOnceListener(event: 'test:start', listener: (data: TestStart) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; } - + interface DiagnosticData { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + } interface TestFail { /** - * The test duration. + * Additional execution metadata. */ - duration: number; - - /** - * The failure casing test to fail. - */ - error: Error; - + details: { + /** + * The duration of the test in milliseconds. + */ + duration: number; + /** + * The error thrown by the test. + */ + error: Error; + }; /** * The test name. */ name: string; - + /** + * The nesting level of the test. + */ + nesting: number; /** * The ordinal number of the test. */ testNumber: number; - /** * Present if `context.todo` is called. */ - todo?: string; - + todo?: string | boolean; /** * Present if `context.skip` is called. */ - skip?: string; + skip?: string | boolean; } - interface TestPass { /** - * The test duration. + * Additional execution metadata. */ - duration: number; - + details: { + /** + * The duration of the test in milliseconds. + */ + duration: number; + }; /** * The test name. */ name: string; - + /** + * The nesting level of the test. + */ + nesting: number; /** * The ordinal number of the test. */ testNumber: number; - /** * Present if `context.todo` is called. */ - todo?: string; - + todo?: string | boolean; /** * Present if `context.skip` is called. */ - skip?: string; + skip?: string | boolean; + } + interface TestPlan { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; } - /** - * An instance of `TestContext` is passed to each test function in order to interact with the - * test runner. However, the `TestContext` constructor is not exposed as part of the API. - * @since v18.0.0 + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 */ - interface TestContext { + class TestContext { + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v20.1.0 + */ + before: typeof before; /** * This function is used to create a hook running before each subtest of the current test. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as @@ -263,7 +458,14 @@ declare module 'node:test' { * @since v18.8.0 */ beforeEach: typeof beforeEach; - + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after: typeof after; /** * This function is used to create a hook running after each subtest of the current test. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as @@ -272,54 +474,84 @@ declare module 'node:test' { * @since v18.8.0 */ afterEach: typeof afterEach; - /** - * This function is used to write TAP diagnostics to the output. Any diagnostic information is - * included at the end of the test's results. This function does not return a value. - * @param message Message to be displayed as a TAP diagnostic. - * @since v18.0.0 + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. */ diagnostic(message: string): void; - /** * The name of the test. - * @since v18.8.0 + * @since v18.8.0, v16.18.0 */ readonly name: string; - /** - * If `shouldRunOnlyTests` is truthy, the test context will only run tests that have the `only` - * option set. Otherwise, all tests are run. If Node.js was not started with the `--test-only` - * command-line option, this function is a no-op. + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 * @param shouldRunOnlyTests Whether or not to run `only` tests. - * @since v18.0.0 */ runOnly(shouldRunOnlyTests: boolean): void; - /** - * Can be used to abort test subtasks when the test has been aborted. - * @since v18.7.0 + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 */ readonly signal: AbortSignal; - /** - * This function causes the test's output to indicate the test as skipped. If `message` is - * provided, it is included in the TAP output. Calling `skip()` does not terminate execution of - * the test function. This function does not return a value. - * @param message Optional skip message to be displayed in TAP output. - * @since v18.0.0 + * This function causes the test's output to indicate the test as skipped. If`message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. */ skip(message?: string): void; - /** - * This function adds a `TODO` directive to the test's output. If `message` is provided, it is - * included in the TAP output. Calling `todo()` does not terminate execution of the test - * function. This function does not return a value. - * @param message Optional `TODO` message to be displayed in TAP output. - * @since v18.0.0 + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. */ todo(message?: string): void; - /** * This function is used to create subtests under the current test. This function behaves in * the same fashion as the top level {@link test} function. @@ -333,8 +565,11 @@ declare module 'node:test' { * @returns A {@link Promise} resolved with `undefined` once the test completes. */ test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; } - interface TestOptions { /** * If a number is provided, then that many tests would run in parallel. @@ -345,27 +580,23 @@ declare module 'node:test' { * @default false */ concurrency?: number | boolean | undefined; - /** * If truthy, and the test context is configured to run `only` tests, then this test will be * run. Otherwise, the test is skipped. * @default false */ only?: boolean | undefined; - /** * Allows aborting an in-progress test. * @since v18.8.0 */ signal?: AbortSignal | undefined; - /** * If truthy, the test is skipped. If a string is provided, that string is displayed in the * test results as the reason for skipping the test. * @default false */ skip?: boolean | string | undefined; - /** * A number of milliseconds the test will fail after. If unspecified, subtests inherit this * value from their parent. @@ -373,7 +604,6 @@ declare module 'node:test' { * @since v18.7.0 */ timeout?: number | undefined; - /** * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in * the test results as the reason why the test is `TODO`. @@ -381,49 +611,77 @@ declare module 'node:test' { */ todo?: boolean | string | undefined; } - /** * This function is used to create a hook running before running a suite. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: */ function before(fn?: HookFn, options?: HookOptions): void; - /** - * This function is used to create a hook running after running a suite. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 + * This function is used to create a hook running after running a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: */ function after(fn?: HookFn, options?: HookOptions): void; - /** - * This function is used to create a hook running before each subtest of the current suite. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 + * This function is used to create a hook running + * before each subtest of the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: */ function beforeEach(fn?: HookFn, options?: HookOptions): void; - /** - * This function is used to create a hook running after each subtest of the current test. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 + * This function is used to create a hook running + * after each subtest of the current test. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: */ function afterEach(fn?: HookFn, options?: HookOptions): void; - /** * The hook function. If the hook uses callbacks, the callback function is passed as the * second argument. */ type HookFn = (done: (result?: any) => void) => any; - /** * Configuration options for hooks. * @since v18.8.0 @@ -433,7 +691,6 @@ declare module 'node:test' { * Allows aborting an in-progress hook. */ signal?: AbortSignal | undefined; - /** * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this * value from their parent. @@ -441,6 +698,355 @@ declare module 'node:test' { */ timeout?: number | undefined; } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + type NoOpFunction = (...args: any[]) => undefined; + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's`mock` property. + * @since v19.1.0, v18.13.0 + */ + class MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param [original='A no-op function'] An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. The following properties are supported: + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn(original?: F, implementation?: Implementation, options?: MockFunctionOptions): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. The following properties are supported: + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function + ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function + ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; - export { test as default, run, test, describe, it, before, after, beforeEach, afterEach }; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter`set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter`set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the`MockTracker` instance. Once disassociated, the mocks can still be used, but the`MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's`MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T + ? T + : F extends abstract new (...args: any) => infer T + ? T + : unknown, + Args = F extends (...args: infer Y) => any + ? Y + : F extends abstract new (...args: infer Y) => any + ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new (...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + class MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: Array>; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls`is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: Function): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: Function, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + export { test as default, run, test, describe, it, before, after, beforeEach, afterEach, mock, skip, only, todo }; } diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts index b26f3ce..5abcdca 100644 --- a/node_modules/@types/node/timers.d.ts +++ b/node_modules/@types/node/timers.d.ts @@ -1,12 +1,12 @@ /** * The `timer` module exposes a global API for scheduling functions to * be called at some future period of time. Because the timer functions are - * globals, there is no need to call `require('timers')` to use the API. + * globals, there is no need to call `require('node:timers')` to use the API. * * The timer functions within Node.js implement a similar API as the timers API * provided by Web Browsers but use a different internal implementation that is * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/timers.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/timers.js) */ declare module 'timers' { import { Abortable } from 'node:events'; @@ -33,7 +33,35 @@ declare module 'timers' { refresh(): this; [Symbol.toPrimitive](): number; } - interface Immediate extends RefCounted { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`functions that can be used to + * control this default behavior. + */ + class Immediate implements RefCounted { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @return a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @return a reference to `immediate` + */ + unref(): this; /** * If true, the `Immediate` object will keep the Node.js event loop active. * @since v11.0.0 @@ -41,7 +69,33 @@ declare module 'timers' { hasRef(): boolean; _onImmediate: Function; // to distinguish it from the Timeout class } - interface Timeout extends Timer { + /** + * This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the + * scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + class Timeout implements Timer { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @return a reference to `timeout` + */ + ref(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling`timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @return a reference to `timeout` + */ + unref(): this; /** * If true, the `Timeout` object will keep the Node.js event loop active. * @since v11.0.0 @@ -62,6 +116,25 @@ declare module 'timers' { [Symbol.toPrimitive](): number; } } + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay`will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearTimeout} + */ function setTimeout(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout; // util.promisify no rest args compability // tslint:disable-next-line void-return @@ -69,7 +142,27 @@ declare module 'timers' { namespace setTimeout { const __promisify__: typeof setTimeoutPromise; } + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. + */ function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be + * set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearInterval} + */ function setInterval(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer; // util.promisify no rest args compability // tslint:disable-next-line void-return @@ -77,7 +170,30 @@ declare module 'timers' { namespace setInterval { const __promisify__: typeof setIntervalPromise; } + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. + */ function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of the Node.js `Event Loop` + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearImmediate} + */ function setImmediate(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate; // util.promisify no rest args compability // tslint:disable-next-line void-return @@ -85,6 +201,11 @@ declare module 'timers' { namespace setImmediate { const __promisify__: typeof setImmediatePromise; } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by {@link setImmediate}. + */ function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; function queueMicrotask(callback: () => void): void; } diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts index c145068..299a355 100644 --- a/node_modules/@types/node/timers/promises.d.ts +++ b/node_modules/@types/node/timers/promises.d.ts @@ -1,6 +1,6 @@ /** * The `timers/promises` API provides an alternative set of timer functions - * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * that return `Promise` objects. The API is accessible via`require('node:timers/promises')`. * * ```js * import { @@ -44,6 +44,8 @@ declare module 'timers/promises' { function setImmediate(value?: T, options?: TimerOptions): Promise; /** * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. * * ```js * import { @@ -62,7 +64,6 @@ declare module 'timers/promises' { * @since v15.9.0 */ function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; - interface Scheduler { /** * ```js @@ -85,7 +86,6 @@ declare module 'timers/promises' { */ yield: () => Promise; } - const scheduler: Scheduler; } declare module 'node:timers/promises' { diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts index 2cbc716..13ee563 100644 --- a/node_modules/@types/node/tls.d.ts +++ b/node_modules/@types/node/tls.d.ts @@ -1,12 +1,12 @@ /** - * The `tls` module provides an implementation of the Transport Layer Security + * The `node:tls` module provides an implementation of the Transport Layer Security * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. * The module can be accessed using: * * ```js - * const tls = require('tls'); + * const tls = require('node:tls'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tls.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tls.js) */ declare module 'tls' { import { X509Certificate } from 'node:crypto'; @@ -41,21 +41,100 @@ declare module 'tls' { CN: string; } interface PeerCertificate { - subject: Certificate; - issuer: Certificate; - subjectaltname: string; - infoAccess: NodeJS.Dict; - modulus: string; - exponent: string; - valid_from: string; - valid_to: string; - fingerprint: string; - fingerprint256: string; - ext_key_usage: string[]; - serialNumber: string; + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve,if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; } interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ issuerCertificate: DetailedPeerCertificate; } interface CipherNameAndProtocol { @@ -133,7 +212,7 @@ declare module 'tls' { * * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. * - * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the * connection is open. * @since v0.11.4 */ @@ -180,13 +259,13 @@ declare module 'tls' { /** * Returns an object containing information on the negotiated cipher suite. * - * For example: + * For example, a TLSv1.2 protocol with AES256-SHA cipher: * * ```json * { - * "name": "AES128-SHA256", - * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", - * "version": "TLSv1.2" + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" * } * ``` * @@ -558,7 +637,8 @@ declare module 'tls' { * used. * @since v0.5.3 * @param hostname A SNI host name or wildcard (e.g. `'*'`) - * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. */ addContext(hostname: string, context: SecureContextOptions): void; /** @@ -689,12 +769,9 @@ declare module 'tls' { */ crl?: string | Buffer | Array | undefined; /** - * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use - * openssl dhparam to create the parameters. The key length must be - * greater than or equal to 1024 bits or else an error will be thrown. - * Although 1024 bits is permissible, use 2048 bits or larger for - * stronger security. If omitted or invalid, the parameters are - * silently discarded and DHE ciphers will not be available. + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. */ dhparam?: string | Buffer | undefined; /** @@ -836,14 +913,14 @@ declare module 'tls' { * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is * automatically set as a listener for the `'secureConnection'` event. * - * The `ticketKeys` options is automatically shared between `cluster` module + * The `ticketKeys` options is automatically shared between `node:cluster` module * workers. * * The following illustrates a simple echo server: * * ```js - * const tls = require('tls'); - * const fs = require('fs'); + * const tls = require('node:tls'); + * const fs = require('node:fs'); * * const options = { * key: fs.readFileSync('server-key.pem'), @@ -853,7 +930,7 @@ declare module 'tls' { * requestCert: true, * * // This is necessary only if the client uses a self-signed certificate. - * ca: [ fs.readFileSync('client-cert.pem') ] + * ca: [ fs.readFileSync('client-cert.pem') ], * }; * * const server = tls.createServer(options, (socket) => { @@ -888,8 +965,8 @@ declare module 'tls' { * * ```js * // Assumes an echo server that is listening on port 8000. - * const tls = require('tls'); - * const fs = require('fs'); + * const tls = require('node:tls'); + * const fs = require('node:fs'); * * const options = { * // Necessary only if the server requires client certificate authentication. @@ -965,12 +1042,19 @@ declare module 'tls' { * APIs that create secure contexts have no default value. * * The `tls.createSecureContext()` method creates a `SecureContext` object. It is - * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. * * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. * * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. * @since v0.11.13 */ function createSecureContext(options?: SecureContextOptions): SecureContext; @@ -1016,6 +1100,13 @@ declare module 'tls' { * are provided, the lowest minimum is used. */ let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the ciphers option of tls.createSecureContext(). + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of crypto.constants.defaultCoreCipherList, unless + * changed using CLI options using --tls-default-ciphers. + */ + let DEFAULT_CIPHERS: string; /** * An immutable array of strings representing the root certificates (in PEM * format) used for verifying peer certificates. This is the default value diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts index d47aa93..ca8baed 100644 --- a/node_modules/@types/node/trace_events.d.ts +++ b/node_modules/@types/node/trace_events.d.ts @@ -1,9 +1,9 @@ /** - * The `trace_events` module provides a mechanism to centralize tracing information - * generated by V8, Node.js core, and userspace code. + * The `node:trace_events` module provides a mechanism to centralize tracing + * information generated by V8, Node.js core, and userspace code. * * Tracing can be enabled with the `--trace-event-categories` command-line flag - * or by using the `trace_events` module. The `--trace-event-categories` flag + * or by using the `node:trace_events` module. The `--trace-event-categories` flag * accepts a list of comma-separated category names. * * The available categories are: @@ -13,9 +13,19 @@ * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool + * synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool + * asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. * * `node.environment`: Enables capture of Node.js Environment milestones. * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync + * directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async + * directory methods. * * `node.perf`: Enables capture of `Performance API` measurements. * * `node.perf.usertiming`: Enables capture of only Performance API User Timing * measures and marks. @@ -23,8 +33,9 @@ * measurements. * * `node.promises.rejections`: Enables capture of trace data tracking the number * of unhandled Promise rejections and handled-after-rejections. - * * `node.vm.script`: Enables capture of trace data for the `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. * * `v8`: The `V8` events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. * * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. * @@ -43,10 +54,10 @@ * node --trace-event-categories v8,node,node.async_hooks * ``` * - * Alternatively, trace events may be enabled using the `trace_events` module: + * Alternatively, trace events may be enabled using the `node:trace_events` module: * * ```js - * const trace_events = require('trace_events'); + * const trace_events = require('node:trace_events'); * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); * tracing.enable(); // Enable trace event capture for the 'node.perf' category * @@ -83,7 +94,7 @@ * * The features from this module are not available in `Worker` threads. * @experimental - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/trace_events.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/trace_events.js) */ declare module 'trace_events' { /** @@ -132,7 +143,7 @@ declare module 'trace_events' { * Creates and returns a `Tracing` object for the given set of `categories`. * * ```js - * const trace_events = require('trace_events'); + * const trace_events = require('node:trace_events'); * const categories = ['node.perf', 'node.async_hooks']; * const tracing = trace_events.createTracing({ categories }); * tracing.enable(); @@ -152,7 +163,7 @@ declare module 'trace_events' { * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. * * ```js - * const trace_events = require('trace_events'); + * const trace_events = require('node:trace_events'); * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); * const t3 = trace_events.createTracing({ categories: ['v8'] }); diff --git a/node_modules/@types/node/ts4.8/assert.d.ts b/node_modules/@types/node/ts4.8/assert.d.ts index e8595e6..e309252 100644 --- a/node_modules/@types/node/ts4.8/assert.d.ts +++ b/node_modules/@types/node/ts4.8/assert.d.ts @@ -1,7 +1,7 @@ /** - * The `assert` module provides a set of assertion functions for verifying + * The `node: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) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/assert.js) */ declare module 'assert' { /** @@ -12,14 +12,28 @@ declare module 'assert' { 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. + * Indicates the failure of an assertion. All errors thrown by the `node:assert`module will be instances of the `AssertionError` class. */ class AssertionError extends Error { + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ expected: unknown; + /** + * Set to the passed in operator value. + */ operator: string; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ code: 'ERR_ASSERTION'; constructor(options?: { /** If provided, the error message is set to this value. */ @@ -36,9 +50,10 @@ declare module 'assert' { }); } /** - * This feature is currently experimental and behavior might still change. + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. * @since v14.2.0, v12.19.0 - * @experimental + * @deprecated Deprecated */ class CallTracker { /** @@ -47,7 +62,7 @@ declare module 'assert' { * error. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); @@ -78,12 +93,11 @@ declare module 'assert' { * callsfunc(1, 2, 3); * * assert.deepStrictEqual(tracker.getCalls(callsfunc), - * [{ thisArg: this, arguments: [1, 2, 3 ] }]); + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); * ``` - * * @since v18.8.0, v16.18.0 - * @params fn - * @returns An Array with the calls to a tracked function. + * @param fn + * @return An Array with all the calls to a tracked function. */ getCalls(fn: Function): CallTrackerCall[]; /** @@ -91,21 +105,19 @@ declare module 'assert' { * the functions that have not been called the expected number of times. * * ```js - * import assert from 'assert'; + * import assert from 'node: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(); + * console.log(tracker.report()); * // [ * // { * // message: 'Expected the func function to be executed 2 time(s) but was @@ -118,7 +130,7 @@ declare module 'assert' { * // ] * ``` * @since v14.2.0, v12.19.0 - * @return of objects containing information about the wrapper functions returned by `calls`. + * @return An Array of objects containing information about the wrapper functions returned by `calls`. */ report(): CallTrackerReportInformation[]; /** @@ -136,12 +148,11 @@ declare module 'assert' { * * callsfunc(); * // Tracker was called once - * tracker.getCalls(callsfunc).length === 1; + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); * * tracker.reset(callsfunc); - * tracker.getCalls(callsfunc).length === 0; + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); * ``` - * * @since v18.8.0, v16.18.0 * @param fn a tracked function to reset. */ @@ -151,7 +162,7 @@ declare module 'assert' { * have not been called the expected number of times. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); @@ -193,7 +204,7 @@ declare module 'assert' { * it will be thrown instead of the `AssertionError`. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.fail(); * // AssertionError [ERR_ASSERTION]: Failed @@ -231,7 +242,7 @@ declare module 'assert' { * thrown in a file! See below for further details. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.ok(true); * // OK @@ -266,7 +277,7 @@ declare module 'assert' { * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * // Using `assert()` works the same: * assert(0); @@ -291,7 +302,7 @@ declare module 'assert' { * and treated as being identical if both sides are `NaN`. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * assert.equal(1, 1); * // OK, 1 == 1 @@ -324,7 +335,7 @@ declare module 'assert' { * specially handled and treated as being identical if both sides are `NaN`. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * assert.notEqual(1, 2); * // OK @@ -371,24 +382,24 @@ declare module 'assert' { * Tests for any deep inequality. Opposite of {@link deepEqual}. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * const obj1 = { * a: { - * b: 1 - * } + * b: 1, + * }, * }; * const obj2 = { * a: { - * b: 2 - * } + * b: 2, + * }, * }; * const obj3 = { * a: { - * b: 1 - * } + * b: 1, + * }, * }; - * const obj4 = Object.create(obj1); + * const obj4 = { __proto__: obj1 }; * * assert.notDeepEqual(obj1, obj1); * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } @@ -414,7 +425,7 @@ declare module 'assert' { * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.strictEqual(1, 2); * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: @@ -452,7 +463,7 @@ declare module 'assert' { * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.notStrictEqual(1, 2); * // OK @@ -483,7 +494,7 @@ declare module 'assert' { * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); * // OK @@ -514,14 +525,14 @@ declare module 'assert' { * Custom validation object/error instance: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * const err = new TypeError('Wrong value'); * err.code = 404; * err.foo = 'bar'; * err.info = { * nested: true, - * baz: 'text' + * baz: 'text', * }; * err.reg = /abc/i; * @@ -534,16 +545,16 @@ declare module 'assert' { * message: 'Wrong value', * info: { * nested: true, - * baz: 'text' - * } + * 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( + * assert.throws( * () => { * throw err; * }, @@ -557,17 +568,17 @@ declare module 'assert' { * info: { * nested: true, * // It is not possible to use regular expressions for nested properties! - * baz: 'text' + * 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 - * } + * reg: /abc/i, + * }, * ); * * // Fails due to the different `message` and `name` properties: - * throws( + * assert.throws( * () => { * const otherErr = new Error('Not found'); * // Copy all enumerable properties from `err` to `otherErr`. @@ -578,20 +589,20 @@ declare module 'assert' { * }, * // The error's `message` and `name` properties will also be checked when using * // an error as validation object. - * err + * err, * ); * ``` * * Validate instanceof using constructor: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.throws( * () => { * throw new Error('Wrong value'); * }, - * Error + * Error, * ); * ``` * @@ -601,13 +612,13 @@ declare module 'assert' { * therefore also include the error name. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.throws( * () => { * throw new Error('Wrong value'); * }, - * /^Error: Wrong value$/ + * /^Error: Wrong value$/, * ); * ``` * @@ -617,7 +628,7 @@ declare module 'assert' { * It will otherwise fail with an `AssertionError`. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.throws( * () => { @@ -633,7 +644,7 @@ declare module 'assert' { * // possible. * return true; * }, - * 'unexpected error' + * 'unexpected error', * ); * ``` * @@ -643,7 +654,7 @@ declare module 'assert' { * a string as the second argument gets considered: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * function throwingFirst() { * throw new Error('First'); @@ -699,20 +710,20 @@ declare module 'assert' { * 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 + * [`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'; + * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, - * SyntaxError + * SyntaxError, * ); * ``` * @@ -720,27 +731,27 @@ declare module 'assert' { * 'Got unwanted exception...': * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, - * TypeError + * 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'; + * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, * /Wrong value/, - * 'Whoops' + * 'Whoops', * ); * // Throws: AssertionError: Got unwanted exception: Whoops * ``` @@ -754,7 +765,7 @@ declare module 'assert' { * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.ifError(null); * // OK @@ -800,7 +811,7 @@ declare module 'assert' { * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * await assert.rejects( * async () => { @@ -808,13 +819,13 @@ declare module 'assert' { * }, * { * name: 'TypeError', - * message: 'Wrong value' - * } + * message: 'Wrong value', + * }, * ); * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * await assert.rejects( * async () => { @@ -824,16 +835,16 @@ declare module 'assert' { * assert.strictEqual(err.name, 'TypeError'); * assert.strictEqual(err.message, 'Wrong value'); * return true; - * } + * }, * ); * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.rejects( * Promise.reject(new Error('Wrong value')), - * Error + * Error, * ).then(() => { * // ... * }); @@ -863,24 +874,24 @@ declare module 'assert' { * 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 + * [`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'; + * import assert from 'node:assert/strict'; * * await assert.doesNotReject( * async () => { * throw new TypeError('Wrong value'); * }, - * SyntaxError + * SyntaxError, * ); * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) * .then(() => { @@ -895,7 +906,7 @@ declare module 'assert' { * Expects the `string` input to match the regular expression. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.match('I will fail', /pass/); * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... @@ -918,7 +929,7 @@ declare module 'assert' { * Expects the `string` input not to match the regular expression. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotMatch('I will fail', /fail/); * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... diff --git a/node_modules/@types/node/ts4.8/async_hooks.d.ts b/node_modules/@types/node/ts4.8/async_hooks.d.ts index 0bf4739..e994f02 100644 --- a/node_modules/@types/node/ts4.8/async_hooks.d.ts +++ b/node_modules/@types/node/ts4.8/async_hooks.d.ts @@ -1,17 +1,24 @@ /** - * The `async_hooks` module provides an API to track asynchronous resources. It - * can be accessed using: + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * `AsyncLocalStorage` tracks async context + * * `process.getActiveResourcesInfo()` tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: * * ```js - * import async_hooks from 'async_hooks'; + * import async_hooks from 'node:async_hooks'; * ``` * @experimental - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/async_hooks.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js) */ declare module 'async_hooks' { /** * ```js - * import { executionAsyncId } from 'async_hooks'; + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; * * console.log(executionAsyncId()); // 1 - bootstrap * fs.open(path, 'r', (err, fd) => { @@ -51,8 +58,8 @@ declare module 'async_hooks' { * but having an object representing the top-level can be helpful. * * ```js - * import { open } from 'fs'; - * import { executionAsyncId, executionAsyncResource } from 'async_hooks'; + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; * * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} * open(new URL(import.meta.url), 'r', (err, fd) => { @@ -64,11 +71,11 @@ declare module 'async_hooks' { * use of a tracking `Map` to store the metadata: * * ```js - * import { createServer } from 'http'; + * import { createServer } from 'node:http'; * import { * executionAsyncId, * executionAsyncResource, - * createHook + * createHook, * } from 'async_hooks'; * const sym = Symbol('state'); // Private symbol to avoid pollution * @@ -78,7 +85,7 @@ declare module 'async_hooks' { * if (cr) { * resource[sym] = cr[sym]; * } - * } + * }, * }).enable(); * * const server = createServer((req, res) => { @@ -167,11 +174,11 @@ declare module 'async_hooks' { * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. * * ```js - * import { createHook } from 'async_hooks'; + * import { createHook } from 'node:async_hooks'; * * const asyncHook = createHook({ * init(asyncId, type, triggerAsyncId, resource) { }, - * destroy(asyncId) { } + * destroy(asyncId) { }, * }); * ``` * @@ -223,13 +230,13 @@ declare module 'async_hooks' { * The following is an overview of the `AsyncResource` API. * * ```js - * import { AsyncResource, executionAsyncId } from 'async_hooks'; + * import { AsyncResource, executionAsyncId } from 'node: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 } + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, * ); * * // Run a function in the execution context of the resource. This will @@ -263,33 +270,17 @@ declare module 'async_hooks' { constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); /** * Binds the given function to the current execution context. - * - * The returned function will have an `asyncResource` property referencing - * the `AsyncResource` to which the function is bound. * @since v14.8.0, v12.19.0 * @param fn The function to bind to the current execution context. * @param type An optional name to associate with the underlying `AsyncResource`. */ - static bind any, ThisArg>( - fn: Func, - type?: string, - thisArg?: ThisArg - ): Func & { - asyncResource: AsyncResource; - }; + static bind any, ThisArg>(fn: Func, type?: string, thisArg?: ThisArg): Func; /** * Binds the given function to execute to this `AsyncResource`'s scope. - * - * The returned function will have an `asyncResource` property referencing - * the `AsyncResource` to which the function is bound. * @since v14.8.0, v12.19.0 * @param fn The function to bind to the current `AsyncResource`. */ - bind any>( - fn: Func - ): Func & { - asyncResource: AsyncResource; - }; + bind any>(fn: Func): Func; /** * Call the provided function with the provided arguments in the execution context * of the async resource. This will establish the context, trigger the AsyncHooks @@ -322,17 +313,17 @@ declare module 'async_hooks' { /** * 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. + * While you can create your own implementation on top of the `node: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'; + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; * * const asyncLocalStorage = new AsyncLocalStorage(); * @@ -368,6 +359,44 @@ declare module 'async_hooks' { * @since v13.10.0, v12.17.0 */ class AsyncLocalStorage { + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @experimental + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @experimental + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; /** * Disables the instance of `AsyncLocalStorage`. All subsequent calls * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. diff --git a/node_modules/@types/node/ts4.8/buffer.d.ts b/node_modules/@types/node/ts4.8/buffer.d.ts index ea859cd..86694b0 100644 --- a/node_modules/@types/node/ts4.8/buffer.d.ts +++ b/node_modules/@types/node/ts4.8/buffer.d.ts @@ -10,7 +10,7 @@ * recommended to explicitly reference it via an import or require statement. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Creates a zero-filled Buffer of length 10. * const buf1 = Buffer.alloc(10); @@ -41,11 +41,29 @@ * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. * const buf7 = Buffer.from('tést', 'latin1'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/buffer.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/buffer.js) */ declare module 'buffer' { import { BinaryLike } from 'node:crypto'; import { ReadableStream as WebReadableStream } from 'node:stream/web'; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; export const INSPECT_MAX_BYTES: number; export const kMaxLength: number; export const kStringMaxLength: number; @@ -67,7 +85,7 @@ declare module 'buffer' { * sequence cannot be adequately represented in the target encoding. For instance: * * ```js - * import { Buffer, transcode } from 'buffer'; + * import { Buffer, transcode } from 'node:buffer'; * * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); * console.log(newBuf.toString('ascii')); @@ -158,23 +176,62 @@ declare module 'buffer' { */ text(): Promise; /** - * Returns a new (WHATWG) `ReadableStream` that allows the content of the `Blob` to be read. + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. * @since v16.7.0 */ stream(): WebReadableStream; } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `require('node:os').EOL`. + */ + endings?: 'native' | 'transparent'; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } export import atob = globalThis.atob; export import btoa = globalThis.btoa; - import { Blob as NodeBlob } from 'buffer'; // This conditional type will be the existing global Blob in a browser, or // the copy below in a Node environment. - type __Blob = typeof globalThis extends { onmessage: any, Blob: any } - ? {} : NodeBlob; - + type __Blob = typeof globalThis extends { onmessage: any; Blob: infer T } ? T : NodeBlob; global { + namespace NodeJS { + export { BufferEncoding }; + } // Buffer class - type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; + type BufferEncoding = + | 'ascii' + | 'utf8' + | 'utf-8' + | 'utf16le' + | 'ucs2' + | 'ucs-2' + | 'base64' + | 'base64url' + | 'latin1' + | 'binary' + | 'hex'; type WithImplicitCoercion = | T | { @@ -236,19 +293,27 @@ declare module 'buffer' { * Array entries outside that range will be truncated to fit into it. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); * ``` * + * If `array` is an `Array`\-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. + * * A `TypeError` will be thrown if `array` is not an `Array` or another type * appropriate for `Buffer.from()` variants. * * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. * @since v5.10.0 */ - from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; /** * Creates a new Buffer using the passed {data} * @param data data to create a new Buffer @@ -266,7 +331,7 @@ declare module 'buffer' { | { [Symbol.toPrimitive](hint: 'string'): string; }, - encoding?: BufferEncoding + encoding?: BufferEncoding, ): Buffer; /** * Creates a new Buffer using the passed {data} @@ -277,7 +342,7 @@ declare module 'buffer' { * Returns `true` if `obj` is a `Buffer`, `false` otherwise. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * Buffer.isBuffer(Buffer.alloc(10)); // true * Buffer.isBuffer(Buffer.from('foo')); // true @@ -293,7 +358,7 @@ declare module 'buffer' { * or `false` otherwise. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * console.log(Buffer.isEncoding('utf8')); * // Prints: true @@ -322,7 +387,7 @@ declare module 'buffer' { * string. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const str = '\u00bd + \u00bc = \u00be'; * @@ -340,7 +405,10 @@ declare module 'buffer' { * @param [encoding='utf8'] If `string` is a string, this is its encoding. * @return The number of bytes contained within `string`. */ - byteLength(string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; /** * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. * @@ -354,7 +422,7 @@ declare module 'buffer' { * truncated to `totalLength`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create a single `Buffer` from a list of three `Buffer` instances. * @@ -380,11 +448,28 @@ declare module 'buffer' { * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. */ concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=': 0'] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; /** * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('1234'); * const buf2 = Buffer.from('0123'); @@ -402,7 +487,7 @@ declare module 'buffer' { * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(5); * @@ -410,12 +495,12 @@ declare module 'buffer' { * // Prints: * ``` * - * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. * * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(5, 'a'); * @@ -427,7 +512,7 @@ declare module 'buffer' { * initialized by calling `buf.fill(fill, encoding)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); * @@ -447,13 +532,13 @@ declare module 'buffer' { */ alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; /** - * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. * * The underlying memory for `Buffer` instances created in this way is _not_ * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(10); * @@ -469,9 +554,8 @@ declare module 'buffer' { * A `TypeError` will be thrown if `size` is not a number. * * The `Buffer` module pre-allocates an internal `Buffer` instance of - * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`,`Buffer.from(array)`, `Buffer.concat()`, and the - * deprecated`new Buffer(size)` constructor only when `size` is less than or equal - * to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than or equal to`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). * * Use of this pre-allocated internal memory pool is a key difference between * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. @@ -484,15 +568,15 @@ declare module 'buffer' { */ allocUnsafe(size: number): Buffer; /** - * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. A zero-length `Buffer` is created - * if `size` is 0. + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. * * The underlying memory for `Buffer` instances created in this way is _not_ * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize * such `Buffer` instances with zeroes. * * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, - * allocations under 4 KB are sliced from a single pre-allocated `Buffer`. This + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This * allows applications to avoid the garbage collection overhead of creating many * individually allocated `Buffer` instances. This approach improves both * performance and memory usage by eliminating the need to track and clean up as @@ -504,7 +588,7 @@ declare module 'buffer' { * then copying out the relevant bits. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Need to keep around a few small chunks of memory. * const store = []; @@ -542,7 +626,7 @@ declare module 'buffer' { * written. However, partially encoded characters will not be written. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(256); * @@ -578,7 +662,7 @@ declare module 'buffer' { * as {@link constants.MAX_STRING_LENGTH}. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.allocUnsafe(26); * @@ -615,7 +699,7 @@ declare module 'buffer' { * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); * const json = JSON.stringify(buf); @@ -642,7 +726,7 @@ declare module 'buffer' { * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('ABC'); * const buf2 = Buffer.from('414243', 'hex'); @@ -666,7 +750,7 @@ declare module 'buffer' { * * `-1` is returned if `target` should come _after_`buf` when sorted. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('ABC'); * const buf2 = Buffer.from('BCD'); @@ -690,7 +774,7 @@ declare module 'buffer' { * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); @@ -711,7 +795,13 @@ declare module 'buffer' { * @param [sourceStart=0] The offset within `buf` at which to begin comparison. * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). */ - compare(target: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1; + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; /** * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. * @@ -720,7 +810,7 @@ declare module 'buffer' { * different function arguments. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create two `Buffer` instances. * const buf1 = Buffer.allocUnsafe(26); @@ -741,7 +831,7 @@ declare module 'buffer' { * ``` * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create a `Buffer` and copy data from one region to an overlapping region * // within the same `Buffer`. @@ -774,7 +864,7 @@ declare module 'buffer' { * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -812,7 +902,7 @@ declare module 'buffer' { * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte * // from the original `Buffer`. @@ -839,7 +929,7 @@ declare module 'buffer' { * end of `buf` rather than the beginning. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -866,7 +956,7 @@ declare module 'buffer' { * `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -887,7 +977,7 @@ declare module 'buffer' { * `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -908,7 +998,7 @@ declare module 'buffer' { * This function is also available under the `writeBigUint64BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -932,7 +1022,7 @@ declare module 'buffer' { * Writes `value` to `buf` at the specified `offset` as little-endian * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -961,7 +1051,7 @@ declare module 'buffer' { * This function is also available under the `writeUintLE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -989,7 +1079,7 @@ declare module 'buffer' { * This function is also available under the `writeUintBE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -1015,7 +1105,7 @@ declare module 'buffer' { * when `value` is anything other than a signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -1036,7 +1126,7 @@ declare module 'buffer' { * signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -1058,7 +1148,7 @@ declare module 'buffer' { * This function is also available under the `readBigUint64BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); * @@ -1080,7 +1170,7 @@ declare module 'buffer' { * This function is also available under the `readBigUint64LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); * @@ -1121,7 +1211,7 @@ declare module 'buffer' { * This function is also available under the `readUintLE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1145,7 +1235,7 @@ declare module 'buffer' { * This function is also available under the `readUintBE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1169,7 +1259,7 @@ declare module 'buffer' { * supporting up to 48 bits of accuracy. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1186,7 +1276,7 @@ declare module 'buffer' { * supporting up to 48 bits of accuracy. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1208,7 +1298,7 @@ declare module 'buffer' { * This function is also available under the `readUint8` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, -2]); * @@ -1234,7 +1324,7 @@ declare module 'buffer' { * This function is also available under the `readUint16LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56]); * @@ -1260,7 +1350,7 @@ declare module 'buffer' { * This function is also available under the `readUint16BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56]); * @@ -1284,7 +1374,7 @@ declare module 'buffer' { * This function is also available under the `readUint32LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); * @@ -1308,7 +1398,7 @@ declare module 'buffer' { * This function is also available under the `readUint32BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); * @@ -1330,7 +1420,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([-1, 5]); * @@ -1351,7 +1441,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 5]); * @@ -1370,7 +1460,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 5]); * @@ -1387,7 +1477,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 0, 0, 5]); * @@ -1406,7 +1496,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 0, 0, 5]); * @@ -1421,7 +1511,7 @@ declare module 'buffer' { * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4]); * @@ -1438,7 +1528,7 @@ declare module 'buffer' { * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4]); * @@ -1453,7 +1543,7 @@ declare module 'buffer' { * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); * @@ -1470,7 +1560,7 @@ declare module 'buffer' { * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); * @@ -1487,7 +1577,7 @@ declare module 'buffer' { * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); * @@ -1509,7 +1599,7 @@ declare module 'buffer' { * between UTF-16 little-endian and UTF-16 big-endian: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); * buf.swap16(); // Convert to big-endian UTF-16 text. @@ -1523,7 +1613,7 @@ declare module 'buffer' { * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); * @@ -1549,7 +1639,7 @@ declare module 'buffer' { * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); * @@ -1578,7 +1668,7 @@ declare module 'buffer' { * This function is also available under the `writeUint8` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1608,7 +1698,7 @@ declare module 'buffer' { * This function is also available under the `writeUint16LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1636,7 +1726,7 @@ declare module 'buffer' { * This function is also available under the `writeUint16BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1664,7 +1754,7 @@ declare module 'buffer' { * This function is also available under the `writeUint32LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1691,7 +1781,7 @@ declare module 'buffer' { * This function is also available under the `writeUint32BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1719,7 +1809,7 @@ declare module 'buffer' { * `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(2); * @@ -1742,7 +1832,7 @@ declare module 'buffer' { * The `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(2); * @@ -1764,7 +1854,7 @@ declare module 'buffer' { * The `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(2); * @@ -1786,7 +1876,7 @@ declare module 'buffer' { * The `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1808,7 +1898,7 @@ declare module 'buffer' { * The `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1828,7 +1918,7 @@ declare module 'buffer' { * undefined when `value` is anything other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1848,7 +1938,7 @@ declare module 'buffer' { * undefined when `value` is anything other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1868,7 +1958,7 @@ declare module 'buffer' { * other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -1888,7 +1978,7 @@ declare module 'buffer' { * other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -1908,7 +1998,7 @@ declare module 'buffer' { * the entire `buf` will be filled: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Fill a `Buffer` with the ASCII character 'h'. * @@ -1916,6 +2006,12 @@ declare module 'buffer' { * * console.log(b.toString()); * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: * ``` * * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or @@ -1926,7 +2022,7 @@ declare module 'buffer' { * then only the bytes of that character that fit into `buf` are written: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Fill a `Buffer` with character that takes up two bytes in UTF-8. * @@ -1938,7 +2034,7 @@ declare module 'buffer' { * fill data remains, an exception is thrown: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(5); * @@ -1950,7 +2046,7 @@ declare module 'buffer' { * // Throws an exception. * ``` * @since v0.5.0 - * @param value The value with which to fill `buf`. + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. * @param [offset=0] Number of bytes to skip before starting to fill `buf`. * @param [end=buf.length] Where to stop filling `buf` (not inclusive). * @param [encoding='utf8'] The encoding for `value` if `value` is a string. @@ -1967,7 +2063,7 @@ declare module 'buffer' { * value between `0` and `255`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('this is a buffer'); * @@ -2000,7 +2096,7 @@ declare module 'buffer' { * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const b = Buffer.from('abcdef'); * @@ -2031,7 +2127,7 @@ declare module 'buffer' { * rather than the first occurrence. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('this buffer is a buffer'); * @@ -2066,7 +2162,7 @@ declare module 'buffer' { * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const b = Buffer.from('abcdef'); * @@ -2099,7 +2195,7 @@ declare module 'buffer' { * of `buf`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Log the entire contents of a `Buffer`. * @@ -2123,7 +2219,7 @@ declare module 'buffer' { * Equivalent to `buf.indexOf() !== -1`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('this is a buffer'); * @@ -2153,7 +2249,7 @@ declare module 'buffer' { * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -2176,7 +2272,7 @@ declare module 'buffer' { * called automatically when a `Buffer` is used in a `for..of` statement. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -2219,7 +2315,7 @@ declare module 'buffer' { * **For code running using Node.js APIs, converting between base64-encoded strings** * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** * @since v15.13.0, v14.17.0 - * @deprecated Use `Buffer.from(data, 'base64')` instead. + * @legacy Use `Buffer.from(data, 'base64')` instead. * @param data The Base64-encoded input string. */ function atob(data: string): string; @@ -2235,11 +2331,10 @@ declare module 'buffer' { * **For code running using Node.js APIs, converting between base64-encoded strings** * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** * @since v15.13.0, v14.17.0 - * @deprecated Use `buf.toString('base64')` instead. + * @legacy Use `buf.toString('base64')` instead. * @param data An ASCII (Latin1) string. */ function btoa(data: string): string; - interface Blob extends __Blob {} /** * `Blob` class is a global reference for `require('node:buffer').Blob` diff --git a/node_modules/@types/node/ts4.8/child_process.d.ts b/node_modules/@types/node/ts4.8/child_process.d.ts index c537d6d..771d39d 100644 --- a/node_modules/@types/node/ts4.8/child_process.d.ts +++ b/node_modules/@types/node/ts4.8/child_process.d.ts @@ -1,10 +1,10 @@ /** - * The `child_process` module provides the ability to spawn subprocesses in + * The `node:child_process` module provides the ability to spawn subprocesses in * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability * is primarily provided by the {@link spawn} function: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const ls = spawn('ls', ['-lh', '/usr']); * * ls.stdout.on('data', (data) => { @@ -44,8 +44,8 @@ * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks * the event loop until the spawned process either exits or is terminated. * - * For convenience, the `child_process` module provides a handful of synchronous - * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on * top of {@link spawn} or {@link spawnSync}. * * * {@link exec}: spawns a shell and runs a command within that @@ -63,7 +63,7 @@ * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, * the synchronous methods can have significant impact on performance due to * stalling the event loop while spawned processes complete. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/child_process.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/child_process.js) */ declare module 'child_process' { import { ObjectEncodingOptions } from 'node:fs'; @@ -94,8 +94,7 @@ declare module 'child_process' { * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will * refer to the same value. * - * The `subprocess.stdin` property can be `undefined` if the child process could - * not be successfully spawned. + * The `subprocess.stdin` property can be `null` or `undefined`if the child process could not be successfully spawned. * @since v0.1.90 */ stdin: Writable | null; @@ -109,7 +108,7 @@ declare module 'child_process' { * refer to the same value. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn('ls'); * @@ -118,8 +117,7 @@ declare module 'child_process' { * }); * ``` * - * The `subprocess.stdout` property can be `null` if the child process could - * not be successfully spawned. + * The `subprocess.stdout` property can be `null` or `undefined`if the child process could not be successfully spawned. * @since v0.1.90 */ stdout: Readable | null; @@ -132,14 +130,13 @@ declare module 'child_process' { * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will * refer to the same value. * - * The `subprocess.stderr` property can be `null` if the child process could - * not be successfully spawned. + * The `subprocess.stderr` property can be `null` or `undefined`if the child process could not be successfully spawned. * @since v0.1.90 */ stderr: Readable | null; /** * The `subprocess.channel` property is a reference to the child's IPC channel. If - * no IPC channel currently exists, this property is `undefined`. + * no IPC channel exists, this property is `undefined`. * @since v7.1.0 */ readonly channel?: Pipe | null | undefined; @@ -154,16 +151,16 @@ declare module 'child_process' { * in the array are `null`. * * ```js - * const assert = require('assert'); - * const fs = require('fs'); - * const child_process = require('child_process'); + * const assert = require('node:assert'); + * const fs = require('node:fs'); + * const child_process = require('node:child_process'); * * const subprocess = child_process.spawn('ls', { * stdio: [ * 0, // Use parent's stdin for child. * 'pipe', // Pipe child's stdout to parent. * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. - * ] + * ], * }); * * assert.strictEqual(subprocess.stdio[0], null); @@ -204,7 +201,7 @@ declare module 'child_process' { * emitted. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const grep = spawn('grep', ['ssh']); * * console.log(`Spawned child pid: ${grep.pid}`); @@ -251,7 +248,7 @@ declare module 'child_process' { * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const grep = spawn('grep', ['ssh']); * * grep.on('close', (code, signal) => { @@ -284,7 +281,7 @@ declare module 'child_process' { * * ```js * 'use strict'; - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn( * 'sh', @@ -294,8 +291,8 @@ declare module 'child_process' { * console.log(process.pid, 'is alive') * }, 500);"`, * ], { - * stdio: ['inherit', 'inherit', 'inherit'] - * } + * stdio: ['inherit', 'inherit', 'inherit'], + * }, * ); * * setTimeout(() => { @@ -317,7 +314,7 @@ declare module 'child_process' { * For example, in the parent script: * * ```js - * const cp = require('child_process'); + * const cp = require('node:child_process'); * const n = cp.fork(`${__dirname}/sub.js`); * * n.on('message', (m) => { @@ -371,10 +368,10 @@ declare module 'child_process' { * a TCP server object to the child process as illustrated in the example below: * * ```js - * const subprocess = require('child_process').fork('subprocess.js'); + * const subprocess = require('node:child_process').fork('subprocess.js'); * * // Open up the server object and send the handle. - * const server = require('net').createServer(); + * const server = require('node:net').createServer(); * server.on('connection', (socket) => { * socket.end('handled by parent'); * }); @@ -398,10 +395,9 @@ declare module 'child_process' { * Once the server is now shared between the parent and child, some connections * can be handled by the parent and some by the child. * - * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on - * a `'message'` event instead of `'connection'` and using `server.bind()` instead - * of `server.listen()`. This is, however, currently only supported on Unix - * platforms. + * While the example above uses a server created using the `node:net` module,`node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using`server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. * * #### Example: sending a socket object * @@ -410,13 +406,13 @@ declare module 'child_process' { * handle connections with "normal" or "special" priority: * * ```js - * const { fork } = require('child_process'); + * const { fork } = require('node:child_process'); * const normal = fork('subprocess.js', ['normal']); * const special = fork('subprocess.js', ['special']); * * // Open up the server and send sockets to child. Use pauseOnConnect to prevent * // the sockets from being read before they are sent to the child process. - * const server = require('net').createServer({ pauseOnConnect: true }); + * const server = require('node:net').createServer({ pauseOnConnect: true }); * server.on('connection', (socket) => { * * // If this is special priority... @@ -482,11 +478,11 @@ declare module 'child_process' { * the child and the parent. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn(process.argv[0], ['child_program.js'], { * detached: true, - * stdio: 'ignore' + * stdio: 'ignore', * }); * * subprocess.unref(); @@ -500,11 +496,11 @@ declare module 'child_process' { * to wait for the child to exit before exiting itself. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn(process.argv[0], ['child_program.js'], { * detached: true, - * stdio: 'ignore' + * stdio: 'ignore', * }); * * subprocess.unref(); @@ -634,6 +630,15 @@ declare module 'child_process' { } interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ stdio?: StdioOptions | undefined; shell?: boolean | string | undefined; windowsVerbatimArguments?: boolean | undefined; @@ -663,7 +668,7 @@ declare module 'child_process' { * ```js * const defaults = { * cwd: undefined, - * env: process.env + * env: process.env, * }; * ``` * @@ -682,7 +687,7 @@ declare module 'child_process' { * exit code: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const ls = spawn('ls', ['-lh', '/usr']); * * ls.stdout.on('data', (data) => { @@ -701,7 +706,7 @@ declare module 'child_process' { * Example: A very elaborate way to run `ps ax | grep ssh` * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const ps = spawn('ps', ['ax']); * const grep = spawn('grep', ['ssh']); * @@ -738,7 +743,7 @@ declare module 'child_process' { * Example of checking for failed `spawn`: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const subprocess = spawn('bad_command'); * * subprocess.on('error', (err) => { @@ -749,14 +754,14 @@ declare module 'child_process' { * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process * title while others (Windows, SunOS) will use `command`. * - * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, - * retrieve it with the`process.argv0` property instead. + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent. Retrieve + * it with the`process.argv0` property instead. * * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const grep = spawn('grep', ['ssh'], { signal }); @@ -815,7 +820,7 @@ declare module 'child_process' { * need to be dealt with accordingly: * * ```js - * const { exec } = require('child_process'); + * const { exec } = require('node:child_process'); * * exec('"/path/to/test file/test.sh" arg1 arg2'); * // Double quotes are used so that the space in the path is not interpreted as @@ -841,7 +846,7 @@ declare module 'child_process' { * encoding, `Buffer` objects will be passed to the callback instead. * * ```js - * const { exec } = require('child_process'); + * const { exec } = require('node:child_process'); * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { * if (error) { * console.error(`exec error: ${error}`); @@ -866,8 +871,8 @@ declare module 'child_process' { * callback, but with two additional properties `stdout` and `stderr`. * * ```js - * const util = require('util'); - * const exec = util.promisify(require('child_process').exec); + * const util = require('node:util'); + * const exec = util.promisify(require('node:child_process').exec); * * async function lsExample() { * const { stdout, stderr } = await exec('ls'); @@ -881,11 +886,11 @@ declare module 'child_process' { * the error passed to the callback will be an `AbortError`: * * ```js - * const { exec } = require('child_process'); + * const { exec } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = exec('grep ssh', { signal }, (error) => { - * console.log(error); // an AbortError + * console.error(error); // an AbortError * }); * controller.abort(); * ``` @@ -984,7 +989,10 @@ declare module 'child_process' { interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { encoding: BufferEncoding; } - type ExecFileException = ExecException & NodeJS.ErrnoException; + type ExecFileException = + & Omit + & Omit + & { code?: string | number | undefined | null }; /** * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified * executable `file` is spawned directly as a new process making it slightly more @@ -995,7 +1003,7 @@ declare module 'child_process' { * supported. * * ```js - * const { execFile } = require('child_process'); + * const { execFile } = require('node:child_process'); * const child = execFile('node', ['--version'], (error, stdout, stderr) => { * if (error) { * throw error; @@ -1018,8 +1026,8 @@ declare module 'child_process' { * callback, but with two additional properties `stdout` and `stderr`. * * ```js - * const util = require('util'); - * const execFile = util.promisify(require('child_process').execFile); + * const util = require('node:util'); + * const execFile = util.promisify(require('node:child_process').execFile); * async function getVersion() { * const { stdout } = await execFile('node', ['--version']); * console.log(stdout); @@ -1035,11 +1043,11 @@ declare module 'child_process' { * the error passed to the callback will be an `AbortError`: * * ```js - * const { execFile } = require('child_process'); + * const { execFile } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = execFile('node', ['--version'], { signal }, (error) => { - * console.log(error); // an AbortError + * console.error(error); // an AbortError * }); * controller.abort(); * ``` @@ -1192,6 +1200,15 @@ declare module 'child_process' { execPath?: string | undefined; execArgv?: string[] | undefined; silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ stdio?: StdioOptions | undefined; detached?: boolean | undefined; windowsVerbatimArguments?: boolean | undefined; @@ -1231,7 +1248,7 @@ declare module 'child_process' { * console.log(`Hello from ${process.argv[2]}!`); * }, 1_000); * } else { - * const { fork } = require('child_process'); + * const { fork } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = fork(__filename, ['child'], { signal }); @@ -1292,6 +1309,15 @@ declare module 'child_process' { function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; interface CommonExecOptions extends CommonOptions { input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ stdio?: StdioOptions | undefined; killSignal?: NodeJS.Signals | number | undefined; maxBuffer?: number | undefined; diff --git a/node_modules/@types/node/ts4.8/cluster.d.ts b/node_modules/@types/node/ts4.8/cluster.d.ts index 37dbc57..4fa9aef 100644 --- a/node_modules/@types/node/ts4.8/cluster.d.ts +++ b/node_modules/@types/node/ts4.8/cluster.d.ts @@ -8,12 +8,12 @@ * server ports. * * ```js - * import cluster from 'cluster'; - * import http from 'http'; - * import { cpus } from 'os'; - * import process from 'process'; + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; * - * const numCPUs = cpus().length; + * const numCPUs = availableParallelism(); * * if (cluster.isPrimary) { * console.log(`Primary ${process.pid} is running`); @@ -50,12 +50,13 @@ * ``` * * On Windows, it is not yet possible to set up a named pipe server in a worker. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/cluster.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/cluster.js) */ declare module 'cluster' { import * as child from 'node:child_process'; import EventEmitter = require('node:events'); import * as net from 'node:net'; + type SerializationType = 'json' | 'advanced'; export interface ClusterSettings { execArgv?: string[] | undefined; // default: process.execArgv exec?: string | undefined; @@ -65,6 +66,9 @@ declare module 'cluster' { uid?: number | undefined; gid?: number | undefined; inspectPort?: number | (() => number) | undefined; + serialization?: SerializationType | undefined; + cwd?: string | undefined; + windowsHide?: boolean | undefined; } export interface Address { address: string; @@ -183,7 +187,7 @@ declare module 'cluster' { * }); * * } else if (cluster.isWorker) { - * const net = require('net'); + * const net = require('node:net'); * const server = net.createServer((socket) => { * // Connections never end * }); @@ -213,12 +217,12 @@ declare module 'cluster' { * because of exiting or being signaled). Otherwise, it returns `false`. * * ```js - * import cluster from 'cluster'; - * import http from 'http'; - * import { cpus } from 'os'; - * import process from 'process'; + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; * - * const numCPUs = cpus().length; + * const numCPUs = availableParallelism(); * * if (cluster.isPrimary) { * console.log(`Primary ${process.pid} is running`); diff --git a/node_modules/@types/node/ts4.8/console.d.ts b/node_modules/@types/node/ts4.8/console.d.ts index 16c9137..7e35638 100644 --- a/node_modules/@types/node/ts4.8/console.d.ts +++ b/node_modules/@types/node/ts4.8/console.d.ts @@ -1,11 +1,11 @@ /** - * The `console` module provides a simple debugging console that is similar to the - * JavaScript console mechanism provided by web browsers. + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. * * The module exports two specific components: * - * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. - * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * * A `Console` class with methods such as `console.log()`, `console.error()`, and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('node:console')`. * * _**Warning**_: The global console object's methods are neither consistently * synchronous like the browser APIs they resemble, nor are they consistently @@ -53,7 +53,7 @@ * myConsole.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to err * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/console.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/console.js) */ declare module 'console' { import console = require('node:console'); diff --git a/node_modules/@types/node/ts4.8/crypto.d.ts b/node_modules/@types/node/ts4.8/crypto.d.ts index 20d960c..78c579d 100644 --- a/node_modules/@types/node/ts4.8/crypto.d.ts +++ b/node_modules/@types/node/ts4.8/crypto.d.ts @@ -1,9 +1,10 @@ /** - * The `crypto` module provides cryptographic functionality that includes a set of - * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. * * ```js - * const { createHmac } = await import('crypto'); + * const { createHmac } = await import('node:crypto'); * * const secret = 'abcdefg'; * const hash = createHmac('sha256', secret) @@ -13,27 +14,27 @@ * // Prints: * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/crypto.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/crypto.js) */ declare module 'crypto' { import * as stream from 'node:stream'; import { PeerCertificate } from 'node:tls'; /** * SPKAC is a Certificate Signing Request mechanism originally implemented by - * Netscape and was specified formally as part of [HTML5's `keygen` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen). + * Netscape and was specified formally as part of HTML5's `keygen` element. * * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects * should not use this element anymore. * - * The `crypto` module provides the `Certificate` class for working with SPKAC + * The `node:crypto` module provides the `Certificate` class for working with SPKAC * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC - * implementation](https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html) internally. + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. * @since v0.11.8 */ class Certificate { /** * ```js - * const { Certificate } = await import('crypto'); + * const { Certificate } = await import('node:crypto'); * const spkac = getSpkacSomehow(); * const challenge = Certificate.exportChallenge(spkac); * console.log(challenge.toString('utf8')); @@ -46,7 +47,7 @@ declare module 'crypto' { static exportChallenge(spkac: BinaryLike): Buffer; /** * ```js - * const { Certificate } = await import('crypto'); + * const { Certificate } = await import('node:crypto'); * const spkac = getSpkacSomehow(); * const publicKey = Certificate.exportPublicKey(spkac); * console.log(publicKey); @@ -59,8 +60,8 @@ declare module 'crypto' { static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; /** * ```js - * import { Buffer } from 'buffer'; - * const { Certificate } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); * * const spkac = getSpkacSomehow(); * console.log(Certificate.verifySpkac(Buffer.from(spkac))); @@ -95,7 +96,7 @@ declare module 'crypto' { verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; } namespace constants { - // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + // https://nodejs.org/dist/latest-v20.x/docs/api/crypto.html#crypto-constants const OPENSSL_VERSION_NUMBER: number; /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ const SSL_OP_ALL: number; @@ -111,18 +112,8 @@ declare module 'crypto' { const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ - const SSL_OP_EPHEMERAL_RSA: number; /** Allows initial connection to servers that do not support RI. */ const SSL_OP_LEGACY_SERVER_CONNECT: number; - const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - const SSL_OP_MICROSOFT_SESS_ID_BUG: number; - /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ - const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - const SSL_OP_NETSCAPE_CA_DN_BUG: number; - const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; /** Instructs OpenSSL to disable support for SSL/TLS compression. */ const SSL_OP_NO_COMPRESSION: number; const SSL_OP_NO_QUERY_MTU: number; @@ -134,16 +125,6 @@ declare module 'crypto' { const SSL_OP_NO_TLSv1: number; const SSL_OP_NO_TLSv1_1: number; const SSL_OP_NO_TLSv1_2: number; - const SSL_OP_PKCS1_CHECK_1: number; - const SSL_OP_PKCS1_CHECK_2: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ - const SSL_OP_SINGLE_DH_USE: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ - const SSL_OP_SINGLE_ECDH_USE: number; - const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - const SSL_OP_TLS_BLOCK_PADDING_BUG: number; - const SSL_OP_TLS_D5_BUG: number; /** Instructs OpenSSL to disable version rollback attack detection. */ const SSL_OP_TLS_ROLLBACK_BUG: number; const ENGINE_METHOD_RSA: number; @@ -161,7 +142,6 @@ declare module 'crypto' { const DH_CHECK_P_NOT_PRIME: number; const DH_UNABLE_TO_CHECK_GENERATOR: number; const DH_NOT_SUITABLE_GENERATOR: number; - const ALPN_ENABLED: number; const RSA_PKCS1_PADDING: number; const RSA_SSLV23_PADDING: number; const RSA_NO_PADDING: number; @@ -206,12 +186,12 @@ declare module 'crypto' { * * ```js * import { - * createReadStream - * } from 'fs'; - * import { argv } from 'process'; + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const filename = argv[2]; * @@ -243,18 +223,20 @@ declare module 'crypto' { * display the available digest algorithms. * * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is - * a `KeyObject`, its type must be `secret`. + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). * * Example: generating the sha256 HMAC of a file * * ```js * import { - * createReadStream - * } from 'fs'; - * import { argv } from 'process'; + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const filename = argv[2]; * @@ -297,8 +279,8 @@ declare module 'crypto' { * * ```js * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -320,9 +302,9 @@ declare module 'crypto' { * Example: Using `Hash` and piped streams: * * ```js - * import { createReadStream } from 'fs'; - * import { stdout } from 'process'; - * const { createHash } = await import('crypto'); + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -334,8 +316,8 @@ declare module 'crypto' { * * ```js * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -362,8 +344,8 @@ declare module 'crypto' { * ```js * // Calculate a rolling hash. * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -422,8 +404,8 @@ declare module 'crypto' { * * ```js * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const hmac = createHmac('sha256', 'a secret'); * @@ -445,11 +427,11 @@ declare module 'crypto' { * Example: Using `Hmac` and piped streams: * * ```js - * import { createReadStream } from 'fs'; - * import { stdout } from 'process'; + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const hmac = createHmac('sha256', 'a secret'); * @@ -461,8 +443,8 @@ declare module 'crypto' { * * ```js * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const hmac = createHmac('sha256', 'a secret'); * @@ -575,13 +557,13 @@ declare module 'crypto' { * Example: Converting a `CryptoKey` instance to a `KeyObject`: * * ```js - * const { webcrypto, KeyObject } = await import('crypto'); - * const { subtle } = webcrypto; + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; * * const key = await subtle.generateKey({ * name: 'HMAC', * hash: 'SHA-256', - * length: 256 + * length: 256, * }, true, ['sign', 'verify']); * * const keyObject = KeyObject.from(key); @@ -698,14 +680,18 @@ declare module 'crypto' { * The `password` is used to derive the cipher key and initialization vector (IV). * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * * The implementation of `crypto.createCipher()` derives keys using the OpenSSL - * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one * iteration, and no salt. The lack of salt allows dictionary attacks as the same * password always creates the same key. The low iteration count and * non-cryptographically secure hash algorithm allow passwords to be tested very * rapidly. * - * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that * developers derive a key and IV on * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when @@ -773,8 +759,8 @@ declare module 'crypto' { * const { * scrypt, * randomFill, - * createCipheriv - * } = await import('crypto'); + * createCipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -808,17 +794,17 @@ declare module 'crypto' { * import { * createReadStream, * createWriteStream, - * } from 'fs'; + * } from 'node:fs'; * * import { - * pipeline - * } from 'stream'; + * pipeline, + * } from 'node:stream'; * * const { * scrypt, * randomFill, - * createCipheriv - * } = await import('crypto'); + * createCipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -849,8 +835,8 @@ declare module 'crypto' { * const { * scrypt, * randomFill, - * createCipheriv - * } = await import('crypto'); + * createCipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -955,14 +941,18 @@ declare module 'crypto' { * authentication tag in bytes, see `CCM mode`. * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL - * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one * iteration, and no salt. The lack of salt allows dictionary attacks as the same * password always creates the same key. The low iteration count and * non-cryptographically secure hash algorithm allow passwords to be tested very * rapidly. * - * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that * developers derive a key and IV on * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. * @since v0.1.94 @@ -1023,11 +1013,11 @@ declare module 'crypto' { * Example: Using `Decipher` objects as streams: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { * scryptSync, - * createDecipheriv - * } = await import('crypto'); + * createDecipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -1042,6 +1032,7 @@ declare module 'crypto' { * * let decrypted = ''; * decipher.on('readable', () => { + * let chunk; * while (null !== (chunk = decipher.read())) { * decrypted += chunk.toString('utf8'); * } @@ -1064,12 +1055,12 @@ declare module 'crypto' { * import { * createReadStream, * createWriteStream, - * } from 'fs'; - * import { Buffer } from 'buffer'; + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; * const { * scryptSync, - * createDecipheriv - * } = await import('crypto'); + * createDecipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -1089,11 +1080,11 @@ declare module 'crypto' { * Example: Using the `decipher.update()` and `decipher.final()` methods: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { * scryptSync, - * createDecipheriv - * } = await import('crypto'); + * createDecipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -1190,25 +1181,30 @@ declare module 'crypto' { format?: KeyFormat | undefined; type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined; passphrase?: string | Buffer | undefined; + encoding?: string | undefined; } interface PublicKeyInput { key: string | Buffer; format?: KeyFormat | undefined; type?: 'pkcs1' | 'spki' | undefined; + encoding?: string | undefined; } /** * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. * * ```js * const { - * generateKey - * } = await import('crypto'); + * generateKey, + * } = await import('node:crypto'); * - * generateKey('hmac', { length: 64 }, (err, key) => { + * generateKey('hmac', { length: 512 }, (err, key) => { * if (err) throw err; * console.log(key.export().toString('hex')); // 46e..........620 * }); * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. * @since v15.0.0 * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. */ @@ -1224,12 +1220,15 @@ declare module 'crypto' { * * ```js * const { - * generateKeySync - * } = await import('crypto'); + * generateKeySync, + * } = await import('node:crypto'); * - * const key = generateKeySync('hmac', { length: 64 }); + * const key = generateKeySync('hmac', { length: 512 }); * console.log(key.export().toString('hex')); // e89..........41e * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. * @since v15.0.0 * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. */ @@ -1291,7 +1290,7 @@ declare module 'crypto' { type DSAEncoding = 'der' | 'ieee-p1363'; interface SigningOptions { /** - * @See crypto.constants.RSA_PKCS1_PADDING + * @see crypto.constants.RSA_PKCS1_PADDING */ padding?: number | undefined; saltLength?: number | undefined; @@ -1305,6 +1304,7 @@ declare module 'crypto' { interface VerifyKeyObjectInput extends SigningOptions { key: KeyObject; } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} type KeyLike = string | Buffer | KeyObject; /** * The `Sign` class is a utility for generating signatures. It can be used in one @@ -1324,11 +1324,11 @@ declare module 'crypto' { * const { * generateKeyPairSync, * createSign, - * createVerify - * } = await import('crypto'); + * createVerify, + * } = await import('node:crypto'); * * const { privateKey, publicKey } = generateKeyPairSync('ec', { - * namedCurve: 'sect239k1' + * namedCurve: 'sect239k1', * }); * * const sign = createSign('SHA256'); @@ -1349,8 +1349,8 @@ declare module 'crypto' { * const { * generateKeyPairSync, * createSign, - * createVerify - * } = await import('crypto'); + * createVerify, + * } = await import('node:crypto'); * * const { privateKey, publicKey } = generateKeyPairSync('rsa', { * modulusLength: 2048, @@ -1459,8 +1459,8 @@ declare module 'crypto' { * be passed instead of a public key. * @since v0.1.92 */ - verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; - verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, signature: NodeJS.ArrayBufferView): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; } /** * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an @@ -1490,11 +1490,11 @@ declare module 'crypto' { * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * const { - * createDiffieHellman - * } = await import('crypto'); + * createDiffieHellman, + * } = await import('node:crypto'); * * // Generate Alice's keys... * const alice = createDiffieHellman(2048); @@ -1600,7 +1600,7 @@ declare module 'crypto' { * A bit field containing any warnings and/or errors resulting from a check * performed during initialization of the `DiffieHellman` object. * - * The following values are valid for this property (as defined in `constants`module): + * The following values are valid for this property (as defined in `node:constants` module): * * * `DH_CHECK_P_NOT_SAFE_PRIME` * * `DH_CHECK_P_NOT_PRIME` @@ -1635,16 +1635,16 @@ declare module 'crypto' { */ const DiffieHellmanGroup: DiffieHellmanGroupConstructor; interface DiffieHellmanGroupConstructor { - new(name: string): DiffieHellmanGroup; + new (name: string): DiffieHellmanGroup; (name: string): DiffieHellmanGroup; readonly prototype: DiffieHellmanGroup; } type DiffieHellmanGroup = Omit; /** * Creates a predefined `DiffieHellmanGroup` key exchange object. The - * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, - * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The - * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing * the keys (with `diffieHellman.setPublicKey()`, for example). The * advantage of using this method is that the parties do not have to * generate nor exchange a group modulus beforehand, saving both processor @@ -1654,8 +1654,8 @@ declare module 'crypto' { * * ```js * const { - * getDiffieHellman - * } = await import('crypto'); + * getDiffieHellman, + * } = await import('node:crypto'); * const alice = getDiffieHellman('modp14'); * const bob = getDiffieHellman('modp14'); * @@ -1685,9 +1685,6 @@ declare module 'crypto' { * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be * thrown if any of the input arguments specify invalid values or types. * - * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, - * please specify a `digest` explicitly. - * * The `iterations` argument must be a number set as high as possible. The * higher the number of iterations, the more secure the derived key will be, * but will take a longer amount of time to complete. @@ -1699,8 +1696,8 @@ declare module 'crypto' { * * ```js * const { - * pbkdf2 - * } = await import('crypto'); + * pbkdf2, + * } = await import('node:crypto'); * * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { * if (err) throw err; @@ -1708,18 +1705,6 @@ declare module 'crypto' { * }); * ``` * - * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been - * deprecated and use should be avoided. - * - * ```js - * import crypto from 'crypto'; - * crypto.DEFAULT_ENCODING = 'hex'; - * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { - * if (err) throw err; - * console.log(derivedKey); // '3745e48...aa39b34' - * }); - * ``` - * * An array of supported digest functions can be retrieved using {@link getHashes}. * * This API uses libuv's threadpool, which can have surprising and @@ -1735,9 +1720,6 @@ declare module 'crypto' { * If an error occurs an `Error` will be thrown, otherwise the derived key will be * returned as a `Buffer`. * - * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, - * please specify a `digest` explicitly. - * * The `iterations` argument must be a number set as high as possible. The * higher the number of iterations, the more secure the derived key will be, * but will take a longer amount of time to complete. @@ -1749,23 +1731,13 @@ declare module 'crypto' { * * ```js * const { - * pbkdf2Sync - * } = await import('crypto'); + * pbkdf2Sync, + * } = await import('node:crypto'); * * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); * console.log(key.toString('hex')); // '3745e48...08d59ae' * ``` * - * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use - * should be avoided. - * - * ```js - * import crypto from 'crypto'; - * crypto.DEFAULT_ENCODING = 'hex'; - * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); - * console.log(key); // '3745e48...aa39b34' - * ``` - * * An array of supported digest functions can be retrieved using {@link getHashes}. * @since v0.9.3 */ @@ -1781,8 +1753,8 @@ declare module 'crypto' { * ```js * // Asynchronous * const { - * randomBytes - * } = await import('crypto'); + * randomBytes, + * } = await import('node:crypto'); * * randomBytes(256, (err, buf) => { * if (err) throw err; @@ -1797,8 +1769,8 @@ declare module 'crypto' { * ```js * // Synchronous * const { - * randomBytes - * } = await import('crypto'); + * randomBytes, + * } = await import('node:crypto'); * * const buf = randomBytes(256); * console.log( @@ -1830,7 +1802,7 @@ declare module 'crypto' { * Return a random integer `n` such that `min <= n < max`. This * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). * - * The range (`max - min`) must be less than 2^48. `min` and `max` must + * The range (`max - min`) must be less than 248. `min` and `max` must * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). * * If the `callback` function is not provided, the random integer is @@ -1839,8 +1811,8 @@ declare module 'crypto' { * ```js * // Asynchronous * const { - * randomInt - * } = await import('crypto'); + * randomInt, + * } = await import('node:crypto'); * * randomInt(3, (err, n) => { * if (err) throw err; @@ -1851,8 +1823,8 @@ declare module 'crypto' { * ```js * // Synchronous * const { - * randomInt - * } = await import('crypto'); + * randomInt, + * } = await import('node:crypto'); * * const n = randomInt(3); * console.log(`Random number chosen from (0, 1, 2): ${n}`); @@ -1861,8 +1833,8 @@ declare module 'crypto' { * ```js * // With `min` argument * const { - * randomInt - * } = await import('crypto'); + * randomInt, + * } = await import('node:crypto'); * * const n = randomInt(1, 7); * console.log(`The dice rolled: ${n}`); @@ -1880,8 +1852,8 @@ declare module 'crypto' { * Synchronous version of {@link randomFill}. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFillSync } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); * * const buf = Buffer.alloc(10); * console.log(randomFillSync(buf).toString('hex')); @@ -1897,8 +1869,8 @@ declare module 'crypto' { * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFillSync } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); * * const a = new Uint32Array(10); * console.log(Buffer.from(randomFillSync(a).buffer, @@ -1926,8 +1898,8 @@ declare module 'crypto' { * If the `callback` function is not provided, an error will be thrown. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFill } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); * * const buf = Buffer.alloc(10); * randomFill(buf, (err, buf) => { @@ -1956,8 +1928,8 @@ declare module 'crypto' { * distribution and have no meaningful lower or upper bounds. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFill } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); * * const a = new Uint32Array(10); * randomFill(a, (err, buf) => { @@ -2023,8 +1995,8 @@ declare module 'crypto' { * * ```js * const { - * scrypt - * } = await import('crypto'); + * scrypt, + * } = await import('node:crypto'); * * // Using the factory defaults. * scrypt('password', 'salt', 64, (err, derivedKey) => { @@ -2059,8 +2031,8 @@ declare module 'crypto' { * * ```js * const { - * scryptSync - * } = await import('crypto'); + * scryptSync, + * } = await import('node:crypto'); * // Using the factory defaults. * * const key1 = scryptSync('password', 'salt', 64); @@ -2131,8 +2103,8 @@ declare module 'crypto' { /** * ```js * const { - * getCiphers - * } = await import('crypto'); + * getCiphers, + * } = await import('node:crypto'); * * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] * ``` @@ -2143,8 +2115,8 @@ declare module 'crypto' { /** * ```js * const { - * getCurves - * } = await import('crypto'); + * getCurves, + * } = await import('node:crypto'); * * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] * ``` @@ -2158,7 +2130,8 @@ declare module 'crypto' { */ function getFips(): 1 | 0; /** - * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available. + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. * @since v10.0.0 * @param bool `true` to enable FIPS mode. */ @@ -2166,8 +2139,8 @@ declare module 'crypto' { /** * ```js * const { - * getHashes - * } = await import('crypto'); + * getHashes, + * } = await import('node:crypto'); * * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] * ``` @@ -2182,11 +2155,11 @@ declare module 'crypto' { * Instances of the `ECDH` class can be created using the {@link createECDH} function. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * const { - * createECDH - * } = await import('crypto'); + * createECDH, + * } = await import('node:crypto'); * * // Generate Alice's keys... * const alice = createECDH('secp521r1'); @@ -2227,8 +2200,8 @@ declare module 'crypto' { * ```js * const { * createECDH, - * ECDH - * } = await import('crypto'); + * ECDH, + * } = await import('node:crypto'); * * const ecdh = createECDH('secp256k1'); * ecdh.generateKeys(); @@ -2306,7 +2279,7 @@ declare module 'crypto' { * If `encoding` is specified, a string is returned; otherwise a `Buffer` is * returned. * @since v0.11.14 - * @param [encoding] The `encoding` of the return value. + * @param encoding The `encoding` of the return value. * @param [format='uncompressed'] * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. */ @@ -2335,8 +2308,10 @@ declare module 'crypto' { */ function createECDH(curveName: string): ECDH; /** - * This function is based on a constant-time algorithm. - * Returns true if `a` is equal to `b`, without leaking timing information that + * This function compares the underlying bytes that represent the given`ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that * would allow an attacker to guess one of the values. This is suitable for * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). * @@ -2348,14 +2323,16 @@ declare module 'crypto' { * entry, such as `Uint16Array`, the result will be computed using the platform * byte order. * + * **When both of the inputs are `Float32Array`s or`Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor`Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code * is timing-safe. Care should be taken to ensure that the surrounding code does * not introduce timing vulnerabilities. * @since v6.6.0 */ function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; - /** @deprecated since v10.0.0 */ - const DEFAULT_ENCODING: BufferEncoding; type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; type KeyFormat = 'pem' | 'der' | 'jwk'; interface BasePrivateKeyEncodingOptions { @@ -2553,8 +2530,8 @@ declare module 'crypto' { * * ```js * const { - * generateKeyPairSync - * } = await import('crypto'); + * generateKeyPairSync, + * } = await import('node:crypto'); * * const { * publicKey, @@ -2563,14 +2540,14 @@ declare module 'crypto' { * modulusLength: 4096, * publicKeyEncoding: { * type: 'spki', - * format: 'pem' + * format: 'pem', * }, * privateKeyEncoding: { * type: 'pkcs8', * format: 'pem', * cipher: 'aes-256-cbc', - * passphrase: 'top secret' - * } + * passphrase: 'top secret', + * }, * }); * ``` * @@ -2632,21 +2609,21 @@ declare module 'crypto' { * * ```js * const { - * generateKeyPair - * } = await import('crypto'); + * generateKeyPair, + * } = await import('node:crypto'); * * generateKeyPair('rsa', { * modulusLength: 4096, * publicKeyEncoding: { * type: 'spki', - * format: 'pem' + * format: 'pem', * }, * privateKeyEncoding: { * type: 'pkcs8', * format: 'pem', * cipher: 'aes-256-cbc', - * passphrase: 'top secret' - * } + * passphrase: 'top secret', + * }, * }, (err, publicKey, privateKey) => { * // Handle errors and use the generated key pair. * }); @@ -2968,11 +2945,16 @@ declare module 'crypto' { * If the `callback` function is provided this function uses libuv's threadpool. * @since v12.0.0 */ - function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; function verify( algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, - key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, signature: NodeJS.ArrayBufferView, callback: (error: Error | null, result: boolean) => void ): void; @@ -3042,10 +3024,10 @@ declare module 'crypto' { * of the input arguments specify invalid values or types. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { - * hkdf - * } = await import('crypto'); + * hkdf, + * } = await import('node:crypto'); * * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { * if (err) throw err; @@ -3054,7 +3036,7 @@ declare module 'crypto' { * ``` * @since v15.0.0 * @param digest The digest algorithm to use. - * @param ikm The input keying material. It must be at least one byte in length. + * @param ikm The input keying material. Must be provided but can be zero-length. * @param salt The salt value. Must be provided but can be zero-length. * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` @@ -3071,17 +3053,17 @@ declare module 'crypto' { * types, or if the derived key cannot be generated. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { - * hkdfSync - * } = await import('crypto'); + * hkdfSync, + * } = await import('node:crypto'); * * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' * ``` * @since v15.0.0 * @param digest The digest algorithm to use. - * @param ikm The input keying material. It must be at least one byte in length. + * @param ikm The input keying material. Must be provided but can be zero-length. * @param salt The salt value. Must be provided but can be zero-length. * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` @@ -3154,7 +3136,7 @@ declare module 'crypto' { * its information. * * ```js - * const { X509Certificate } = await import('crypto'); + * const { X509Certificate } = await import('node:crypto'); * * const x509 = new X509Certificate('{... pem encoded cert ...}'); * @@ -3184,23 +3166,53 @@ declare module 'crypto' { readonly fingerprint256: string; /** * The SHA-512 fingerprint of this certificate. - * @since v16.14.0 + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 */ - readonly fingerprint512: string; + readonly fingerprint512: string; /** * The complete subject of this certificate. * @since v15.6.0 */ readonly subject: string; /** - * The subject alternative name specified for this certificate or `undefined` - * if not available. + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. * @since v15.6.0 */ readonly subjectAltName: string | undefined; /** - * The information access content of this certificate or `undefined` if not - * available. + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. * @since v15.6.0 */ readonly infoAccess: string | undefined; @@ -3444,36 +3456,29 @@ declare module 'crypto' { * * `engine` could be either an id or a path to the engine's shared library. * - * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. - * The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`is a bit field taking one of or a mix of the following flags (defined in`crypto.constants`): * - * - `crypto.constants.ENGINE_METHOD_RSA` - * - `crypto.constants.ENGINE_METHOD_DSA` - * - `crypto.constants.ENGINE_METHOD_DH` - * - `crypto.constants.ENGINE_METHOD_RAND` - * - `crypto.constants.ENGINE_METHOD_EC` - * - `crypto.constants.ENGINE_METHOD_CIPHERS` - * - `crypto.constants.ENGINE_METHOD_DIGESTS` - * - `crypto.constants.ENGINE_METHOD_PKEY_METHS` - * - `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` - * - `crypto.constants.ENGINE_METHOD_ALL` - * - `crypto.constants.ENGINE_METHOD_NONE` - * - * The flags below are deprecated in OpenSSL-1.1.0. - * - * - `crypto.constants.ENGINE_METHOD_ECDH` - * - `crypto.constants.ENGINE_METHOD_ECDSA` - * - `crypto.constants.ENGINE_METHOD_STORE` + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` * @since v0.11.11 - * @param [flags=crypto.constants.ENGINE_METHOD_ALL] + * @param flags */ function setEngine(engine: string, flags?: number): void; /** - * A convenient alias for `crypto.webcrypto.getRandomValues()`. - * This implementation is not compliant with the Web Crypto spec, - * to write web-compatible code use `crypto.webcrypto.getRandomValues()` instead. + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. * @since v17.4.0 - * @returns Returns `typedArray`. + * @return Returns `typedArray`. */ function getRandomValues(typedArray: T): T; /** diff --git a/node_modules/@types/node/ts4.8/dgram.d.ts b/node_modules/@types/node/ts4.8/dgram.d.ts index 247328d..02d7106 100644 --- a/node_modules/@types/node/ts4.8/dgram.d.ts +++ b/node_modules/@types/node/ts4.8/dgram.d.ts @@ -1,13 +1,13 @@ /** - * The `dgram` module provides an implementation of UDP datagram sockets. + * The `node:dgram` module provides an implementation of UDP datagram sockets. * * ```js - * import dgram from 'dgram'; + * import dgram from 'node:dgram'; * * const server = dgram.createSocket('udp4'); * * server.on('error', (err) => { - * console.log(`server error:\n${err.stack}`); + * console.error(`server error:\n${err.stack}`); * server.close(); * }); * @@ -23,7 +23,7 @@ * 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) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dgram.js) */ declare module 'dgram' { import { AddressInfo } from 'node:net'; @@ -98,8 +98,8 @@ declare module 'dgram' { * 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'; + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; * * if (cluster.isPrimary) { * cluster.fork(); // Works ok. @@ -116,7 +116,7 @@ declare module 'dgram' { 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. + * 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 @@ -142,12 +142,12 @@ declare module 'dgram' { * Example of a UDP server listening on port 41234: * * ```js - * import dgram from 'dgram'; + * import dgram from 'node:dgram'; * * const server = dgram.createSocket('udp4'); * * server.on('error', (err) => { - * console.log(`server error:\n${err.stack}`); + * console.error(`server error:\n${err.stack}`); * server.close(); * }); * @@ -284,8 +284,8 @@ declare module 'dgram' { * Example of sending a UDP packet to a port on `localhost`; * * ```js - * import dgram from 'dgram'; - * import { Buffer } from 'buffer'; + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; * * const message = Buffer.from('Some bytes'); * const client = dgram.createSocket('udp4'); @@ -297,8 +297,8 @@ declare module 'dgram' { * 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'; + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('Some '); * const buf2 = Buffer.from('bytes'); @@ -316,8 +316,8 @@ declare module 'dgram' { * Example of sending a UDP packet using a socket connected to a port on`localhost`: * * ```js - * import dgram from 'dgram'; - * import { Buffer } from 'buffer'; + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; * * const message = Buffer.from('Some bytes'); * const client = dgram.createSocket('udp4'); diff --git a/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts b/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts index 3dcaa03..5f19b20 100644 --- a/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts +++ b/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts @@ -1,11 +1,11 @@ /** - * The `diagnostics_channel` module provides an API to create named channels + * The `node: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'; + * import diagnostics_channel from 'node:diagnostics_channel'; * ``` * * It is intended that a module writer wanting to report diagnostics messages @@ -19,8 +19,8 @@ * 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) + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js) */ declare module 'diagnostics_channel' { /** @@ -31,7 +31,7 @@ declare module 'diagnostics_channel' { * performance-sensitive code. * * ```js - * import diagnostics_channel from 'diagnostics_channel'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * if (diagnostics_channel.hasSubscribers('my-channel')) { * // There are subscribers, prepare and publish message @@ -43,12 +43,12 @@ declare module 'diagnostics_channel' { */ function hasSubscribers(name: string | symbol): boolean; /** - * This is the primary entry-point for anyone wanting to interact with a named + * This is the primary entry-point for anyone wanting to publish to 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'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * ``` @@ -58,9 +58,46 @@ declare module 'diagnostics_channel' { */ 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 'node: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 {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node: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 + * @return `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 + * pipeline. It is used 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 @@ -77,7 +114,7 @@ declare module 'diagnostics_channel' { * performance-sensitive code. * * ```js - * import diagnostics_channel from 'diagnostics_channel'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * @@ -90,17 +127,16 @@ declare module 'diagnostics_channel' { 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. + * 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'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * * channel.publish({ - * some: 'message' + * some: 'message', * }); * ``` * @since v15.1.0, v14.17.0 @@ -113,7 +149,7 @@ declare module 'diagnostics_channel' { * errors thrown in the message handler will trigger an `'uncaughtException'`. * * ```js - * import diagnostics_channel from 'diagnostics_channel'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * @@ -122,6 +158,7 @@ declare module 'diagnostics_channel' { * }); * ``` * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} * @param onMessage The handler to receive channel messages */ subscribe(onMessage: ChannelListener): void; @@ -129,7 +166,7 @@ declare module 'diagnostics_channel' { * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. * * ```js - * import diagnostics_channel from 'diagnostics_channel'; + * import diagnostics_channel from 'node:diagnostics_channel'; * * const channel = diagnostics_channel.channel('my-channel'); * @@ -142,6 +179,7 @@ declare module 'diagnostics_channel' { * channel.unsubscribe(onMessage); * ``` * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} * @param onMessage The previous subscribed handler to remove * @return `true` if the handler was found, `false` otherwise. */ diff --git a/node_modules/@types/node/ts4.8/dns.d.ts b/node_modules/@types/node/ts4.8/dns.d.ts index 305367b..db3febc 100644 --- a/node_modules/@types/node/ts4.8/dns.d.ts +++ b/node_modules/@types/node/ts4.8/dns.d.ts @@ -1,5 +1,5 @@ /** - * The `dns` module enables name resolution. For example, use it to look up IP + * The `node:dns` module enables name resolution. For example, use it to look up IP * addresses of host names. * * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the @@ -9,7 +9,7 @@ * system do, use {@link lookup}. * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * * dns.lookup('example.org', (err, address, family) => { * console.log('address: %j family: IPv%s', address, family); @@ -17,13 +17,13 @@ * // address: "93.184.216.34" family: IPv4 * ``` * - * All other functions in the `dns` module connect to an actual DNS server to + * All other functions in the `node:dns` module connect to an actual DNS server to * perform name resolution. They will always use the network to perform DNS * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform * DNS queries, bypassing other name-resolution facilities. * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * * dns.resolve4('archive.org', (err, addresses) => { * if (err) throw err; @@ -42,7 +42,7 @@ * ``` * * See the `Implementation considerations section` for more information. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/dns.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dns.js) */ declare module 'dns' { import * as dnsPromises from 'node:dns/promises'; @@ -76,8 +76,8 @@ declare module 'dns' { /** * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or * AAAA (IPv6) record. All `option` properties are optional. If `options` is an - * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 - * and IPv6 addresses are both returned if found. + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. * * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the * properties `address` and `family`. @@ -89,14 +89,14 @@ declare module 'dns' { * * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. * The implementation uses an operating system facility that can associate names - * with addresses, and vice versa. This implementation can have subtle but + * with addresses and vice versa. This implementation can have subtle but * important consequences on the behavior of any Node.js program. Please take some * time to consult the `Implementation considerations section` before using`dns.lookup()`. * * Example usage: * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * const options = { * family: 6, * hints: dns.ADDRCONFIG | dns.V4MAPPED, @@ -135,7 +135,7 @@ declare module 'dns' { * On an error, `err` is an `Error` object, where `err.code` is the error code. * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { * console.log(hostname, service); * // Prints: localhost ssh @@ -174,7 +174,7 @@ declare module 'dns' { type: 'AAAA'; } export interface CaaRecord { - critial: number; + critical: number; issue?: string | undefined; issuewild?: string | undefined; iodef?: string | undefined; @@ -291,7 +291,7 @@ declare module 'dns' { function __promisify__(hostname: string, options?: ResolveOptions): Promise; } /** - * Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function * will contain an array of IPv6 addresses. * @since v0.1.16 * @param hostname Host name to resolve. @@ -333,7 +333,7 @@ declare module 'dns' { function __promisify__(hostname: string): Promise; } /** - * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of * objects with the following properties: * * * `flags` @@ -484,6 +484,14 @@ declare module 'dns' { * @since v0.1.16 */ export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + /** + * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + export function getDefaultResultOrder(): 'ipv4first' | 'verbatim'; /** * Sets the IP address and port of servers to be used when performing DNS * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted @@ -535,7 +543,7 @@ declare module 'dns' { * * `ipv4first`: sets default `verbatim` `false`. * * `verbatim`: sets default `verbatim` `true`. * - * The default is `ipv4first` and {@link setDefaultResultOrder} have higher + * The default is `verbatim` and {@link setDefaultResultOrder} have higher * priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default * dns orders in workers. * @since v16.4.0, v14.18.0 @@ -582,7 +590,7 @@ declare module 'dns' { * other resolvers: * * ```js - * const { Resolver } = require('dns'); + * const { Resolver } = require('node:dns'); * const resolver = new Resolver(); * resolver.setServers(['4.4.4.4']); * @@ -592,7 +600,7 @@ declare module 'dns' { * }); * ``` * - * The following methods from the `dns` module are available: + * The following methods from the `node:dns` module are available: * * * `resolver.getServers()` * * `resolver.resolve()` @@ -625,6 +633,7 @@ declare module 'dns' { resolve4: typeof resolve4; resolve6: typeof resolve6; resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; resolveCname: typeof resolveCname; resolveMx: typeof resolveMx; resolveNaptr: typeof resolveNaptr; @@ -639,7 +648,7 @@ declare module 'dns' { * This allows programs to specify outbound interfaces when used on multi-homed * systems. * - * If a v4 or v6 address is not specified, it is set to the default, and the + * If a v4 or v6 address is not specified, it is set to the default and the * operating system will choose a local address automatically. * * The resolver will use the v4 local address when making requests to IPv4 DNS diff --git a/node_modules/@types/node/ts4.8/dns/promises.d.ts b/node_modules/@types/node/ts4.8/dns/promises.d.ts index 77cd807..4c151e4 100644 --- a/node_modules/@types/node/ts4.8/dns/promises.d.ts +++ b/node_modules/@types/node/ts4.8/dns/promises.d.ts @@ -1,7 +1,7 @@ /** * The `dns.promises` API provides an alternative set of asynchronous DNS methods * that return `Promise` objects rather than using callbacks. The API is accessible - * via `require('dns').promises` or `require('dns/promises')`. + * via `require('node:dns').promises` or `require('node:dns/promises')`. * @since v10.6.0 */ declare module 'dns/promises' { @@ -52,7 +52,7 @@ declare module 'dns/promises' { * * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS * protocol. The implementation uses an operating system facility that can - * associate names with addresses, and vice versa. This implementation can have + * associate names with addresses and vice versa. This implementation can have * subtle but important consequences on the behavior of any Node.js program. Please * take some time to consult the `Implementation considerations section` before * using `dnsPromises.lookup()`. @@ -60,7 +60,7 @@ declare module 'dns/promises' { * Example usage: * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * const dnsPromises = dns.promises; * const options = { * family: 6, @@ -96,7 +96,7 @@ declare module 'dns/promises' { * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. * * ```js - * const dnsPromises = require('dns').promises; + * const dnsPromises = require('node:dns').promises; * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { * console.log(result.hostname, result.service); * // Prints: localhost ssh @@ -206,7 +206,7 @@ declare module 'dns/promises' { */ function resolveMx(hostname: string): Promise; /** - * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array * of objects with the following properties: * * * `flags` @@ -337,13 +337,56 @@ declare module 'dns/promises' { * * `ipv4first`: sets default `verbatim` `false`. * * `verbatim`: sets default `verbatim` `true`. * - * The default is `ipv4first` and `dnsPromises.setDefaultResultOrder()` have + * The default is `verbatim` and `dnsPromises.setDefaultResultOrder()` have * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the * default dns orders in workers. * @since v16.4.0, v14.18.0 * @param order must be `'ipv4first'` or `'verbatim'`. */ function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns').promises; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ class Resolver { constructor(options?: ResolverOptions); cancel(): void; @@ -352,6 +395,7 @@ declare module 'dns/promises' { resolve4: typeof resolve4; resolve6: typeof resolve6; resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; resolveCname: typeof resolveCname; resolveMx: typeof resolveMx; resolveNaptr: typeof resolveNaptr; diff --git a/node_modules/@types/node/ts4.8/domain.d.ts b/node_modules/@types/node/ts4.8/domain.d.ts index fafe68a..e49b87f 100644 --- a/node_modules/@types/node/ts4.8/domain.d.ts +++ b/node_modules/@types/node/ts4.8/domain.d.ts @@ -12,7 +12,7 @@ * 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) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/domain.js) */ declare module 'domain' { import EventEmitter = require('node:events'); @@ -56,15 +56,15 @@ declare module 'domain' { exit(): void; /** * Run the supplied function in the context of the domain, implicitly - * binding all event emitters, timers, and lowlevel requests that are + * binding all event emitters, timers, and low-level 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 domain = require('node:domain'); + * const fs = require('node:fs'); * const d = domain.create(); * d.on('error', (er) => { * console.error('Caught error!', er); diff --git a/node_modules/@types/node/ts4.8/events.d.ts b/node_modules/@types/node/ts4.8/events.d.ts index 4633df1..29616e1 100644 --- a/node_modules/@types/node/ts4.8/events.d.ts +++ b/node_modules/@types/node/ts4.8/events.d.ts @@ -22,7 +22,7 @@ * the `eventEmitter.emit()` method is used to trigger the event. * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; * * class MyEmitter extends EventEmitter {} * @@ -32,13 +32,12 @@ * }); * myEmitter.emit('event'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/events.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.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 { @@ -69,7 +68,6 @@ declare module 'events' { // */ // removeListener(type: string, listener: EventListener | EventListenerObject): this; // } - interface EventEmitterOptions { /** * Enables automatic capturing of promise rejection. @@ -95,10 +93,10 @@ declare module 'events' { } interface EventEmitter extends NodeJS.EventEmitter {} /** - * The `EventEmitter` class is defined and exposed by the `events` module: + * The `EventEmitter` class is defined and exposed by the `node:events` module: * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; * ``` * * All `EventEmitter`s emit the event `'newListener'` when new listeners are @@ -119,31 +117,28 @@ declare module 'events' { * semantics and does not listen to the `'error'` event. * * ```js - * const { once, EventEmitter } = require('events'); + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; * - * async function run() { - * const ee = new EventEmitter(); + * const ee = new EventEmitter(); * - * process.nextTick(() => { - * ee.emit('myevent', 42); - * }); + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); * - * const [value] = await once(ee, 'myevent'); - * console.log(value); + * const [value] = await once(ee, 'myevent'); + * console.log(value); * - * const err = new Error('kaboom'); - * process.nextTick(() => { - * ee.emit('error', err); - * }); + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); * - * try { - * await once(ee, 'myevent'); - * } catch (err) { - * console.log('error happened', err); - * } + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('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 @@ -151,13 +146,13 @@ declare module 'events' { * special handling: * * ```js - * const { EventEmitter, once } = require('events'); + * import { EventEmitter, once } from 'node:events'; * * const ee = new EventEmitter(); * * once(ee, 'error') * .then(([err]) => console.log('ok', err.message)) - * .catch((err) => console.log('error', err.message)); + * .catch((err) => console.error('error', err.message)); * * ee.emit('error', new Error('boom')); * @@ -167,7 +162,7 @@ declare module 'events' { * An `AbortSignal` can be used to cancel waiting for the event: * * ```js - * const { EventEmitter, once } = require('events'); + * import { EventEmitter, once } from 'node:events'; * * const ee = new EventEmitter(); * const ac = new AbortController(); @@ -195,25 +190,24 @@ declare module 'events' { static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; /** * ```js - * const { on, EventEmitter } = require('events'); + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; * - * (async () => { - * const ee = new EventEmitter(); + * const ee = new EventEmitter(); * - * // Emit later on - * process.nextTick(() => { - * ee.emit('foo', 'bar'); - * ee.emit('foo', 42); - * }); + * // 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 - * })(); + * 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 @@ -224,7 +218,9 @@ declare module 'events' { * An `AbortSignal` can be used to cancel waiting on events: * * ```js - * const { on, EventEmitter } = require('events'); + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * * const ac = new AbortController(); * * (async () => { @@ -256,7 +252,8 @@ declare module 'events' { * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. * * ```js - * const { EventEmitter, listenerCount } = require('events'); + * import { EventEmitter, listenerCount } from 'node:events'; + * * const myEmitter = new EventEmitter(); * myEmitter.on('event', () => {}); * myEmitter.on('event', () => {}); @@ -279,19 +276,19 @@ declare module 'events' { * event target. This is useful for debugging and diagnostic purposes. * * ```js - * const { getEventListeners, EventEmitter } = require('events'); + * import { getEventListeners, EventEmitter } from 'node:events'; * * { * const ee = new EventEmitter(); * const listener = () => console.log('Events are fun'); * ee.on('foo', listener); - * getEventListeners(ee, 'foo'); // [listener] + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] * } * { * const et = new EventTarget(); * const listener = () => console.log('Events are fun'); * et.addEventListener('foo', listener); - * getEventListeners(et, 'foo'); // [listener] + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] * } * ``` * @since v15.2.0, v14.17.0 @@ -299,10 +296,7 @@ declare module 'events' { static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; /** * ```js - * const { - * setMaxListeners, - * EventEmitter - * } = require('events'); + * import { setMaxListeners, EventEmitter } from 'node:events'; * * const target = new EventTarget(); * const emitter = new EventEmitter(); @@ -316,21 +310,63 @@ declare module 'events' { */ 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. + * 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 + * 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. + * @since v13.6.0, v12.17.0 */ static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ static readonly captureRejectionSymbol: unique symbol; /** - * Sets or gets the default captureRejection value for all emitters. + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 */ - // TODO: These should be described using static getter/setter pairs: static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners`property can be used. If this value is not a positive number, a `RangeError`is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_`EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ static defaultMaxListeners: number; } import internal = require('node:events'); @@ -370,6 +406,7 @@ declare module 'events' { * event listener to the beginning of the listeners array. * * ```js + * import { EventEmitter } from 'node:events'; * const myEE = new EventEmitter(); * myEE.on('foo', () => console.log('a')); * myEE.prependListener('foo', () => console.log('b')); @@ -399,6 +436,7 @@ declare module 'events' { * event listener to the beginning of the listeners array. * * ```js + * import { EventEmitter } from 'node:events'; * const myEE = new EventEmitter(); * myEE.once('foo', () => console.log('a')); * myEE.prependOnceListener('foo', () => console.log('b')); @@ -434,6 +472,8 @@ declare module 'events' { * will not remove them from`emit()` in progress. Subsequent events behave as expected. * * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} * const myEmitter = new MyEmitter(); * * const callbackA = () => { @@ -474,6 +514,7 @@ declare module 'events' { * recently added instance. In the example the `once('ping')`listener is removed: * * ```js + * import { EventEmitter } from 'node:events'; * const ee = new EventEmitter(); * * function pong() { @@ -542,6 +583,7 @@ declare module 'events' { * including any wrappers (such as those created by `.once()`). * * ```js + * import { EventEmitter } from 'node:events'; * const emitter = new EventEmitter(); * emitter.once('log', () => console.log('log once')); * @@ -574,7 +616,7 @@ declare module 'events' { * Returns `true` if the event had listeners, `false` otherwise. * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; * const myEmitter = new EventEmitter(); * * // First listener @@ -609,11 +651,14 @@ declare module 'events' { */ emit(eventName: string | symbol, ...args: any[]): boolean; /** - * Returns the number of listeners listening to the event named `eventName`. + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. * @since v3.2.0 * @param eventName The name of the event being listened for + * @param listener The event handler function */ - listenerCount(eventName: string | symbol): number; + listenerCount(eventName: string | symbol, listener?: Function): 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 @@ -653,7 +698,8 @@ declare module 'events' { * listeners. The values in the array are strings or `Symbol`s. * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; + * * const myEE = new EventEmitter(); * myEE.on('foo', () => {}); * myEE.on('bar', () => {}); diff --git a/node_modules/@types/node/ts4.8/fs.d.ts b/node_modules/@types/node/ts4.8/fs.d.ts index 75c53fb..00f1cf3 100644 --- a/node_modules/@types/node/ts4.8/fs.d.ts +++ b/node_modules/@types/node/ts4.8/fs.d.ts @@ -1,22 +1,22 @@ /** - * The `fs` module enables interacting with the file system in a + * The `node:fs` module enables interacting with the file system in a * way modeled on standard POSIX functions. * * To use the promise-based APIs: * * ```js - * import * as fs from 'fs/promises'; + * import * as fs from 'node:fs/promises'; * ``` * * To use the callback and sync APIs: * * ```js - * import * as fs from 'fs'; + * import * as fs from 'node:fs'; * ``` * * All file system operations have synchronous, callback, and promise-based * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/fs.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/fs.js) */ declare module 'fs' { import * as stream from 'node:stream'; @@ -73,7 +73,7 @@ declare module 'fs' { /** * A `fs.Stats` object provides information about a file. * - * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and * their synchronous counterparts are of this type. * If `bigint` in the `options` passed to those methods is true, the numeric values * will be `bigint` instead of `number`, and the object will contain additional @@ -131,6 +131,62 @@ declare module 'fs' { * @since v0.1.21 */ export class Stats {} + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } /** * A representation of a directory entry, which can be a file or a subdirectory * within the directory, as returned by reading from an `fs.Dir`. The @@ -184,6 +240,11 @@ declare module 'fs' { * @since v10.10.0 */ name: string; + /** + * The base path that this `fs.Dirent` object refers to. + * @since v20.1.0 + */ + path: string; } /** * A class representing a directory stream. @@ -191,7 +252,7 @@ declare module 'fs' { * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. * * ```js - * import { opendir } from 'fs/promises'; + * import { opendir } from 'node:fs/promises'; * * try { * const dir = await opendir('./'); @@ -494,7 +555,7 @@ declare module 'fs' { * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). * * ```js - * import { rename } from 'fs'; + * import { rename } from 'node:fs'; * * rename('oldFile.txt', 'newFile.txt', (err) => { * if (err) throw err; @@ -527,7 +588,7 @@ declare module 'fs' { * first argument. In this case, `fs.ftruncate()` is called. * * ```js - * import { truncate } from 'fs'; + * import { truncate } from 'node:fs'; * // Assuming that 'path/file.txt' is a regular file. * truncate('path/file.txt', (err) => { * if (err) throw err; @@ -579,7 +640,7 @@ declare module 'fs' { * file: * * ```js - * import { open, close, ftruncate } from 'fs'; + * import { open, close, ftruncate } from 'node:fs'; * * function closeFd(fd) { * close(fd, (err) => { @@ -736,7 +797,7 @@ declare module 'fs' { * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. * * ```js - * import { chmod } from 'fs'; + * import { chmod } from 'node:fs'; * * chmod('my_file.txt', 0o775, (err) => { * if (err) throw err; @@ -818,7 +879,10 @@ declare module 'fs' { * * In case of an error, the `err.code` will be one of `Common System Errors`. * - * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. * Instead, user code should open/read/write the file directly and handle the * error raised if the file is not available. * @@ -835,7 +899,7 @@ declare module 'fs' { * The next program will check for the stats of the given paths: * * ```js - * import { stat } from 'fs'; + * import { stat } from 'node:fs'; * * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; * @@ -1081,6 +1145,72 @@ declare module 'fs' { ): Promise; function __promisify__(path: PathLike, options?: StatOptions): Promise; } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void + ): void; + export function statfs(path: PathLike, options: StatFsOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + } + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + } + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; /** * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -1114,14 +1244,15 @@ declare module 'fs' { * * The `type` argument is only available on Windows and ignored on other platforms. * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is - * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If - * the `target` does not exist, `'file'` will be used. Windows junction points - * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. * - * Relative targets are relative to the link’s parent directory. + * Relative targets are relative to the link's parent directory. * * ```js - * import { symlink } from 'fs'; + * import { symlink } from 'node:fs'; * * symlink('./mew', './mewtwo', callback); * ``` @@ -1136,6 +1267,7 @@ declare module 'fs' { * └── mewtwo -> ./mew * ``` * @since v0.1.31 + * @param [type='null'] */ export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; /** @@ -1161,6 +1293,7 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link symlink}. * @since v0.1.31 + * @param [type='null'] */ export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; /** @@ -1238,7 +1371,7 @@ declare module 'fs' { */ export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; /** - * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and * symbolic links. * * A canonical pathname is not necessarily unique. Hard links and bind mounts can @@ -1352,7 +1485,7 @@ declare module 'fs' { * possible exception are given to the completion callback. * * ```js - * import { unlink } from 'fs'; + * import { unlink } from 'node:fs'; * // Assuming that 'path/file.txt' is a regular file. * unlink('path/file.txt', (err) => { * if (err) throw err; @@ -1499,18 +1632,19 @@ declare module 'fs' { * * The callback is given a possible exception and, if `recursive` is `true`, the * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was - * created. + * created (for instance, if it was previously created). * * The optional `options` argument can be an integer specifying `mode` (permission * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that * exists results in an error only - * when `recursive` is false. + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. * * ```js - * import { mkdir } from 'fs'; + * import { mkdir } from 'node:fs'; * - * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. - * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { * if (err) throw err; * }); * ``` @@ -1519,7 +1653,7 @@ declare module 'fs' { * result in an error: * * ```js - * import { mkdir } from 'fs'; + * import { mkdir } from 'node:fs'; * * mkdir('/', { recursive: true }, (err) => { * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] @@ -1651,9 +1785,11 @@ declare module 'fs' { * object with an `encoding` property specifying the character encoding to use. * * ```js - * import { mkdtemp } from 'fs'; + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; * - * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { * if (err) throw err; * console.log(directory); * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 @@ -1663,11 +1799,11 @@ declare module 'fs' { * The `fs.mkdtemp()` method will append the six randomly selected characters * directly to the `prefix` string. For instance, given a directory `/tmp`, if the * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator - * (`require('path').sep`). + * (`require('node:path').sep`). * * ```js - * import { tmpdir } from 'os'; - * import { mkdtemp } from 'fs'; + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; * * // The parent directory for the new temporary directory * const tmpDir = tmpdir(); @@ -1682,7 +1818,7 @@ declare module 'fs' { * }); * * // This method is *CORRECT*: - * import { sep } from 'path'; + * import { sep } from 'node:path'; * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { * if (err) throw err; * console.log(directory); @@ -1781,6 +1917,7 @@ declare module 'fs' { | { encoding: BufferEncoding | null; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | BufferEncoding | undefined @@ -1798,6 +1935,7 @@ declare module 'fs' { | { encoding: 'buffer'; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | 'buffer', callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void @@ -1812,6 +1950,7 @@ declare module 'fs' { options: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | undefined @@ -1832,6 +1971,7 @@ declare module 'fs' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; + recursive?: boolean | undefined; }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void ): void; @@ -1847,6 +1987,7 @@ declare module 'fs' { | { encoding: BufferEncoding | null; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | BufferEncoding | null @@ -1863,6 +2004,7 @@ declare module 'fs' { | { encoding: 'buffer'; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } ): Promise; /** @@ -1875,6 +2017,7 @@ declare module 'fs' { options?: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | null @@ -1888,6 +2031,7 @@ declare module 'fs' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; + recursive?: boolean | undefined; } ): Promise; } @@ -1910,6 +2054,7 @@ declare module 'fs' { | { encoding: BufferEncoding | null; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | BufferEncoding | null @@ -1925,6 +2070,7 @@ declare module 'fs' { | { encoding: 'buffer'; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | 'buffer' ): Buffer[]; @@ -1938,6 +2084,7 @@ declare module 'fs' { options?: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | null @@ -1951,6 +2098,7 @@ declare module 'fs' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; + recursive?: boolean | undefined; } ): Dirent[]; /** @@ -2010,7 +2158,6 @@ declare module 'fs' { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - export namespace open { /** * Asynchronous open(2) - open and possibly create a file. @@ -2035,7 +2182,7 @@ declare module 'fs' { * The `atime` and `mtime` arguments follow these rules: * * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. - * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. * @since v0.4.2 */ export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; @@ -2121,6 +2268,9 @@ declare module 'fs' { * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] */ export function write( fd: number, @@ -2225,6 +2375,9 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link write}. * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] * @return The number of bytes written. */ export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; @@ -2330,6 +2483,7 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link read}. * @since v0.1.21 + * @param [position='null'] */ export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number; /** @@ -2341,7 +2495,7 @@ declare module 'fs' { * Asynchronously reads the entire contents of a file. * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * readFile('/etc/passwd', (err, data) => { * if (err) throw err; @@ -2357,7 +2511,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * readFile('/etc/passwd', 'utf8', callback); * ``` @@ -2367,7 +2521,7 @@ declare module 'fs' { * will be returned. * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * // macOS, Linux, and Windows * readFile('', (err, data) => { @@ -2384,7 +2538,7 @@ declare module 'fs' { * request is aborted the callback is called with an `AbortError`: * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * const controller = new AbortController(); * const signal = controller.signal; @@ -2517,7 +2671,7 @@ declare module 'fs' { * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. * * ```js - * import { readFileSync } from 'fs'; + * import { readFileSync } from 'node:fs'; * * // macOS, Linux, and Windows * readFileSync(''); @@ -2588,8 +2742,8 @@ declare module 'fs' { * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js - * import { writeFile } from 'fs'; - * import { Buffer } from 'buffer'; + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; * * const data = new Uint8Array(Buffer.from('Hello Node.js')); * writeFile('message.txt', data, (err) => { @@ -2601,7 +2755,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { writeFile } from 'fs'; + * import { writeFile } from 'node:fs'; * * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); * ``` @@ -2619,8 +2773,8 @@ declare module 'fs' { * to be written. * * ```js - * import { writeFile } from 'fs'; - * import { Buffer } from 'buffer'; + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; * * const controller = new AbortController(); * const { signal } = controller; @@ -2678,7 +2832,7 @@ declare module 'fs' { * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js - * import { appendFile } from 'fs'; + * import { appendFile } from 'node:fs'; * * appendFile('message.txt', 'data to append', (err) => { * if (err) throw err; @@ -2689,7 +2843,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { appendFile } from 'fs'; + * import { appendFile } from 'node:fs'; * * appendFile('message.txt', 'data to append', 'utf8', callback); * ``` @@ -2699,7 +2853,7 @@ declare module 'fs' { * not be closed automatically. * * ```js - * import { open, close, appendFile } from 'fs'; + * import { open, close, appendFile } from 'node:fs'; * * function closeFd(fd) { * close(fd, (err) => { @@ -2754,7 +2908,7 @@ declare module 'fs' { * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js - * import { appendFileSync } from 'fs'; + * import { appendFileSync } from 'node:fs'; * * try { * appendFileSync('message.txt', 'data to append'); @@ -2767,7 +2921,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { appendFileSync } from 'fs'; + * import { appendFileSync } from 'node:fs'; * * appendFileSync('message.txt', 'data to append', 'utf8'); * ``` @@ -2777,7 +2931,7 @@ declare module 'fs' { * not be closed automatically. * * ```js - * import { openSync, closeSync, appendFileSync } from 'fs'; + * import { openSync, closeSync, appendFileSync } from 'node:fs'; * * let fd; * @@ -2859,7 +3013,7 @@ declare module 'fs' { * stat object: * * ```js - * import { watchFile } from 'fs'; + * import { watchFile } from 'node:fs'; * * watchFile('message.text', (curr, prev) => { * console.log(`the current mtime is: ${curr.mtime}`); @@ -2899,7 +3053,7 @@ declare module 'fs' { bigint?: false | undefined; }) | undefined, - listener: (curr: Stats, prev: Stats) => void + listener: StatsListener ): StatWatcher; export function watchFile( filename: PathLike, @@ -2908,13 +3062,13 @@ declare module 'fs' { bigint: true; }) | undefined, - listener: (curr: BigIntStats, prev: BigIntStats) => void + listener: BigIntStatsListener ): StatWatcher; /** * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. */ - export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): StatWatcher; + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; /** * Stop watching for changes on `filename`. If `listener` is specified, only that * particular listener is removed. Otherwise, _all_ listeners are removed, @@ -2927,14 +3081,17 @@ declare module 'fs' { * @since v0.1.31 * @param listener Optional, a listener previously attached using `fs.watchFile()` */ - export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; export interface WatchOptions extends Abortable { encoding?: BufferEncoding | 'buffer' | undefined; persistent?: boolean | undefined; recursive?: boolean | undefined; } export type WatchEventType = 'rename' | 'change'; - export type WatchListener = (event: WatchEventType, filename: T) => void; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; /** * Watch for changes on `filename`, where `filename` is either a file or a * directory. @@ -2992,7 +3149,7 @@ declare module 'fs' { * Then call the `callback` argument with either true or false: * * ```js - * import { exists } from 'fs'; + * import { exists } from 'node:fs'; * * exists('/etc/passwd', (e) => { * console.log(e ? 'it exists' : 'no passwd!'); @@ -3004,7 +3161,7 @@ declare module 'fs' { * has only one boolean parameter. This is one reason `fs.access()` is recommended * instead of `fs.exists()`. * - * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing * so introduces a race condition, since other processes may change the file's * state between the two calls. Instead, user code should open/read/write the * file directly and handle the error raised if the file does not exist. @@ -3012,7 +3169,7 @@ declare module 'fs' { * **write (NOT RECOMMENDED)** * * ```js - * import { exists, open, close } from 'fs'; + * import { exists, open, close } from 'node:fs'; * * exists('myfile', (e) => { * if (e) { @@ -3036,7 +3193,7 @@ declare module 'fs' { * **write (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * open('myfile', 'wx', (err, fd) => { * if (err) { * if (err.code === 'EEXIST') { @@ -3060,7 +3217,7 @@ declare module 'fs' { * **read (NOT RECOMMENDED)** * * ```js - * import { open, close, exists } from 'fs'; + * import { open, close, exists } from 'node:fs'; * * exists('myfile', (e) => { * if (e) { @@ -3084,7 +3241,7 @@ declare module 'fs' { * **read (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * * open('myfile', 'r', (err, fd) => { * if (err) { @@ -3110,7 +3267,7 @@ declare module 'fs' { * file; the "recommended" examples are better because they use the file directly * and handle the error, if any. * - * In general, check for the existence of a file only if the file won’t be + * In general, check for the existence of a file only if the file won't be * used directly, for example when its existence is a signal from another * process. * @since v0.0.2 @@ -3135,7 +3292,7 @@ declare module 'fs' { * Node.js callbacks. `fs.existsSync()` does not use a callback. * * ```js - * import { existsSync } from 'fs'; + * import { existsSync } from 'node:fs'; * * if (existsSync('/etc/passwd')) * console.log('The path exists.'); @@ -3269,7 +3426,7 @@ declare module 'fs' { * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. * * ```js - * import { access, constants } from 'fs'; + * import { access, constants } from 'node:fs'; * * const file = 'package.json'; * @@ -3294,7 +3451,7 @@ declare module 'fs' { * }); * ``` * - * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing * so introduces a race condition, since other processes may change the file's * state between the two calls. Instead, user code should open/read/write the * file directly and handle the error raised if the file is not accessible. @@ -3302,7 +3459,7 @@ declare module 'fs' { * **write (NOT RECOMMENDED)** * * ```js - * import { access, open, close } from 'fs'; + * import { access, open, close } from 'node:fs'; * * access('myfile', (err) => { * if (!err) { @@ -3327,7 +3484,7 @@ declare module 'fs' { * **write (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * * open('myfile', 'wx', (err, fd) => { * if (err) { @@ -3352,7 +3509,7 @@ declare module 'fs' { * **read (NOT RECOMMENDED)** * * ```js - * import { access, open, close } from 'fs'; + * import { access, open, close } from 'node:fs'; * access('myfile', (err) => { * if (err) { * if (err.code === 'ENOENT') { @@ -3380,7 +3537,7 @@ declare module 'fs' { * **read (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * * open('myfile', 'r', (err, fd) => { * if (err) { @@ -3442,7 +3599,7 @@ declare module 'fs' { * the method will return `undefined`. * * ```js - * import { accessSync, constants } from 'fs'; + * import { accessSync, constants } from 'node:fs'; * * try { * accessSync('etc/passwd', constants.R_OK | constants.W_OK); @@ -3472,8 +3629,8 @@ declare module 'fs' { end?: number | undefined; } /** - * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream - * returned by this method has a default `highWaterMark` of 64 kb. + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. * * `options` can include `start` and `end` values to read a range of bytes from * the file instead of the entire file. Both `start` and `end` are inclusive and @@ -3499,7 +3656,7 @@ declare module 'fs' { * also required. * * ```js - * import { createReadStream } from 'fs'; + * import { createReadStream } from 'node:fs'; * * // Create a stream from some character device. * const stream = createReadStream('/dev/input/event0'); @@ -3527,7 +3684,7 @@ declare module 'fs' { * An example to read the last 10 bytes of a file which is 100 bytes long: * * ```js - * import { createReadStream } from 'fs'; + * import { createReadStream } from 'node:fs'; * * createReadStream('sample.txt', { start: 90, end: 99 }); * ``` @@ -3551,7 +3708,7 @@ declare module 'fs' { * By default, the stream will emit a `'close'` event after it has been * destroyed. Set the `emitClose` option to `false` to change this behavior. * - * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev`, and `close`. Overriding `write()`without `writev()` can reduce * performance as some optimizations (`_writev()`) * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. @@ -3606,7 +3763,7 @@ declare module 'fs' { * copy-on-write, then the operation will fail. * * ```js - * import { copyFile, constants } from 'fs'; + * import { copyFile, constants } from 'node:fs'; * * function callback(err) { * if (err) throw err; @@ -3649,7 +3806,7 @@ declare module 'fs' { * copy-on-write, then the operation will fail. * * ```js - * import { copyFileSync, constants } from 'fs'; + * import { copyFileSync, constants } from 'node:fs'; * * // destination.txt will be created or overwritten by default. * copyFileSync('source.txt', 'destination.txt'); @@ -3682,6 +3839,7 @@ declare module 'fs' { * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v12.9.0 + * @param [position='null'] */ export function writev(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; export function writev( @@ -3701,6 +3859,7 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link writev}. * @since v12.9.0 + * @param [position='null'] * @return The number of bytes written. */ export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; @@ -3717,6 +3876,7 @@ declare module 'fs' { * If this method is invoked as its `util.promisify()` ed version, it returns * a promise for an `Object` with `bytesRead` and `buffers` properties. * @since v13.13.0, v12.17.0 + * @param [position='null'] */ export function readv(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; export function readv( @@ -3736,10 +3896,14 @@ declare module 'fs' { * For detailed information, see the documentation of the asynchronous version of * this API: {@link readv}. * @since v13.13.0, v12.17.0 + * @param [position='null'] * @return The number of bytes read. */ export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; export interface OpenDirOptions { + /** + * @default 'utf8' + */ encoding?: BufferEncoding | undefined; /** * Number of directory entries that are buffered @@ -3748,6 +3912,10 @@ declare module 'fs' { * @default 32 */ bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean; } /** * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). @@ -3810,6 +3978,10 @@ declare module 'fs' { * @default true */ force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; /** * When `true` timestamps from `src` will * be preserved. diff --git a/node_modules/@types/node/ts4.8/fs/promises.d.ts b/node_modules/@types/node/ts4.8/fs/promises.d.ts index aca2fd5..93e705e 100644 --- a/node_modules/@types/node/ts4.8/fs/promises.d.ts +++ b/node_modules/@types/node/ts4.8/fs/promises.d.ts @@ -14,6 +14,7 @@ declare module 'fs/promises' { import { ReadableStream } from 'node:stream/web'; import { BigIntStats, + BigIntStatsFs, BufferEncodingOption, constants as fsConstants, CopyOptions, @@ -30,7 +31,9 @@ declare module 'fs/promises' { RmDirOptions, RmOptions, StatOptions, + StatFsOptions, Stats, + StatsFs, TimeLike, WatchEventType, WatchOptions, @@ -38,10 +41,9 @@ declare module 'fs/promises' { WriteVResult, } from 'node:fs'; import { Interface as ReadlineInterface } from 'node:readline'; - interface FileChangeInfo { eventType: WatchEventType; - filename: T; + filename: T | null; } interface FlagAndOpenMode { mode?: Mode | undefined; @@ -112,8 +114,8 @@ declare module 'fs/promises' { */ chmod(mode: Mode): Promise; /** - * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream - * returned by this method has a default `highWaterMark` of 64 kb. + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. * * `options` can include `start` and `end` values to read a range of bytes from * the file instead of the entire file. Both `start` and `end` are inclusive and @@ -131,7 +133,7 @@ declare module 'fs/promises' { * destroyed. Set the `emitClose` option to `false` to change this behavior. * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * const fd = await open('/dev/input/event0'); * // Create a stream from some character device. @@ -157,7 +159,7 @@ declare module 'fs/promises' { * An example to read the last 10 bytes of a file which is 100 bytes long: * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * const fd = await open('sample.txt'); * fd.createReadStream({ start: 90, end: 99 }); @@ -196,7 +198,7 @@ declare module 'fs/promises' { * device. The specific implementation is operating system and device specific. * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. * @since v10.0.0 - * @return Fufills with `undefined` upon success. + * @return Fulfills with `undefined` upon success. */ sync(): Promise; /** @@ -217,11 +219,13 @@ declare module 'fs/promises' { /** * Returns a `ReadableStream` that may be used to read the files data. * - * An error will be thrown if this method is called more than once or is called after the `FileHandle` is closed - * or closing. + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. * * ```js - * import { open } from 'node:fs/promises'; + * import { + * open, + * } from 'node:fs/promises'; * * const file = await open('./some/file/to/read'); * @@ -231,8 +235,8 @@ declare module 'fs/promises' { * await file.close(); * ``` * - * While the `ReadableStream` will read the file to completion, it will not close the `FileHandle` automatically. User code must still call the `fileHandle.close()` method. - * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. * @since v17.0.0 * @experimental */ @@ -286,7 +290,8 @@ declare module 'fs/promises' { | null ): Promise; /** - * Convenience method to create a `readline` interface and stream over the file. For example: + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. * * ```js * import { open } from 'node:fs/promises'; @@ -297,9 +302,7 @@ declare module 'fs/promises' { * console.log(line); * } * ``` - * * @since v18.11.0 - * @param options See `filehandle.createReadStream()` for the options. */ readLines(options?: CreateReadStreamOptions): ReadlineInterface; /** @@ -326,7 +329,7 @@ declare module 'fs/promises' { * The following example retains only the first four bytes of the file: * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * let filehandle = null; * try { @@ -353,7 +356,7 @@ declare module 'fs/promises' { utimes(atime: TimeLike, mtime: TimeLike): Promise; /** * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an - * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. * The promise is resolved with no arguments upon success. * @@ -383,10 +386,10 @@ declare module 'fs/promises' { * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v10.0.0 - * @param [offset=0] The start position from within `buffer` where the data to write begins. + * @param offset The start position from within `buffer` where the data to write begins. * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. - * @param position The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. - * See the POSIX pwrite(2) documentation for more detail. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. */ write( buffer: TBuffer, @@ -417,14 +420,14 @@ declare module 'fs/promises' { * The kernel ignores the position argument and always appends the data to * the end of the file. * @since v12.9.0 - * @param position The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current * position. */ writev(buffers: ReadonlyArray, position?: number): Promise; /** * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s * @since v13.13.0, v12.17.0 - * @param position The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. * @return Fulfills upon success an object containing two properties: */ readv(buffers: ReadonlyArray, position?: number): Promise; @@ -433,7 +436,7 @@ declare module 'fs/promises' { * complete. * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * let filehandle; * try { @@ -447,9 +450,7 @@ declare module 'fs/promises' { */ close(): Promise; } - const constants: typeof fsConstants; - /** * Tests a user's permissions for the file or directory specified by `path`. * The `mode` argument is an optional integer that specifies the accessibility @@ -463,8 +464,7 @@ declare module 'fs/promises' { * written by the current process. * * ```js - * import { access } from 'fs/promises'; - * import { constants } from 'fs'; + * import { access, constants } from 'node:fs/promises'; * * try { * await access('/etc/passwd', constants.R_OK | constants.W_OK); @@ -493,14 +493,13 @@ declare module 'fs/promises' { * will be made to remove the destination. * * ```js - * import { constants } from 'fs'; - * import { copyFile } from 'fs/promises'; + * import { copyFile, constants } from 'node:fs/promises'; * * try { * await copyFile('source.txt', 'destination.txt'); * console.log('source.txt was copied to destination.txt'); * } catch { - * console.log('The file could not be copied'); + * console.error('The file could not be copied'); * } * * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. @@ -508,7 +507,7 @@ declare module 'fs/promises' { * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); * console.log('source.txt was copied to destination.txt'); * } catch { - * console.log('The file could not be copied'); + * console.error('The file could not be copied'); * } * ``` * @since v10.0.0 @@ -570,6 +569,19 @@ declare module 'fs/promises' { * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory * that exists results in a * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` * @since v10.0.0 * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. */ @@ -612,7 +624,7 @@ declare module 'fs/promises' { * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. * * ```js - * import { readdir } from 'fs/promises'; + * import { readdir } from 'node:fs/promises'; * * try { * const files = await readdir(path); @@ -630,6 +642,7 @@ declare module 'fs/promises' { options?: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | null @@ -645,6 +658,7 @@ declare module 'fs/promises' { | { encoding: 'buffer'; withFileTypes?: false | undefined; + recursive?: boolean | undefined; } | 'buffer' ): Promise; @@ -658,6 +672,7 @@ declare module 'fs/promises' { options?: | (ObjectEncodingOptions & { withFileTypes?: false | undefined; + recursive?: boolean | undefined; }) | BufferEncoding | null @@ -671,6 +686,7 @@ declare module 'fs/promises' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; + recursive?: boolean | undefined; } ): Promise; /** @@ -700,11 +716,13 @@ declare module 'fs/promises' { /** * Creates a symbolic link. * - * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path - * to be absolute. When using `'junction'`, the `target` argument will + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will * automatically be normalized to absolute path. * @since v10.0.0 - * @param [type='file'] + * @param [type='null'] * @return Fulfills with `undefined` upon success. */ function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; @@ -745,6 +763,23 @@ declare module 'fs/promises' { } ): Promise; function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + } + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + } + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; /** * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. * @since v10.0.0 @@ -800,7 +835,7 @@ declare module 'fs/promises' { * * * Values can be either numbers representing Unix epoch time, `Date`s, or a * numeric string like `'123456789.0'`. - * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. * @since v10.0.0 * @return Fulfills with `undefined` upon success. */ @@ -845,10 +880,12 @@ declare module 'fs/promises' { * object with an `encoding` property specifying the character encoding to use. * * ```js - * import { mkdtemp } from 'fs/promises'; + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; * * try { - * await mkdtemp(path.join(os.tmpdir(), 'foo-')); + * await mkdtemp(join(tmpdir(), 'foo-')); * } catch (err) { * console.error(err); * } @@ -857,9 +894,9 @@ declare module 'fs/promises' { * The `fsPromises.mkdtemp()` method will append the six randomly selected * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing * platform-specific path separator - * (`require('path').sep`). + * (`require('node:path').sep`). * @since v10.0.0 - * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + * @return Fulfills with a string containing the file system path of the newly created temporary directory. */ function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** @@ -876,7 +913,7 @@ declare module 'fs/promises' { function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an - * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. * * The `encoding` option is ignored if `data` is a buffer. @@ -899,8 +936,8 @@ declare module 'fs/promises' { * to be written. * * ```js - * import { writeFile } from 'fs/promises'; - * import { Buffer } from 'buffer'; + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; * * try { * const controller = new AbortController(); @@ -963,11 +1000,25 @@ declare module 'fs/promises' { * with an error. On FreeBSD, a representation of the directory's contents will be * returned. * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a * request is aborted the promise returned is rejected with an `AbortError`: * * ```js - * import { readFile } from 'fs/promises'; + * import { readFile } from 'node:fs/promises'; * * try { * const controller = new AbortController(); @@ -1046,7 +1097,7 @@ declare module 'fs/promises' { * Example using async iteration: * * ```js - * import { opendir } from 'fs/promises'; + * import { opendir } from 'node:fs/promises'; * * try { * const dir = await opendir('./'); @@ -1067,7 +1118,7 @@ declare module 'fs/promises' { * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. * * ```js - * const { watch } = require('fs/promises'); + * const { watch } = require('node:fs/promises'); * * const ac = new AbortController(); * const { signal } = ac; diff --git a/node_modules/@types/node/ts4.8/globals.d.ts b/node_modules/@types/node/ts4.8/globals.d.ts index f401d95..7414561 100644 --- a/node_modules/@types/node/ts4.8/globals.d.ts +++ b/node_modules/@types/node/ts4.8/globals.d.ts @@ -53,7 +53,7 @@ interface AbortController { /** * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. */ - abort(): void; + abort(reason?: any): void; } /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ @@ -62,18 +62,26 @@ interface AbortSignal extends EventTarget { * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ readonly aborted: boolean; + readonly reason: any; + onabort: null | ((this: AbortSignal, event: Event) => any); + throwIfAborted(): void; } -declare var AbortController: { - prototype: AbortController; - new(): AbortController; -}; +declare var AbortController: typeof globalThis extends {onmessage: any; AbortController: infer T} + ? T + : { + prototype: AbortController; + new(): AbortController; + }; -declare var AbortSignal: { - prototype: AbortSignal; - new(): AbortSignal; - // TODO: Add abort() static -}; +declare var AbortSignal: typeof globalThis extends {onmessage: any; AbortSignal: infer T} + ? T + : { + prototype: AbortSignal; + new(): AbortSignal; + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; //#endregion borrowed //#region ArrayLike.at() @@ -87,6 +95,7 @@ interface RelativeIndexable { } interface String extends RelativeIndexable {} interface Array extends RelativeIndexable {} +interface ReadonlyArray extends RelativeIndexable {} interface Int8Array extends RelativeIndexable {} interface Uint8Array extends RelativeIndexable {} interface Uint8ClampedArray extends RelativeIndexable {} @@ -151,7 +160,7 @@ declare namespace NodeJS { /** * Name of the script [if this function was defined in a script] */ - getFileName(): string | null; + getFileName(): string | undefined; /** * Current line number [if this function was defined in a script] diff --git a/node_modules/@types/node/ts4.8/http.d.ts b/node_modules/@types/node/ts4.8/http.d.ts index e14de6c..cb50335 100644 --- a/node_modules/@types/node/ts4.8/http.d.ts +++ b/node_modules/@types/node/ts4.8/http.d.ts @@ -1,5 +1,5 @@ /** - * To use the HTTP server and client one must `require('http')`. + * To use the HTTP server and client one must `require('node:http')`. * * The HTTP interfaces in Node.js are designed to support many features * of the protocol which have been traditionally difficult to use. @@ -37,13 +37,14 @@ * 'Host', 'example.com', * 'accepT', '*' ] * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http.js) */ declare module 'http' { import * as stream from 'node:stream'; import { URL } from 'node:url'; - import { TcpSocketConnectOpts, Socket, Server as NetServer, LookupFunction } from 'node:net'; import { LookupOptions } from 'node:dns'; + import { EventEmitter } from 'node:events'; + import { TcpSocketConnectOpts, Socket, Server as NetServer, LookupFunction } from 'node:net'; // incoming headers will never contain number interface IncomingHttpHeaders extends NodeJS.Dict { accept?: string | undefined; @@ -144,6 +145,7 @@ declare module 'http' { socketPath?: string | undefined; timeout?: number | undefined; uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean; } interface ServerOptions< Request extends typeof IncomingMessage = typeof IncomingMessage, @@ -164,6 +166,12 @@ declare module 'http' { * @since v18.0.0 */ requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean; /** * The number of milliseconds of inactivity a server needs to wait for additional incoming data, * after it has finished writing the last response, before a socket will be destroyed. @@ -177,6 +185,13 @@ declare module 'http' { * @default 30000 */ connectionsCheckingInterval?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; /** * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. * Using the insecure parser should be avoided. @@ -322,7 +337,8 @@ declare module 'http' { */ closeAllConnections(): void; /** - * Closes all connections connected to this server which are not sending a request or waiting for a response. + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. * @since v18.2.0 */ closeIdleConnections(): void; @@ -334,15 +350,10 @@ declare module 'http' { addListener(event: 'checkContinue', listener: RequestListener): this; addListener(event: 'checkExpectation', listener: RequestListener): this; addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - addListener( - event: 'connect', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + addListener(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + addListener(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; addListener(event: 'request', listener: RequestListener): this; - addListener( - event: 'upgrade', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + addListener(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; emit(event: string, ...args: any[]): boolean; emit(event: 'close'): boolean; emit(event: 'connection', socket: Socket): boolean; @@ -360,6 +371,7 @@ declare module 'http' { ): boolean; emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; emit(event: 'connect', req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit(event: 'dropRequest', req: InstanceType, socket: stream.Duplex): boolean; emit( event: 'request', req: InstanceType, @@ -375,6 +387,7 @@ declare module 'http' { on(event: 'checkExpectation', listener: RequestListener): this; on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; on(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; on(event: 'request', listener: RequestListener): this; on(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; @@ -385,15 +398,10 @@ declare module 'http' { once(event: 'checkContinue', listener: RequestListener): this; once(event: 'checkExpectation', listener: RequestListener): this; once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - once( - event: 'connect', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + once(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + once(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; once(event: 'request', listener: RequestListener): this; - once( - event: 'upgrade', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + once(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: 'close', listener: () => void): this; prependListener(event: 'connection', listener: (socket: Socket) => void): this; @@ -402,15 +410,10 @@ declare module 'http' { prependListener(event: 'checkContinue', listener: RequestListener): this; prependListener(event: 'checkExpectation', listener: RequestListener): this; prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - prependListener( - event: 'connect', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + prependListener(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; prependListener(event: 'request', listener: RequestListener): this; - prependListener( - event: 'upgrade', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + prependListener(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: 'close', listener: () => void): this; prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; @@ -419,19 +422,14 @@ declare module 'http' { prependOnceListener(event: 'checkContinue', listener: RequestListener): this; prependOnceListener(event: 'checkExpectation', listener: RequestListener): this; prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - prependOnceListener( - event: 'connect', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + prependOnceListener(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'dropRequest', listener: (req: InstanceType, socket: stream.Duplex) => void): this; prependOnceListener(event: 'request', listener: RequestListener): this; - prependOnceListener( - event: 'upgrade', - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; + prependOnceListener(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; } /** - * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from - * the perspective of the participants of HTTP transaction. + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. * @since v0.1.17 */ class OutgoingMessage extends stream.Writable { @@ -450,7 +448,7 @@ declare module 'http' { */ readonly headersSent: boolean; /** - * Aliases of `outgoingMessage.socket` + * Alias of `outgoingMessage.socket`. * @since v0.3.0 * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. */ @@ -471,15 +469,33 @@ declare module 'http' { */ setTimeout(msecs: number, callback?: () => void): this; /** - * Sets a single header value for the header object. + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. * @since v0.4.0 * @param name Header name * @param value Header value */ setHeader(name: string, value: number | string | ReadonlyArray): this; /** - * Gets the value of HTTP header with the given name. If such a name doesn't - * exist in message, it will be `undefined`. + * Append a single header value for the header object. + * + * If the value is an array, this is equivalent of calling this method multiple + * times. + * + * If there were no previous value for the header, this is equivalent of calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | ReadonlyArray): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. * @since v0.4.0 * @param name Name of header */ @@ -492,8 +508,8 @@ declare module 'http' { * values. All header names are lowercase. * * The object returned by the `outgoingMessage.getHeaders()` method does - * not prototypically inherit from the JavaScript Object. This means that - * typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, * and others are not defined and will not work. * * ```js @@ -507,8 +523,8 @@ declare module 'http' { */ getHeaders(): OutgoingHttpHeaders; /** - * Returns an array of names of headers of the outgoing outgoingMessage. All - * names are lowercase. + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. * @since v7.7.0 */ getHeaderNames(): string[]; @@ -535,11 +551,11 @@ declare module 'http' { /** * Adds HTTP trailers (headers but at the end of the message) to the message. * - * Trailers are **only** be emitted if the message is chunked encoded. If not, - * the trailer will be silently discarded. + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. * * HTTP requires the `Trailer` header to be sent to emit trailers, - * with a list of header fields in its value, e.g. + * with a list of header field names in its value, e.g. * * ```js * message.writeHead(200, { 'Content-Type': 'text/plain', @@ -555,7 +571,7 @@ declare module 'http' { */ addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; /** - * Compulsorily flushes the message headers + * Flushes the message headers. * * For efficiency reason, Node.js normally buffers the message headers * until `outgoingMessage.end()` is called or the first chunk of message data @@ -563,7 +579,7 @@ declare module 'http' { * packet. * * It is usually desired (it saves a TCP round-trip), but not when the first - * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the message. * @since v1.6.0 */ flushHeaders(): void; @@ -603,6 +619,13 @@ declare module 'http' { * @since v0.11.8 */ statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length`header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; constructor(req: Request); assignSocket(socket: Socket): void; detachSocket(socket: Socket): void; @@ -619,7 +642,7 @@ declare module 'http' { * early hints message. The optional `callback` argument will be called when * the response message has been written. * - * Example: + * **Example** * * ```js * const earlyHintsLink = '; rel=preload; as=style'; @@ -633,15 +656,14 @@ declare module 'http' { * ]; * response.writeEarlyHints({ * 'link': earlyHintsLinks, - * 'x-trace-id': 'id for diagnostics' + * 'x-trace-id': 'id for diagnostics', * }); * * const earlyHintsCallback = () => console.log('early hints message sent'); * response.writeEarlyHints({ - * 'link': earlyHintsLinks + * 'link': earlyHintsLinks, * }, earlyHintsCallback); * ``` - * * @since v18.11.0 * @param hints An object containing the values of headers * @param callback Will be called when the response message has been written @@ -665,7 +687,7 @@ declare module 'http' { * response * .writeHead(200, { * 'Content-Length': Buffer.byteLength(body), - * 'Content-Type': 'text/plain' + * 'Content-Type': 'text/plain', * }) * .end(body); * ``` @@ -696,12 +718,12 @@ declare module 'http' { * }); * ``` * - * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js - * does not check whether `Content-Length` and the length of the body which has + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has * been transmitted are equal or not. * * Attempting to set a header field name or value that contains invalid characters - * will result in a `TypeError` being thrown. + * will result in a \[`Error`\]\[\] being thrown. * @since v0.1.30 */ writeHead( @@ -711,7 +733,7 @@ declare module 'http' { ): this; writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; /** - * Sends an HTTP/1.1 102 Processing message to the client, indicating that + * Sends a HTTP/1.1 102 Processing message to the client, indicating that * the request body should be sent. * @since v10.0.0 */ @@ -750,8 +772,11 @@ declare module 'http' { * * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. * - * Node.js does not check whether Content-Length and the length of the - * body which has been transmitted are equal or not. + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the`Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. * @since v0.1.17 */ class ClientRequest extends OutgoingMessage { @@ -778,7 +803,7 @@ declare module 'http' { * may run into a 'ECONNRESET' error. * * ```js - * const http = require('http'); + * const http = require('node:http'); * * // Server has a 5 seconds keep-alive timeout by default * http @@ -802,7 +827,7 @@ declare module 'http' { * automatic error retry base on it. * * ```js - * const http = require('http'); + * const http = require('node:http'); * const agent = new http.Agent({ keepAlive: true }); * * function retriableRequest() { @@ -881,19 +906,13 @@ declare module 'http' { * @deprecated */ addListener(event: 'abort', listener: () => void): this; - addListener( - event: 'connect', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; addListener(event: 'continue', listener: () => void): this; addListener(event: 'information', listener: (info: InformationEvent) => void): this; addListener(event: 'response', listener: (response: IncomingMessage) => void): this; addListener(event: 'socket', listener: (socket: Socket) => void): this; addListener(event: 'timeout', listener: () => void): this; - addListener( - event: 'upgrade', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; addListener(event: 'close', listener: () => void): this; addListener(event: 'drain', listener: () => void): this; addListener(event: 'error', listener: (err: Error) => void): this; @@ -941,19 +960,13 @@ declare module 'http' { * @deprecated */ prependListener(event: 'abort', listener: () => void): this; - prependListener( - event: 'connect', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; prependListener(event: 'continue', listener: () => void): this; prependListener(event: 'information', listener: (info: InformationEvent) => void): this; prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; prependListener(event: 'socket', listener: (socket: Socket) => void): this; prependListener(event: 'timeout', listener: () => void): this; - prependListener( - event: 'upgrade', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; prependListener(event: 'close', listener: () => void): this; prependListener(event: 'drain', listener: () => void): this; prependListener(event: 'error', listener: (err: Error) => void): this; @@ -965,19 +978,13 @@ declare module 'http' { * @deprecated */ prependOnceListener(event: 'abort', listener: () => void): this; - prependOnceListener( - event: 'connect', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; prependOnceListener(event: 'continue', listener: () => void): this; prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; prependOnceListener(event: 'timeout', listener: () => void): this; - prependOnceListener( - event: 'upgrade', - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; + prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; prependOnceListener(event: 'close', listener: () => void): this; prependOnceListener(event: 'drain', listener: () => void): this; prependOnceListener(event: 'error', listener: (err: Error) => void): this; @@ -989,7 +996,7 @@ declare module 'http' { /** * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to * access response - * status, headers and data. + * status, headers, and data. * * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to * parse and emit the incoming HTTP headers and payload, as the underlying socket @@ -1027,7 +1034,7 @@ declare module 'http' { * const req = http.request({ * host: '127.0.0.1', * port: 8080, - * method: 'POST' + * method: 'POST', * }, (res) => { * res.resume(); * res.on('end', () => { @@ -1069,7 +1076,7 @@ declare module 'http' { * // { 'user-agent': 'curl/7.22.0', * // host: '127.0.0.1:8000', * // accept: '*' } - * console.log(request.getHeaders()); + * console.log(request.headers); * ``` * * Duplicates in raw headers are handled in the following ways, depending on the @@ -1077,12 +1084,30 @@ declare module 'http' { * * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. * * `set-cookie` is always an array. Duplicates are added to the array. - * * For duplicate `cookie` headers, the values are joined together with '; '. - * * For all other headers, the values are joined together with ', '. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. * @since v0.1.5 */ headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; /** * The raw request/response headers list exactly as they were received. * @@ -1113,6 +1138,13 @@ declare module 'http' { * @since v0.3.0 */ trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; /** * The raw request/response trailer keys and values exactly as they were * received. Only populated at the `'end'` event. @@ -1145,14 +1177,14 @@ declare module 'http' { * To parse the URL into its parts: * * ```js - * new URL(request.url, `http://${request.getHeaders().host}`); + * new URL(request.url, `http://${request.headers.host}`); * ``` * - * When `request.url` is `'/status?name=ryan'` and`request.getHeaders().host` is `'localhost:3000'`: + * When `request.url` is `'/status?name=ryan'` and `request.headers.host` is`'localhost:3000'`: * * ```console * $ node - * > new URL(request.url, `http://${request.getHeaders().host}`) + * > new URL(request.url, `http://${request.headers.host}`) * URL { * href: 'http://localhost:3000/status?name=ryan', * origin: 'http://localhost:3000', @@ -1272,16 +1304,16 @@ declare module 'http' { * hostname: 'localhost', * port: 80, * path: '/', - * agent: false // Create a new agent just for this one request + * agent: false, // Create a new agent just for this one request * }, (res) => { * // Do stuff with response * }); * ``` * @since v0.3.4 */ - class Agent { + class Agent extends EventEmitter { /** - * By default set to 256\. For agents with `keepAlive` enabled, this + * By default set to 256. For agents with `keepAlive` enabled, this * sets the maximum number of sockets that will be left open in the free * state. * @since v0.11.7 @@ -1377,10 +1409,10 @@ declare module 'http' { * upload a file with a POST request, then write to the `ClientRequest` object. * * ```js - * const http = require('http'); + * const http = require('node:http'); * * const postData = JSON.stringify({ - * 'msg': 'Hello World!' + * 'msg': 'Hello World!', * }); * * const options = { @@ -1390,8 +1422,8 @@ declare module 'http' { * method: 'POST', * headers: { * 'Content-Type': 'application/json', - * 'Content-Length': Buffer.byteLength(postData) - * } + * 'Content-Length': Buffer.byteLength(postData), + * }, * }; * * const req = http.request(options, (res) => { @@ -1478,7 +1510,7 @@ declare module 'http' { * * `'data'` any number of times, on the `res` object * * (connection closed here) * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'` * * `'close'` * * `'close'` on the `res` object * @@ -1486,7 +1518,7 @@ declare module 'http' { * events will be emitted in the following order: * * * (`req.destroy()` called here) - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * If `req.destroy()` is called before the connection succeeds, the following @@ -1494,7 +1526,7 @@ declare module 'http' { * * * `'socket'` * * (`req.destroy()` called here) - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * If `req.destroy()` is called after the response is received, the following @@ -1505,7 +1537,7 @@ declare module 'http' { * * `'data'` any number of times, on the `res` object * * (`req.destroy()` called here) * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'error'` on the `res` object with an error with message `'Error: aborted'`and code `'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * `'close'` on the `res` object * @@ -1541,16 +1573,13 @@ declare module 'http' { * Setting the `timeout` option or using the `setTimeout()` function will * not abort the request or do anything besides add a `'timeout'` event. * - * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the - * request itself. + * Passing an `AbortSignal` and then calling `abort()` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`and the `cause`, if one was provided. * @since v0.3.6 */ function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - function request( - url: string | URL, - options: RequestOptions, - callback?: (res: IncomingMessage) => void, - ): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; /** * Since most requests are GET requests without bodies, Node.js provides this * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the @@ -1602,7 +1631,7 @@ declare module 'http' { * const server = http.createServer((req, res) => { * res.writeHead(200, { 'Content-Type': 'application/json' }); * res.end(JSON.stringify({ - * data: 'Hello World!' + * data: 'Hello World!', * })); * }); * @@ -1613,32 +1642,76 @@ declare module 'http' { */ function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - /** - * Performs the low-level validations on the provided name that are done when `res.setHeader(name, value)` is called. - * Passing illegal value as name will result in a TypeError being thrown, identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. - * @param name Header name + * Performs the low-level validations on the provided `name` that are done when`res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * Examples: + * + * Example: + * + * ```js + * const { validateHeaderName } = require('node:http'); + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` * @since v14.3.0 + * @param [label='Header name'] Label for error message. */ function validateHeaderName(name: string): void; /** - * Performs the low-level validations on the provided value that are done when `res.setHeader(name, value)` is called. - * Passing illegal value as value will result in a TypeError being thrown. - * - Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. - * - Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * Performs the low-level validations on the provided `value` that are done when`res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * const { validateHeaderValue } = require('node:http'); + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 * @param name Header name * @param value Header value - * @since v14.3.0 */ function validateHeaderValue(name: string, value: string): void; - /** - * Set the maximum number of idle HTTP parsers. Default: 1000. - * @param count + * Set the maximum number of idle HTTP parsers. * @since v18.8.0, v16.18.0 + * @param [max=1000] */ - function setMaxIdleHTTPParsers(count: number): void; - + function setMaxIdleHTTPParsers(max: number): void; let globalAgent: Agent; /** * Read-only property specifying the maximum allowed size of HTTP headers in bytes. diff --git a/node_modules/@types/node/ts4.8/http2.d.ts b/node_modules/@types/node/ts4.8/http2.d.ts index 0e36826..8005709 100644 --- a/node_modules/@types/node/ts4.8/http2.d.ts +++ b/node_modules/@types/node/ts4.8/http2.d.ts @@ -1,12 +1,12 @@ /** - * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It - * can be accessed using: + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * ``` * @since v8.4.0 - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http2.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http2.js) */ declare module 'http2' { import EventEmitter = require('node:events'); @@ -151,7 +151,7 @@ declare module 'http2' { priority(options: StreamPriorityOptions): void; /** * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const client = http2.connect('http://example.org:8000'); * const { NGHTTP2_CANCEL } = http2.constants; * const req = client.request({ ':path': '/' }); @@ -171,7 +171,7 @@ declare module 'http2' { * trailers can be sent. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond(undefined, { waitForTrailers: true }); @@ -332,7 +332,7 @@ declare module 'http2' { * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond({ ':status': 200 }); @@ -357,7 +357,7 @@ declare module 'http2' { pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; /** * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond({ ':status': 200 }); @@ -365,16 +365,15 @@ declare module 'http2' { * }); * ``` * - * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event - * will be emitted immediately after queuing the last chunk of payload data to be - * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing - * header fields to the peer. + * Initiates a response. When the `options.waitForTrailers` option is set, the`'wantTrailers'` event will be emitted immediately after queuing the last chunk + * of payload data to be sent. The `http2stream.sendTrailers()` method can then be + * used to sent trailing header fields to the peer. * * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond({ ':status': 200 }, { waitForTrailers: true }); @@ -397,8 +396,8 @@ declare module 'http2' { * automatically. * * ```js - * const http2 = require('http2'); - * const fs = require('fs'); + * const http2 = require('node:http2'); + * const fs = require('node:fs'); * * const server = http2.createServer(); * server.on('stream', (stream) => { @@ -408,7 +407,7 @@ declare module 'http2' { * const headers = { * 'content-length': stat.size, * 'last-modified': stat.mtime.toUTCString(), - * 'content-type': 'text/plain; charset=utf-8' + * 'content-type': 'text/plain; charset=utf-8', * }; * stream.respondWithFD(fd, headers); * stream.on('close', () => fs.closeSync(fd)); @@ -439,8 +438,8 @@ declare module 'http2' { * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. * * ```js - * const http2 = require('http2'); - * const fs = require('fs'); + * const http2 = require('node:http2'); + * const fs = require('node:fs'); * * const server = http2.createServer(); * server.on('stream', (stream) => { @@ -450,7 +449,7 @@ declare module 'http2' { * const headers = { * 'content-length': stat.size, * 'last-modified': stat.mtime.toUTCString(), - * 'content-type': 'text/plain; charset=utf-8' + * 'content-type': 'text/plain; charset=utf-8', * }; * stream.respondWithFD(fd, headers, { waitForTrailers: true }); * stream.on('wantTrailers', () => { @@ -482,7 +481,7 @@ declare module 'http2' { * Example using a file path: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * function statCheck(stat, headers) { @@ -500,7 +499,7 @@ declare module 'http2' { * } * } catch (err) { * // Perform actual error handling. - * console.log(err); + * console.error(err); * } * stream.end(); * } @@ -516,7 +515,7 @@ declare module 'http2' { * results to determine if the file has been modified to return an appropriate`304` response: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * function statCheck(stat, headers) { @@ -549,7 +548,7 @@ declare module 'http2' { * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respondWithFile('/some/file', @@ -748,7 +747,7 @@ declare module 'http2' { * the delta. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * const server = http2.createServer(); * const expectedWindowSize = 2 ** 20; @@ -854,11 +853,11 @@ declare module 'http2' { * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const clientSession = http2.connect('https://localhost:1234'); * const { * HTTP2_HEADER_PATH, - * HTTP2_HEADER_STATUS + * HTTP2_HEADER_STATUS, * } = http2.constants; * * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); @@ -928,7 +927,7 @@ declare module 'http2' { * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * const server = http2.createServer(); * server.on('session', (session) => { @@ -969,7 +968,7 @@ declare module 'http2' { * authoritative responses. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const options = getSecureOptionsSomehow(); * const server = http2.createSecureServer(options); * server.on('stream', (stream) => { @@ -995,7 +994,7 @@ declare module 'http2' { * server using the `http2.createSecureServer()` method: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const options = getSecureOptionsSomehow(); * options.origins = ['https://example.com', 'https://example.org']; * const server = http2.createSecureServer(options); @@ -1053,7 +1052,6 @@ declare module 'http2' { */ unknownProtocolTimeout?: number | undefined; selectPadding?(frameLen: number, maxFrameLen: number): number; - createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; } export interface ClientSessionOptions extends SessionOptions { maxReservedRemoteStreams?: number | undefined; @@ -1437,7 +1435,7 @@ declare module 'http2' { */ readonly headersSent: boolean; /** - * A reference to the original HTTP2 request object. + * A reference to the original HTTP2 `request` object. * @since v15.7.0 */ readonly req: Http2ServerRequest; @@ -1458,7 +1456,7 @@ declare module 'http2' { * All other interactions will be routed directly to the socket. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer((req, res) => { * const ip = req.socket.remoteAddress; * const port = req.socket.remotePort; @@ -1641,7 +1639,7 @@ declare module 'http2' { * This sends a chunk of the response body. This method may * be called multiple times to provide successive parts of the body. * - * In the `http` module, the response body is omitted when the + * In the `node:http` module, the response body is omitted when the * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. * * `chunk` can be a string or a buffer. If `chunk` is a string, @@ -1676,7 +1674,7 @@ declare module 'http2' { * The `hints` is an object containing the values of headers to be sent with * early hints message. * - * Example: + * **Example** * * ```js * const earlyHintsLink = '; rel=preload; as=style'; @@ -1690,12 +1688,9 @@ declare module 'http2' { * ]; * response.writeEarlyHints({ * 'link': earlyHintsLinks, - * 'x-trace-id': 'id for diagnostics' * }); * ``` - * * @since v18.11.0 - * @param hints An object containing the values of headers */ writeEarlyHints(hints: Record): void; /** @@ -2028,7 +2023,7 @@ declare module 'http2' { * for use with the `HTTP2-Settings` header field. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * const packed = http2.getPackedSettings({ enablePush: false }); * @@ -2053,7 +2048,7 @@ declare module 'http2' { * with browser clients. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * // Create an unencrypted HTTP/2 server. * // Since there are no browsers known that support @@ -2064,12 +2059,12 @@ declare module 'http2' { * server.on('stream', (stream, headers) => { * stream.respond({ * 'content-type': 'text/html; charset=utf-8', - * ':status': 200 + * ':status': 200, * }); * stream.end('

Hello World

'); * }); * - * server.listen(80); + * server.listen(8000); * ``` * @since v8.4.0 * @param onRequestHandler See `Compatibility API` @@ -2080,12 +2075,12 @@ declare module 'http2' { * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. * * ```js - * const http2 = require('http2'); - * const fs = require('fs'); + * const http2 = require('node:http2'); + * const fs = require('node:fs'); * * const options = { * key: fs.readFileSync('server-key.pem'), - * cert: fs.readFileSync('server-cert.pem') + * cert: fs.readFileSync('server-cert.pem'), * }; * * // Create a secure HTTP/2 server @@ -2094,12 +2089,12 @@ declare module 'http2' { * server.on('stream', (stream, headers) => { * stream.respond({ * 'content-type': 'text/html; charset=utf-8', - * ':status': 200 + * ':status': 200, * }); * stream.end('

Hello World

'); * }); * - * server.listen(80); + * server.listen(8443); * ``` * @since v8.4.0 * @param onRequestHandler See `Compatibility API` @@ -2110,7 +2105,7 @@ declare module 'http2' { * Returns a `ClientHttp2Session` instance. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const client = http2.connect('https://localhost:1234'); * * // Use the client diff --git a/node_modules/@types/node/ts4.8/https.d.ts b/node_modules/@types/node/ts4.8/https.d.ts index bda367d..76fca92 100644 --- a/node_modules/@types/node/ts4.8/https.d.ts +++ b/node_modules/@types/node/ts4.8/https.d.ts @@ -1,7 +1,7 @@ /** * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a * separate module. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/https.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/https.js) */ declare module 'https' { import { Duplex } from 'node:stream'; @@ -59,22 +59,9 @@ declare module 'https' { closeIdleConnections(): void; addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - addListener( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - addListener( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - addListener( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; addListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; addListener(event: 'close', listener: () => void): this; @@ -84,29 +71,13 @@ declare module 'https' { addListener(event: 'checkContinue', listener: http.RequestListener): this; addListener(event: 'checkExpectation', listener: http.RequestListener): this; addListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - addListener( - event: 'connect', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + addListener(event: 'connect', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; addListener(event: 'request', listener: http.RequestListener): this; - addListener( - event: 'upgrade', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + addListener(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; emit(event: string, ...args: any[]): boolean; emit(event: 'keylog', line: Buffer, tlsSocket: tls.TLSSocket): boolean; - emit( - event: 'newSession', - sessionId: Buffer, - sessionData: Buffer, - callback: (err: Error, resp: Buffer) => void, - ): boolean; - emit( - event: 'OCSPRequest', - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; emit(event: 'secureConnection', tlsSocket: tls.TLSSocket): boolean; emit(event: 'tlsClientError', err: Error, tlsSocket: tls.TLSSocket): boolean; @@ -117,39 +88,32 @@ declare module 'https' { emit( event: 'checkContinue', req: InstanceType, - res: InstanceType & { req: InstanceType }, + res: InstanceType & { + req: InstanceType; + } ): boolean; emit( event: 'checkExpectation', req: InstanceType, - res: InstanceType & { req: InstanceType }, + res: InstanceType & { + req: InstanceType; + } ): boolean; emit(event: 'clientError', err: Error, socket: Duplex): boolean; emit(event: 'connect', req: InstanceType, socket: Duplex, head: Buffer): boolean; emit( event: 'request', req: InstanceType, - res: InstanceType & { req: InstanceType }, + res: InstanceType & { + req: InstanceType; + } ): boolean; emit(event: 'upgrade', req: InstanceType, socket: Duplex, head: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - on( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - on( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - on( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; on(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; on(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; on(event: 'close', listener: () => void): this; @@ -164,22 +128,9 @@ declare module 'https' { on(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - once( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - once( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - once( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; once(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; once(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; once(event: 'close', listener: () => void): this; @@ -194,22 +145,9 @@ declare module 'https' { once(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - prependListener( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - prependListener( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - prependListener( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; prependListener(event: 'close', listener: () => void): this; @@ -219,33 +157,14 @@ declare module 'https' { prependListener(event: 'checkContinue', listener: http.RequestListener): this; prependListener(event: 'checkExpectation', listener: http.RequestListener): this; prependListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - prependListener( - event: 'connect', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + prependListener(event: 'connect', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; prependListener(event: 'request', listener: http.RequestListener): this; - prependListener( - event: 'upgrade', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + prependListener(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - prependOnceListener( - event: 'newSession', - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - prependOnceListener( - event: 'OCSPRequest', - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - prependOnceListener( - event: 'resumeSession', - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependOnceListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; prependOnceListener(event: 'close', listener: () => void): this; @@ -255,25 +174,19 @@ declare module 'https' { prependOnceListener(event: 'checkContinue', listener: http.RequestListener): this; prependOnceListener(event: 'checkExpectation', listener: http.RequestListener): this; prependOnceListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - prependOnceListener( - event: 'connect', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + prependOnceListener(event: 'connect', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; prependOnceListener(event: 'request', listener: http.RequestListener): this; - prependOnceListener( - event: 'upgrade', - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; + prependOnceListener(event: 'upgrade', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; } /** * ```js * // curl -k https://localhost:8000/ - * const https = require('https'); - * const fs = require('fs'); + * const https = require('node:https'); + * const fs = require('node:fs'); * * const options = { * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), - * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), * }; * * https.createServer(options, (req, res) => { @@ -285,12 +198,12 @@ declare module 'https' { * Or * * ```js - * const https = require('https'); - * const fs = require('fs'); + * const https = require('node:https'); + * const fs = require('node:fs'); * * const options = { * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), - * passphrase: 'sample' + * passphrase: 'sample', * }; * * https.createServer(options, (req, res) => { @@ -326,13 +239,13 @@ declare module 'https' { * upload a file with a POST request, then write to the `ClientRequest` object. * * ```js - * const https = require('https'); + * const https = require('node:https'); * * const options = { * hostname: 'encrypted.google.com', * port: 443, * path: '/', - * method: 'GET' + * method: 'GET', * }; * * const req = https.request(options, (res) => { @@ -359,7 +272,7 @@ declare module 'https' { * path: '/', * method: 'GET', * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), - * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), * }; * options.agent = new https.Agent(options); * @@ -378,7 +291,7 @@ declare module 'https' { * method: 'GET', * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), - * agent: false + * agent: false, * }; * * const req = https.request(options, (res) => { @@ -399,9 +312,9 @@ declare module 'https' { * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): * * ```js - * const tls = require('tls'); - * const https = require('https'); - * const crypto = require('crypto'); + * const tls = require('node:tls'); + * const https = require('node:https'); + * const crypto = require('node:crypto'); * * function sha256(s) { * return crypto.createHash('sha256').update(s).digest('base64'); @@ -418,7 +331,7 @@ declare module 'https' { * return err; * } * - * // Pin the public key, similar to HPKP pin-sha25 pinning + * // Pin the public key, similar to HPKP pin-sha256 pinning * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; * if (sha256(cert.pubkey) !== pubkey256) { * const msg = 'Certificate verification error: ' + @@ -493,15 +406,8 @@ declare module 'https' { * @since v0.3.6 * @param options Accepts all `options` from `request`, with some differences in default values: */ - function request( - options: RequestOptions | string | URL, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; - function request( - url: string | URL, - options: RequestOptions, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; /** * Like `http.get()` but for HTTPS. * @@ -509,7 +415,7 @@ declare module 'https' { * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. * * ```js - * const https = require('https'); + * const https = require('node:https'); * * https.get('https://encrypted.google.com/', (res) => { * console.log('statusCode:', res.statusCode); @@ -526,15 +432,8 @@ declare module 'https' { * @since v0.3.6 * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. */ - function get( - options: RequestOptions | string | URL, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; - function get( - url: string | URL, - options: RequestOptions, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; let globalAgent: Agent; } declare module 'node:https' { diff --git a/node_modules/@types/node/ts4.8/inspector.d.ts b/node_modules/@types/node/ts4.8/inspector.d.ts index eba0b55..48920de 100644 --- a/node_modules/@types/node/ts4.8/inspector.d.ts +++ b/node_modules/@types/node/ts4.8/inspector.d.ts @@ -8,14 +8,21 @@ // tslint:disable:max-line-length /** - * The `inspector` module provides an API for interacting with the V8 inspector. + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. * * It can be accessed using: * * ```js - * const inspector = require('inspector'); + * import * as inspector from 'node:inspector/promises'; * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/inspector.js) + * + * or + * + * ```js + * import * as inspector from 'node:inspector'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/inspector.js) */ declare module 'inspector' { import EventEmitter = require('node:events'); diff --git a/node_modules/@types/node/ts4.8/module.d.ts b/node_modules/@types/node/ts4.8/module.d.ts index d83aec9..e884f32 100644 --- a/node_modules/@types/node/ts4.8/module.d.ts +++ b/node_modules/@types/node/ts4.8/module.d.ts @@ -10,9 +10,9 @@ declare module 'module' { * does not add or remove exported names from the `ES Modules`. * * ```js - * const fs = require('fs'); - * const assert = require('assert'); - * const { syncBuiltinESMExports } = require('module'); + * const fs = require('node:fs'); + * const assert = require('node:assert'); + * const { syncBuiltinESMExports } = require('node:module'); * * fs.readFile = newAPI; * @@ -26,7 +26,7 @@ declare module 'module' { * * syncBuiltinESMExports(); * - * import('fs').then((esmFS) => { + * import('node:fs').then((esmFS) => { * // It syncs the existing readFile property with the new value * assert.strictEqual(esmFS.readFile, newAPI); * // readFileSync has been deleted from the required fs @@ -44,6 +44,7 @@ declare module 'module' { * `path` is the resolved path for the file for which a corresponding source map * should be fetched. * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. */ function findSourceMap(path: string, error?: Error): SourceMap; interface SourceMapPayload { @@ -85,6 +86,7 @@ declare module 'module' { static wrap(code: string): string; static createRequire(path: string | URL): NodeRequire; static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; static Module: typeof Module; constructor(id: string, parent?: Module); } diff --git a/node_modules/@types/node/ts4.8/net.d.ts b/node_modules/@types/node/ts4.8/net.d.ts index 72cebc8..485a971 100644 --- a/node_modules/@types/node/ts4.8/net.d.ts +++ b/node_modules/@types/node/ts4.8/net.d.ts @@ -1,16 +1,16 @@ /** * > Stability: 2 - Stable * - * The `net` module provides an asynchronous network API for creating stream-based + * The `node:net` module provides an asynchronous network API for creating stream-based * TCP or `IPC` servers ({@link createServer}) and clients * ({@link createConnection}). * * It can be accessed using: * * ```js - * const net = require('net'); + * const net = require('node:net'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/net.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/net.js) */ declare module 'net' { import * as stream from 'node:stream'; @@ -57,6 +57,14 @@ declare module 'net' { noDelay?: boolean | undefined; keepAlive?: boolean | undefined; keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; } interface IpcSocketConnectOpts extends ConnectOpts { path: string; @@ -133,13 +141,10 @@ declare module 'net' { pause(): this; /** * Close the TCP connection by sending an RST packet and destroy the stream. - * If this TCP socket is in connecting status, it will send an RST packet - * and destroy this TCP socket once it is connected. Otherwise, it will call - * `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. If this is not a TCP socket - * (for example, a pipe), calling this method will immediately throw - * an `ERR_INVALID_HANDLE_TYPE` Error. - * @since v18.3.0 - * @return The socket itself. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 */ resetAndDestroy(): this; /** @@ -261,6 +266,12 @@ declare module 'net' { * @since v6.1.0 */ readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; /** * See `writable.destroyed` for further details. */ @@ -279,12 +290,16 @@ declare module 'net' { readonly localPort?: number; /** * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. - * @since v18.8.0 + * @since v18.8.0, v16.18.0 */ - readonly localFamily?: string; + readonly localFamily?: string; /** * This property represents the state of the connection as a string. - * @see {https://nodejs.org/api/net.html#socketreadystate} + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. * @since v0.5.0 */ readonly readyState: SocketReadyState; @@ -295,17 +310,20 @@ declare module 'net' { */ readonly remoteAddress?: string | undefined; /** - * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). * @since v0.11.14 */ readonly remoteFamily?: string | undefined; /** - * The numeric representation of the remote port. For example, `80` or `21`. + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). * @since v0.5.10 */ readonly remotePort?: number | undefined; /** - * The socket timeout in milliseconds as set by socket.setTimeout(). It is undefined if a timeout has not been set. + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. * @since v10.7.0 */ readonly timeout?: number | undefined; @@ -486,7 +504,7 @@ declare module 'net' { * ```js * server.on('error', (e) => { * if (e.code === 'EADDRINUSE') { - * console.log('Address in use, retrying...'); + * console.error('Address in use, retrying...'); * setTimeout(() => { * server.close(); * server.listen(PORT, HOST); @@ -708,7 +726,7 @@ declare module 'net' { * on port 8124: * * ```js - * const net = require('net'); + * const net = require('node:net'); * const server = net.createServer((c) => { * // 'connection' listener. * console.log('client connected'); @@ -728,8 +746,8 @@ declare module 'net' { * * Test this by using `telnet`: * - * ```console - * $ telnet localhost 8124 + * ```bash + * telnet localhost 8124 * ``` * * To listen on the socket `/tmp/echo.sock`: @@ -742,8 +760,8 @@ declare module 'net' { * * Use `nc` to connect to a Unix domain socket server: * - * ```console - * $ nc -U /tmp/echo.sock + * ```bash + * nc -U /tmp/echo.sock * ``` * @since v0.5.0 * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. @@ -846,6 +864,7 @@ declare module 'net' { class SocketAddress { constructor(options: SocketAddressInitOptions); /** + * Either \`'ipv4'\` or \`'ipv6'\`. * @since v15.14.0, v14.18.0 */ readonly address: string; diff --git a/node_modules/@types/node/ts4.8/os.d.ts b/node_modules/@types/node/ts4.8/os.d.ts index 3c55599..3d20864 100644 --- a/node_modules/@types/node/ts4.8/os.d.ts +++ b/node_modules/@types/node/ts4.8/os.d.ts @@ -1,11 +1,11 @@ /** - * The `os` module provides operating system-related utility methods and + * The `node:os` module provides operating system-related utility methods and * properties. It can be accessed using: * * ```js - * const os = require('os'); + * const os = require('node:os'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/os.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/os.js) */ declare module 'os' { interface CpuInfo { @@ -75,6 +75,7 @@ declare module 'os' { function totalmem(): number; /** * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the`/proc` file system is unavailable. * * The properties included on each object include: * @@ -88,8 +89,8 @@ declare module 'os' { * nice: 0, * sys: 30340, * idle: 1070356870, - * irq: 0 - * } + * irq: 0, + * }, * }, * { * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', @@ -99,8 +100,8 @@ declare module 'os' { * nice: 0, * sys: 26980, * idle: 1071569080, - * irq: 0 - * } + * irq: 0, + * }, * }, * { * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', @@ -110,8 +111,8 @@ declare module 'os' { * nice: 0, * sys: 21750, * idle: 1070919370, - * irq: 0 - * } + * irq: 0, + * }, * }, * { * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', @@ -121,17 +122,28 @@ declare module 'os' { * nice: 0, * sys: 19430, * idle: 1070905480, - * irq: 20 - * } + * irq: 20, + * }, * }, * ] * ``` * * `nice` values are POSIX-only. On Windows, the `nice` values of all processors * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. * @since v0.3.3 */ function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; /** * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. @@ -415,12 +427,11 @@ declare module 'os' { */ function platform(): NodeJS.Platform; /** - * Returns the machine type as a string, such as arm, aarch64, mips, mips64, ppc64, ppc64le, s390, s390x, i386, i686, x86_64. + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,`mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. * - * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). - * On Windows, `RtlGetVersion()` is used, and if it is not available, `GetVersionExW()` will be used. - * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. - * @since v18.9.0 + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 */ function machine(): string; /** diff --git a/node_modules/@types/node/ts4.8/path.d.ts b/node_modules/@types/node/ts4.8/path.d.ts index 1d33f79..723d5da 100644 --- a/node_modules/@types/node/ts4.8/path.d.ts +++ b/node_modules/@types/node/ts4.8/path.d.ts @@ -7,13 +7,13 @@ declare module 'path/win32' { export = path; } /** - * The `path` module provides utilities for working with file and directory paths. - * It can be accessed using: + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: * * ```js - * const path = require('path'); + * const path = require('node:path'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/path.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/path.js) */ declare module 'path' { namespace path { diff --git a/node_modules/@types/node/ts4.8/perf_hooks.d.ts b/node_modules/@types/node/ts4.8/perf_hooks.d.ts index 5c0b228..c090e1d 100644 --- a/node_modules/@types/node/ts4.8/perf_hooks.d.ts +++ b/node_modules/@types/node/ts4.8/perf_hooks.d.ts @@ -7,9 +7,10 @@ * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) * * [Performance Timeline](https://w3c.github.io/performance-timeline/) * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) * * ```js - * const { PerformanceObserver, performance } = require('perf_hooks'); + * const { PerformanceObserver, performance } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((items) => { * console.log(items.getEntries()[0].duration); @@ -26,7 +27,7 @@ * performance.measure('A to B', 'A', 'B'); * }); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/perf_hooks.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/perf_hooks.js) */ declare module 'perf_hooks' { import { AsyncResource } from 'node:async_hooks'; @@ -46,6 +47,7 @@ declare module 'perf_hooks' { readonly flags?: number | undefined; } /** + * The constructor of this class is not exposed to users directly. * @since v8.5.0 */ class PerformanceEntry { @@ -87,10 +89,20 @@ declare module 'perf_hooks' { readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. toJSON(): any; } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ class PerformanceMark extends PerformanceEntry { readonly duration: 0; readonly entryType: 'mark'; } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ class PerformanceMeasure extends PerformanceEntry { readonly entryType: 'measure'; } @@ -288,8 +300,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntries()); @@ -330,8 +342,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByName('meow')); @@ -379,8 +391,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByType('mark')); @@ -414,6 +426,9 @@ declare module 'perf_hooks' { getEntriesByType(type: EntryType): PerformanceEntry[]; } type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ class PerformanceObserver extends AsyncResource { constructor(callback: PerformanceObserverCallback); /** @@ -427,8 +442,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((list, observer) => { * // Called once asynchronously. `list` contains three items. @@ -547,11 +562,10 @@ declare module 'perf_hooks' { */ recordDelta(): void; /** - * Adds the values from other to this histogram. + * Adds the values from `other` to this histogram. * @since v17.4.0, v16.14.0 - * @param other Recordable Histogram to combine with */ - add(other: RecordableHistogram): void; + add(other: RecordableHistogram): void; } /** * _This property is an extension by Node.js. It is not available in Web browsers._ @@ -566,7 +580,7 @@ declare module 'perf_hooks' { * detect. * * ```js - * const { monitorEventLoopDelay } = require('perf_hooks'); + * const { monitorEventLoopDelay } = require('node:perf_hooks'); * const h = monitorEventLoopDelay({ resolution: 20 }); * h.enable(); * // Do something. @@ -604,7 +618,6 @@ declare module 'perf_hooks' { * @since v15.9.0, v14.18.0 */ function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; - import { performance as _performance } from 'perf_hooks'; global { /** diff --git a/node_modules/@types/node/ts4.8/process.d.ts b/node_modules/@types/node/ts4.8/process.d.ts index 12148f9..f122546 100644 --- a/node_modules/@types/node/ts4.8/process.d.ts +++ b/node_modules/@types/node/ts4.8/process.d.ts @@ -250,7 +250,7 @@ declare module 'process' { * For example, to copy `process.stdin` to `process.stdout`: * * ```js - * import { stdin, stdout } from 'process'; + * import { stdin, stdout } from 'node:process'; * * stdin.pipe(stdout); * ``` @@ -297,7 +297,7 @@ declare module 'process' { * For example, assuming the following script for `process-args.js`: * * ```js - * import { argv } from 'process'; + * import { argv } from 'node:process'; * * // print process.argv * argv.forEach((val, index) => { @@ -307,8 +307,8 @@ declare module 'process' { * * Launching the Node.js process as: * - * ```console - * $ node process-args.js one two=three four + * ```bash + * node process-args.js one two=three four * ``` * * Would generate the output: @@ -344,8 +344,8 @@ declare module 'process' { * the script name. These options are useful in order to spawn child processes with * the same execution environment as the parent. * - * ```console - * $ node --harmony script.js --version + * ```bash + * node --harmony script.js --version * ``` * * Results in `process.execArgv`: @@ -389,7 +389,7 @@ declare module 'process' { * the specified `directory` does not exist). * * ```js - * import { chdir, cwd } from 'process'; + * import { chdir, cwd } from 'node:process'; * * console.log(`Starting directory: ${cwd()}`); * try { @@ -409,7 +409,7 @@ declare module 'process' { * process. * * ```js - * import { cwd } from 'process'; + * import { cwd } from 'node:process'; * * console.log(`Current directory: ${cwd()}`); * ``` @@ -420,7 +420,7 @@ declare module 'process' { * The port used by the Node.js debugger when enabled. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * process.debugPort = 5858; * ``` @@ -432,12 +432,12 @@ declare module 'process' { * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. * * ```js - * import { emitWarning } from 'process'; + * import { emitWarning } from 'node:process'; * * // Emit a warning with a code and additional detail. * emitWarning('Something happened!', { * code: 'MY_WARNING', - * detail: 'This is some additional information' + * detail: 'This is some additional information', * }); * // Emits: * // (node:56338) [MY_WARNING] Warning: Something happened! @@ -447,7 +447,7 @@ declare module 'process' { * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * process.on('warning', (warning) => { * console.warn(warning.name); // 'Warning' @@ -492,14 +492,14 @@ declare module 'process' { * to other `Worker` threads. * In other words, the following example would not work: * - * ```console - * $ node -e 'process.env.foo = "bar"' && echo $foo + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo * ``` * * While the following will: * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.foo = 'bar'; * console.log(env.foo); @@ -510,7 +510,7 @@ declare module 'process' { * throw an error when the value is not a string, number, or boolean. * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.test = null; * console.log(env.test); @@ -523,7 +523,7 @@ declare module 'process' { * Use `delete` to delete a property from `process.env`. * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.TEST = 1; * delete env.TEST; @@ -534,7 +534,7 @@ declare module 'process' { * On Windows operating systems, environment variables are case-insensitive. * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.TEST = 1; * console.log(env.test); @@ -543,7 +543,7 @@ declare module 'process' { * * Unless explicitly specified when creating a `Worker` instance, * each `Worker` thread has its own copy of `process.env`, based on its - * parent thread’s `process.env`, or whatever was specified as the `env` option + * parent thread's `process.env`, or whatever was specified as the `env` option * to the `Worker` constructor. Changes to `process.env` will not be visible * across `Worker` threads, and only the main thread can make changes that * are visible to the operating system or to native add-ons. @@ -560,7 +560,7 @@ declare module 'process' { * To exit with a 'failure' code: * * ```js - * import { exit } from 'process'; + * import { exit } from 'node:process'; * * exit(1); * ``` @@ -579,7 +579,7 @@ declare module 'process' { * truncated and lost: * * ```js - * import { exit } from 'process'; + * import { exit } from 'node:process'; * * // This is an example of what *not* to do: * if (someConditionNotMet()) { @@ -596,7 +596,7 @@ declare module 'process' { * scheduling any additional work for the event loop: * * ```js - * import process from 'process'; + * import process from 'node:process'; * * // How to properly set the exit code while letting * // the process exit gracefully. @@ -613,7 +613,7 @@ declare module 'process' { * In `Worker` threads, this function stops the current thread rather * than the current process. * @since v0.1.13 - * @param [code=0] The exit code. + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. */ exit(code?: number): never; /** @@ -873,7 +873,7 @@ declare module 'process' { * The `process.version` property contains the Node.js version string. * * ```js - * import { version } from 'process'; + * import { version } from 'node:process'; * * console.log(`Version: ${version}`); * // Version: v14.8.0 @@ -890,7 +890,7 @@ declare module 'process' { * to load modules that were compiled against a different module ABI version. * * ```js - * import { versions } from 'process'; + * import { versions } from 'node:process'; * * console.log(versions); * ``` @@ -898,30 +898,39 @@ declare module 'process' { * Will generate an object similar to: * * ```console - * { node: '11.13.0', - * v8: '7.0.276.38-node.18', - * uv: '1.27.0', - * zlib: '1.2.11', - * brotli: '1.0.7', - * ares: '1.15.0', - * modules: '67', - * nghttp2: '1.34.0', - * napi: '4', - * llhttp: '1.1.1', - * openssl: '1.1.1b', - * cldr: '34.0', - * icu: '63.1', - * tz: '2018e', - * unicode: '11.0' } + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } * ``` * @since v0.2.0 */ readonly versions: ProcessVersions; /** - * The `process.config` property returns an `Object` containing the JavaScript - * representation of the configure options used to compile the current Node.js - * executable. This is the same as the `config.gypi` file that was produced when - * running the `./configure` script. + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. * * An example of the possible output looks like: * @@ -943,7 +952,6 @@ declare module 'process' { * node_shared_http_parser: 'false', * node_shared_libuv: 'false', * node_shared_zlib: 'false', - * node_use_dtrace: 'false', * node_use_openssl: 'true', * node_shared_openssl: 'false', * strict_aliasing: 'true', @@ -952,13 +960,6 @@ declare module 'process' { * } * } * ``` - * - * The `process.config` property is **not** read-only and there are existing - * modules in the ecosystem that are known to extend, modify, or entirely replace - * the value of `process.config`. - * - * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made - * read-only in a future release. * @since v0.7.7 */ readonly config: ProcessConfig; @@ -977,7 +978,7 @@ declare module 'process' { * other than kill the target process. * * ```js - * import process, { kill } from 'process'; + * import process, { kill } from 'node:process'; * * process.on('SIGHUP', () => { * console.log('Got SIGHUP signal.'); @@ -1002,7 +1003,7 @@ declare module 'process' { * The `process.pid` property returns the PID of the process. * * ```js - * import { pid } from 'process'; + * import { pid } from 'node:process'; * * console.log(`This process is pid ${pid}`); * ``` @@ -1014,7 +1015,7 @@ declare module 'process' { * current process. * * ```js - * import { ppid } from 'process'; + * import { ppid } from 'node:process'; * * console.log(`The parent process is pid ${ppid}`); * ``` @@ -1044,7 +1045,7 @@ declare module 'process' { * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. * * ```js - * import { arch } from 'process'; + * import { arch } from 'node:process'; * * console.log(`This processor architecture is ${arch}`); * ``` @@ -1066,7 +1067,7 @@ declare module 'process' { * * `'win32'` * * ```js - * import { platform } from 'process'; + * import { platform } from 'node:process'; * * console.log(`This platform is ${platform}`); * ``` @@ -1089,6 +1090,17 @@ declare module 'process' { */ mainModule?: Module | undefined; memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `undefined` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + * @experimental + */ + constrainedMemory(): number | undefined; /** * The `process.cpuUsage()` method returns the user and system CPU time usage of * the current process, in an object with properties `user` and `system`, whose @@ -1100,7 +1112,7 @@ declare module 'process' { * argument to the function, to get a diff reading. * * ```js - * import { cpuUsage } from 'process'; + * import { cpuUsage } from 'node:process'; * * const startUsage = cpuUsage(); * // { user: 38579, system: 6986 } @@ -1124,7 +1136,7 @@ declare module 'process' { * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. * * ```js - * import { nextTick } from 'process'; + * import { nextTick } from 'node:process'; * * console.log('start'); * nextTick(() => { @@ -1142,7 +1154,7 @@ declare module 'process' { * I/O has occurred: * * ```js - * import { nextTick } from 'process'; + * import { nextTick } from 'node:process'; * * function MyThing(options) { * this.setupOptions(options); @@ -1190,7 +1202,7 @@ declare module 'process' { * The following approach is much better: * * ```js - * import { nextTick } from 'process'; + * import { nextTick } from 'node:process'; * * function definitelyAsync(arg, cb) { * if (arg) { @@ -1215,10 +1227,10 @@ declare module 'process' { * ```js * { * name: 'node', - * lts: 'Erbium', - * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', - * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', - * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' * } * ``` * @@ -1322,7 +1334,7 @@ declare module 'process' { * dashes: * * ```js - * import { allowedNodeEnvironmentFlags } from 'process'; + * import { allowedNodeEnvironmentFlags } from 'node:process'; * * allowedNodeEnvironmentFlags.forEach((flag) => { * // -r @@ -1348,7 +1360,7 @@ declare module 'process' { report?: ProcessReport | undefined; /** * ```js - * import { resourceUsage } from 'process'; + * import { resourceUsage } from 'node:process'; * * console.log(resourceUsage()); * /* diff --git a/node_modules/@types/node/ts4.8/punycode.d.ts b/node_modules/@types/node/ts4.8/punycode.d.ts index 87ebbb9..8927207 100644 --- a/node_modules/@types/node/ts4.8/punycode.d.ts +++ b/node_modules/@types/node/ts4.8/punycode.d.ts @@ -24,7 +24,7 @@ * made available to developers as a convenience. Fixes or other modifications to * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. * @deprecated Since v7.0.0 - Deprecated - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/punycode.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/punycode.js) */ declare module 'punycode' { /** diff --git a/node_modules/@types/node/ts4.8/querystring.d.ts b/node_modules/@types/node/ts4.8/querystring.d.ts index e118547..e9d087c 100644 --- a/node_modules/@types/node/ts4.8/querystring.d.ts +++ b/node_modules/@types/node/ts4.8/querystring.d.ts @@ -1,15 +1,15 @@ /** - * The `querystring` module provides utilities for parsing and formatting URL + * The `node:querystring` module provides utilities for parsing and formatting URL * query strings. It can be accessed using: * * ```js - * const querystring = require('querystring'); + * const querystring = require('node:querystring'); * ``` * * `querystring` is more performant than `URLSearchParams` but is not a - * standardized API. Use `URLSearchParams` when performance is not critical - * or when compatibility with browser code is desirable. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/querystring.js) + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/querystring.js) */ declare module 'querystring' { interface StringifyOptions { diff --git a/node_modules/@types/node/ts4.8/readline.d.ts b/node_modules/@types/node/ts4.8/readline.d.ts index 6ab64ac..e6f7b0a 100644 --- a/node_modules/@types/node/ts4.8/readline.d.ts +++ b/node_modules/@types/node/ts4.8/readline.d.ts @@ -1,5 +1,5 @@ /** - * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. + * The `node:readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. * * To use the promise-based APIs: * @@ -13,7 +13,7 @@ * import * as readline from 'node:readline'; * ``` * - * The following simple example illustrates the basic use of the `readline` module. + * The following simple example illustrates the basic use of the `node:readline`module. * * ```js * import * as readline from 'node:readline/promises'; @@ -30,12 +30,11 @@ * * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be * received on the `input` stream. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/readline.js) */ declare module 'readline' { import { Abortable, EventEmitter } from 'node:events'; import * as promises from 'node:readline/promises'; - export { promises }; export interface Key { sequence?: string | undefined; @@ -74,7 +73,7 @@ declare module 'readline' { * const showResults = debounce(() => { * console.log( * '\n', - * values.filter((val) => val.startsWith(rl.line)).join(' ') + * values.filter((val) => val.startsWith(rl.line)).join(' '), * ); * }, 300); * process.stdin.on('keypress', (c, k) => { @@ -100,7 +99,7 @@ declare module 'readline' { * > Instances of the `readline.Interface` class are constructed using the * > `readline.createInterface()` method. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor */ protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); /** @@ -109,12 +108,12 @@ declare module 'readline' { * > Instances of the `readline.Interface` class are constructed using the * > `readline.createInterface()` method. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor */ protected constructor(options: ReadLineOptions); /** * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. - * @since v15.3.0 + * @since v15.3.0, v14.17.0 * @return the current prompt string */ getPrompt(): string; @@ -124,13 +123,13 @@ declare module 'readline' { */ setPrompt(prompt: string): void; /** - * The `rl.prompt()` method writes the `readline.Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new * location at which to provide input. * * When called, `rl.prompt()` will resume the `input` stream if it has been * paused. * - * If the `readline.Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * If the `Interface` was created with `output` set to `null` or`undefined` the prompt is not written. * @since v0.1.98 * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. */ @@ -142,12 +141,14 @@ declare module 'readline' { * When called, `rl.question()` will resume the `input` stream if it has been * paused. * - * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. * * The `callback` function passed to `rl.question()` does not follow the typical * pattern of accepting an `Error` object or `null` as the first argument. * The `callback` is called with the provided answer as the only argument. * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * * Example usage: * * ```js @@ -172,25 +173,6 @@ declare module 'readline' { * * setTimeout(() => ac.abort(), 10000); * ``` - * - * If this method is invoked as it's util.promisify()ed version, it returns a - * Promise that fulfills with the answer. If the question is canceled using - * an `AbortController` it will reject with an `AbortError`. - * - * ```js - * const util = require('util'); - * const question = util.promisify(rl.question).bind(rl); - * - * async function questionExample() { - * try { - * const answer = await question('What is you favorite food? '); - * console.log(`Oh, so your favorite food is ${answer}`); - * } catch (err) { - * console.error('Question rejected', err); - * } - * } - * questionExample(); - * ``` * @since v0.3.3 * @param query A statement or query to write to `output`, prepended to the prompt. * @param callback A callback function that is invoked with the user's input in response to the `query`. @@ -201,7 +183,7 @@ declare module 'readline' { * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed * later if necessary. * - * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `readline.Interface` instance. + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `Interface` instance. * @since v0.3.4 */ pause(): this; @@ -211,12 +193,12 @@ declare module 'readline' { */ resume(): this; /** - * The `rl.close()` method closes the `readline.Interface` instance and + * The `rl.close()` method closes the `Interface` instance and * relinquishes control over the `input` and `output` streams. When called, * the `'close'` event will be emitted. * * Calling `rl.close()` does not immediately stop other events (including `'line'`) - * from being emitted by the `readline.Interface` instance. + * from being emitted by the `Interface` instance. * @since v0.1.98 */ close(): void; @@ -231,7 +213,7 @@ declare module 'readline' { * When called, `rl.write()` will resume the `input` stream if it has been * paused. * - * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * If the `Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. * * ```js * rl.write('Delete this!'); @@ -351,10 +333,10 @@ declare module 'readline' { * The `readline.createInterface()` method creates a new `readline.Interface`instance. * * ```js - * const readline = require('readline'); + * const readline = require('node:readline'); * const rl = readline.createInterface({ * input: process.stdin, - * output: process.stdout + * output: process.stdout, * }); * ``` * @@ -373,14 +355,8 @@ declare module 'readline' { * (`process.stdout` does this automatically when it is a TTY). * * When creating a `readline.Interface` using `stdin` as input, the program - * will not terminate until it receives `EOF` (Ctrl+D on - * Linux/macOS, Ctrl+Z followed by Return on - * Windows). - * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: - * - * ```js - * process.stdin.unref(); - * ``` + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. * @since v0.1.98 */ export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; @@ -408,11 +384,11 @@ declare module 'readline' { * implement a small command-line interface: * * ```js - * const readline = require('readline'); + * const readline = require('node:readline'); * const rl = readline.createInterface({ * input: process.stdin, * output: process.stdout, - * prompt: 'OHAI> ' + * prompt: 'OHAI> ', * }); * * rl.prompt(); @@ -440,15 +416,15 @@ declare module 'readline' { * well as a `for await...of` loop: * * ```js - * const fs = require('fs'); - * const readline = require('readline'); + * const fs = require('node:fs'); + * const readline = require('node:readline'); * * async function processLineByLine() { * const fileStream = fs.createReadStream('input.txt'); * * const rl = readline.createInterface({ * input: fileStream, - * crlfDelay: Infinity + * crlfDelay: Infinity, * }); * // Note: we use the crlfDelay option to recognize all instances of CR LF * // ('\r\n') in input.txt as a single line break. @@ -465,12 +441,12 @@ declare module 'readline' { * Alternatively, one could use the `'line'` event: * * ```js - * const fs = require('fs'); - * const readline = require('readline'); + * const fs = require('node:fs'); + * const readline = require('node:readline'); * * const rl = readline.createInterface({ * input: fs.createReadStream('sample.txt'), - * crlfDelay: Infinity + * crlfDelay: Infinity, * }); * * rl.on('line', (line) => { @@ -481,15 +457,15 @@ declare module 'readline' { * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: * * ```js - * const { once } = require('events'); - * const { createReadStream } = require('fs'); - * const { createInterface } = require('readline'); + * const { once } = require('node:events'); + * const { createReadStream } = require('node:fs'); + * const { createInterface } = require('node:readline'); * * (async function processLineByLine() { * try { * const rl = createInterface({ * input: createReadStream('big-file.txt'), - * crlfDelay: Infinity + * crlfDelay: Infinity, * }); * * rl.on('line', (line) => { @@ -539,109 +515,6 @@ declare module 'readline' { /** * The `readline.moveCursor()` method moves the cursor _relative_ to its current * position in a given `TTY` `stream`. - * - * ## Example: Tiny CLI - * - * The following example illustrates the use of `readline.Interface` class to - * implement a small command-line interface: - * - * ```js - * const readline = require('readline'); - * const rl = readline.createInterface({ - * input: process.stdin, - * output: process.stdout, - * prompt: 'OHAI> ' - * }); - * - * rl.prompt(); - * - * rl.on('line', (line) => { - * switch (line.trim()) { - * case 'hello': - * console.log('world!'); - * break; - * default: - * console.log(`Say what? I might have heard '${line.trim()}'`); - * break; - * } - * rl.prompt(); - * }).on('close', () => { - * console.log('Have a great day!'); - * process.exit(0); - * }); - * ``` - * - * ## Example: Read file stream line-by-Line - * - * A common use case for `readline` is to consume an input file one line at a - * time. The easiest way to do so is leveraging the `fs.ReadStream` API as - * well as a `for await...of` loop: - * - * ```js - * const fs = require('fs'); - * const readline = require('readline'); - * - * async function processLineByLine() { - * const fileStream = fs.createReadStream('input.txt'); - * - * const rl = readline.createInterface({ - * input: fileStream, - * crlfDelay: Infinity - * }); - * // Note: we use the crlfDelay option to recognize all instances of CR LF - * // ('\r\n') in input.txt as a single line break. - * - * for await (const line of rl) { - * // Each line in input.txt will be successively available here as `line`. - * console.log(`Line from file: ${line}`); - * } - * } - * - * processLineByLine(); - * ``` - * - * Alternatively, one could use the `'line'` event: - * - * ```js - * const fs = require('fs'); - * const readline = require('readline'); - * - * const rl = readline.createInterface({ - * input: fs.createReadStream('sample.txt'), - * crlfDelay: Infinity - * }); - * - * rl.on('line', (line) => { - * console.log(`Line from file: ${line}`); - * }); - * ``` - * - * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: - * - * ```js - * const { once } = require('events'); - * const { createReadStream } = require('fs'); - * const { createInterface } = require('readline'); - * - * (async function processLineByLine() { - * try { - * const rl = createInterface({ - * input: createReadStream('big-file.txt'), - * crlfDelay: Infinity - * }); - * - * rl.on('line', (line) => { - * // Process the line. - * }); - * - * await once(rl, 'close'); - * - * console.log('File processed.'); - * } catch (err) { - * console.error(err); - * } - * })(); - * ``` * @since v0.7.7 * @param callback Invoked once the operation completes. * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. diff --git a/node_modules/@types/node/ts4.8/readline/promises.d.ts b/node_modules/@types/node/ts4.8/readline/promises.d.ts index 8f9f06f..079fbdf 100644 --- a/node_modules/@types/node/ts4.8/readline/promises.d.ts +++ b/node_modules/@types/node/ts4.8/readline/promises.d.ts @@ -1,23 +1,28 @@ /** - * The `readline/promise` module provides an API for reading lines of input from a Readable stream one line at a time. - * - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline/promises.js) * @since v17.0.0 + * @experimental */ declare module 'readline/promises' { import { Interface as _Interface, ReadLineOptions, Completer, AsyncCompleter, Direction } from 'node:readline'; import { Abortable } from 'node:events'; - + /** + * Instances of the `readlinePromises.Interface` class are constructed using the`readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ class Interface extends _Interface { /** - * The rl.question() method displays the query by writing it to the output, waits for user input to be provided on input, - * then invokes the callback function passing the provided input as the first argument. + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. * - * When called, rl.question() will resume the input stream if it has been paused. + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. * - * If the readlinePromises.Interface was created with output set to null or undefined the query is not written. + * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. * - * If the question is called after rl.close(), it returns a rejected promise. + * If the question is called after `rl.close()`, it returns a rejected promise. * * Example usage: * @@ -26,7 +31,7 @@ declare module 'readline/promises' { * console.log(`Oh, so your favorite food is ${answer}`); * ``` * - * Using an AbortSignal to cancel a question. + * Using an `AbortSignal` to cancel a question. * * ```js * const signal = AbortSignal.timeout(10_000); @@ -38,61 +43,87 @@ declare module 'readline/promises' { * const answer = await rl.question('What is your favorite food? ', { signal }); * console.log(`Oh, so your favorite food is ${answer}`); * ``` - * * @since v17.0.0 - * @param query A statement or query to write to output, prepended to the prompt. + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. */ question(query: string): Promise; question(query: string, options: Abortable): Promise; } - + /** + * @since v17.0.0 + */ class Readline { /** * @param stream A TTY stream. */ - constructor(stream: NodeJS.WritableStream, options?: { autoCommit?: boolean }); + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + } + ); /** - * The `rl.clearLine()` method adds to the internal list of pending action an action that clears current line of the associated `stream` in a specified direction identified by `dir`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this */ clearLine(dir: Direction): this; /** - * The `rl.clearScreenDown()` method adds to the internal list of pending action an action that clears the associated `stream` from the current position of the cursor down. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this */ clearScreenDown(): this; /** - * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * The `rl.commit()` method sends all the pending actions to the associated`stream` and clears the internal list of pending actions. + * @since v17.0.0 */ commit(): Promise; /** - * The `rl.cursorTo()` method adds to the internal list of pending action an action that moves cursor to the specified position in the associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this */ cursorTo(x: number, y?: number): this; /** - * The `rl.moveCursor()` method adds to the internal list of pending action an action that moves the cursor relative to its current position in the associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless autoCommit: true was passed to the constructor. + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this */ moveCursor(dx: number, dy: number): this; /** - * The `rl.rollback()` method clears the internal list of pending actions without sending it to the associated `stream`. + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this */ rollback(): this; } - /** - * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface`instance. * * ```js * const readlinePromises = require('node:readline/promises'); * const rl = readlinePromises.createInterface({ * input: process.stdin, - * output: process.stdout + * output: process.stdout, * }); * ``` * - * Once the `readlinePromises.Interface` instance is created, the most common case is to listen for the `'line'` event: + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: * * ```js * rl.on('line', (line) => { @@ -100,42 +131,13 @@ declare module 'readline/promises' { * }); * ``` * - * If `terminal` is `true` for this instance then the `output` stream will get the best compatibility if it defines an `output.columns` property, - * and emits a `'resize'` event on the `output`, if or when the columns ever change (`process.stdout` does this automatically when it is a TTY). - * - * ## Use of the `completer` function - * - * The `completer` function takes the current line entered by the user as an argument, and returns an `Array` with 2 entries: - * - * - An Array with matching entries for the completion. - * - The substring that was used for the matching. - * - * For instance: `[[substr1, substr2, ...], originalsubstring]`. - * - * ```js - * function completer(line) { - * const completions = '.help .error .exit .quit .q'.split(' '); - * const hits = completions.filter((c) => c.startsWith(line)); - * // Show all completions if none found - * return [hits.length ? hits : completions, line]; - * } - * ``` - * - * The `completer` function can also returns a `Promise`, or be asynchronous: - * - * ```js - * async function completer(linePartial) { - * await someAsyncWork(); - * return [['123'], linePartial]; - * } - * ``` + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 */ - function createInterface( - input: NodeJS.ReadableStream, - output?: NodeJS.WritableStream, - completer?: Completer | AsyncCompleter, - terminal?: boolean, - ): Interface; + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; function createInterface(options: ReadLineOptions): Interface; } declare module 'node:readline/promises' { diff --git a/node_modules/@types/node/ts4.8/repl.d.ts b/node_modules/@types/node/ts4.8/repl.d.ts index be42ccc..c8147ed 100644 --- a/node_modules/@types/node/ts4.8/repl.d.ts +++ b/node_modules/@types/node/ts4.8/repl.d.ts @@ -1,12 +1,12 @@ /** - * The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that - * is available both as a standalone program or includible in other applications. - * It can be accessed using: + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/repl.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/repl.js) */ declare module 'repl' { import { Interface, Completer, AsyncCompleter } from 'node:readline'; @@ -41,8 +41,8 @@ declare module 'repl' { * error with `repl.Recoverable` to indicate the input was incomplete and prompt for * additional lines. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_custom_evaluation_functions */ eval?: REPLEval | undefined; /** @@ -74,13 +74,13 @@ declare module 'repl' { * The function to invoke to format the output of each command before writing to `output`. * Default: a wrapper for `util.inspect`. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_customizing_repl_output */ writer?: REPLWriter | undefined; /** * An optional function used for custom Tab auto completion. * - * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#readline_use_of_the_completer_function */ completer?: Completer | AsyncCompleter | undefined; /** @@ -124,7 +124,7 @@ declare module 'repl' { * or directly using the JavaScript `new` keyword. * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * * const options = { useColors: true }; * @@ -162,33 +162,33 @@ declare module 'repl' { /** * A value indicating whether the REPL is currently in "editor mode". * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_commands_and_special_keys */ readonly editorMode: boolean; /** * A value indicating whether the `_` variable has been assigned. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable */ readonly underscoreAssigned: boolean; /** * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable */ readonly last: any; /** * A value indicating whether the `_error` variable has been assigned. * * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable */ readonly underscoreErrAssigned: boolean; /** * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). * * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable */ readonly lastError: any; /** @@ -240,7 +240,7 @@ declare module 'repl' { * * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_class_replserver */ private constructor(); /** @@ -251,7 +251,7 @@ declare module 'repl' { * The following example shows two new commands added to the REPL instance: * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * * const replServer = repl.start({ prompt: '> ' }); * replServer.defineCommand('sayhello', { @@ -260,7 +260,7 @@ declare module 'repl' { * this.clearBufferedCommand(); * console.log(`Hello, ${name}!`); * this.displayPrompt(); - * } + * }, * }); * replServer.defineCommand('saybye', function saybye() { * console.log('Goodbye!'); @@ -401,7 +401,7 @@ declare module 'repl' { * If `options` is a string, then it specifies the input prompt: * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * * // a Unix style prompt * repl.start('$ '); @@ -412,7 +412,7 @@ declare module 'repl' { /** * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_recoverable_errors */ class Recoverable extends SyntaxError { err: Error; diff --git a/node_modules/@types/node/ts4.8/stream.d.ts b/node_modules/@types/node/ts4.8/stream.d.ts index a0df689..a6c80f9 100644 --- a/node_modules/@types/node/ts4.8/stream.d.ts +++ b/node_modules/@types/node/ts4.8/stream.d.ts @@ -1,24 +1,24 @@ /** * A stream is an abstract interface for working with streaming data in Node.js. - * The `stream` module provides an API for implementing the stream interface. + * The `node:stream` module provides an API for implementing the stream interface. * * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. * * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. * - * To access the `stream` module: + * To access the `node:stream` module: * * ```js - * const stream = require('stream'); + * const stream = require('node:stream'); * ``` * - * The `stream` module is useful for creating new types of stream instances. It is - * usually not necessary to use the `stream` module to consume streams. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/stream.js) + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/stream.js) */ declare module 'stream' { import { EventEmitter, Abortable } from 'node:events'; - import { Blob as NodeBlob } from "node:buffer"; + import { Blob as NodeBlob } from 'node:buffer'; import * as streamPromises from 'node:stream/promises'; import * as streamConsumers from 'node:stream/consumers'; import * as streamWeb from 'node:stream/web'; @@ -124,12 +124,12 @@ declare module 'stream' { readonly readableObjectMode: boolean; /** * Is `true` after `readable.destroy()` has been called. - * @since v18.0.0 + * @since v8.0.0 */ destroyed: boolean; /** - * Is true after 'close' has been emitted. - * @since v8.0.0 + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 */ readonly closed: boolean; /** @@ -310,7 +310,7 @@ declare module 'stream' { * the method does nothing. * * ```js - * const fs = require('fs'); + * const fs = require('node:fs'); * const readable = getReadableStreamSomehow(); * const writable = fs.createWriteStream('file.txt'); * // All the data from readable goes into 'file.txt', @@ -348,7 +348,7 @@ declare module 'stream' { * // Pull off a header delimited by \n\n. * // Use unshift() if we get too much. * // Call the callback with (error, header, stream). - * const { StringDecoder } = require('string_decoder'); + * const { StringDecoder } = require('node:string_decoder'); * function parseHeader(stream, callback) { * stream.on('error', callback); * stream.on('readable', onReadable); @@ -388,14 +388,14 @@ declare module 'stream' { * however it is best to simply avoid calling `readable.unshift()` while in the * process of performing a read. * @since v0.9.11 - * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array`, or `null`. For object mode * streams, `chunk` may be any JavaScript value. * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. */ unshift(chunk: any, encoding?: BufferEncoding): void; /** - * Prior to Node.js 0.10, streams did not implement the entire `stream` module API - * as it is currently defined. (See `Compatibility` for more information.) + * Prior to Node.js 0.10, streams did not implement the entire `node:stream`module API as it is currently defined. (See `Compatibility` for more + * information.) * * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` * stream that uses @@ -407,7 +407,7 @@ declare module 'stream' { * * ```js * const { OldReader } = require('./old-api-module.js'); - * const { Readable } = require('stream'); + * const { Readable } = require('node:stream'); * const oreader = new OldReader(); * const myReader = new Readable().wrap(oreader); * @@ -534,7 +534,7 @@ declare module 'stream' { static toWeb(streamWritable: Writable): streamWeb.WritableStream; /** * Is `true` if it is safe to call `writable.write()`, which means - * the stream has not been destroyed, errored or ended. + * the stream has not been destroyed, errored, or ended. * @since v11.4.0 */ readonly writable: boolean; @@ -578,8 +578,8 @@ declare module 'stream' { */ destroyed: boolean; /** - * Is true after 'close' has been emitted. - * @since v8.0.0 + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 */ readonly closed: boolean; /** @@ -588,7 +588,7 @@ declare module 'stream' { */ readonly errored: Error | null; /** - * Is `true` if the stream's buffer has been full and stream will emit 'drain'. + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. * @since v15.2.0, v14.17.0 */ readonly writableNeedDrain: boolean; @@ -678,7 +678,7 @@ declare module 'stream' { * * ```js * // Write 'hello, ' and then end with 'world!'. - * const fs = require('fs'); + * const fs = require('node:fs'); * const file = fs.createWriteStream('example.txt'); * file.write('hello, '); * file.end('world!'); @@ -864,7 +864,7 @@ declare module 'stream' { /** * If `false` then the stream will automatically end the writable side when the * readable side ends. Set initially by the `allowHalfOpen` constructor option, - * which defaults to `false`. + * which defaults to `true`. * * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is * emitted. @@ -912,6 +912,105 @@ declare module 'stream' { end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; cork(): void; uncork(): void; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: any) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'pipe', listener: (src: Readable) => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'unpipe', listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: any): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pause'): boolean; + emit(event: 'pipe', src: Readable): boolean; + emit(event: 'readable'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'unpipe', src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: any) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'pipe', listener: (src: Readable) => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'unpipe', listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: any) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'pipe', listener: (src: Readable) => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'unpipe', listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: any) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: Readable) => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: any) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'data', listener: (chunk: any) => void): this; + removeListener(event: 'drain', listener: () => void): this; + removeListener(event: 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'finish', listener: () => void): this; + removeListener(event: 'pause', listener: () => void): this; + removeListener(event: 'pipe', listener: (src: Readable) => void): this; + removeListener(event: 'readable', listener: () => void): this; + removeListener(event: 'resume', listener: () => void): this; + removeListener(event: 'unpipe', listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; } type TransformCallback = (error?: Error | null, data?: any) => void; interface TransformOptions extends DuplexOptions { @@ -953,18 +1052,21 @@ declare module 'stream' { */ class PassThrough extends Transform {} /** + * A stream to attach a signal to. + * * Attaches an AbortSignal to a readable or writeable stream. This lets code * control stream destruction using an `AbortController`. * - * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream, and `controller.error(new + * AbortError())` for webstreams. * * ```js - * const fs = require('fs'); + * const fs = require('node:fs'); * * const controller = new AbortController(); * const read = addAbortSignal( * controller.signal, - * fs.createReadStream(('object.json')) + * fs.createReadStream(('object.json')), * ); * // Later, abort the operation closing the stream * controller.abort(); @@ -977,7 +1079,7 @@ declare module 'stream' { * setTimeout(() => controller.abort(), 10_000); // set a timeout * const stream = addAbortSignal( * controller.signal, - * fs.createReadStream(('object.json')) + * fs.createReadStream(('object.json')), * ); * (async () => { * try { @@ -993,22 +1095,70 @@ declare module 'stream' { * } * })(); * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` * @since v15.4.0 * @param signal A signal representing possible cancellation * @param stream a stream to attach a signal to */ function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `16384` (16 KiB), or `16` for `objectMode`. + * @since v19.9.0 + * @param objectMode + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param objectMode + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; interface FinishedOptions extends Abortable { error?: boolean | undefined; readable?: boolean | undefined; writable?: boolean | undefined; } /** + * A readable and/or writable stream/webstream. + * * A function to get notified when a stream is no longer readable, writable * or has experienced an error or a premature close event. * * ```js - * const { finished } = require('stream'); + * const { finished } = require('node:stream'); + * const fs = require('node:fs'); * * const rs = fs.createReadStream('archive.tar'); * @@ -1026,21 +1176,7 @@ declare module 'stream' { * Especially useful in error handling scenarios where a stream is destroyed * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. * - * The `finished` API provides promise version: - * - * ```js - * const { finished } = require('stream/promises'); - * - * const rs = fs.createReadStream('archive.tar'); - * - * async function run() { - * await finished(rs); - * console.log('Stream is done reading.'); - * } - * - * run().catch(console.error); - * rs.resume(); // Drain the stream. - * ``` + * The `finished` API provides `promise version`. * * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been * invoked. The reason for this is so that unexpected `'error'` events (due to @@ -1080,16 +1216,17 @@ declare module 'stream' { : (err: NodeJS.ErrnoException | null) => void; type PipelinePromise> = S extends PipelineDestinationPromiseFunction ? Promise

: Promise; interface PipelineOptions { - signal: AbortSignal; + signal?: AbortSignal | undefined; + end?: boolean | undefined; } /** * A module method to pipe between streams and generators forwarding errors and * properly cleaning up and provide a callback when the pipeline is complete. * * ```js - * const { pipeline } = require('stream'); - * const fs = require('fs'); - * const zlib = require('zlib'); + * const { pipeline } = require('node:stream'); + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); * * // Use the pipeline API to easily pipe a series of streams * // together and get notified when the pipeline is fully done. @@ -1106,95 +1243,11 @@ declare module 'stream' { * } else { * console.log('Pipeline succeeded.'); * } - * } + * }, * ); * ``` * - * The `pipeline` API provides a promise version, which can also - * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with - * an`AbortError`. - * - * ```js - * const { pipeline } = require('stream/promises'); - * - * async function run() { - * await pipeline( - * fs.createReadStream('archive.tar'), - * zlib.createGzip(), - * fs.createWriteStream('archive.tar.gz') - * ); - * console.log('Pipeline succeeded.'); - * } - * - * run().catch(console.error); - * ``` - * - * To use an `AbortSignal`, pass it inside an options object, - * as the last argument: - * - * ```js - * const { pipeline } = require('stream/promises'); - * - * async function run() { - * const ac = new AbortController(); - * const signal = ac.signal; - * - * setTimeout(() => ac.abort(), 1); - * await pipeline( - * fs.createReadStream('archive.tar'), - * zlib.createGzip(), - * fs.createWriteStream('archive.tar.gz'), - * { signal }, - * ); - * } - * - * run().catch(console.error); // AbortError - * ``` - * - * The `pipeline` API also supports async generators: - * - * ```js - * const { pipeline } = require('stream/promises'); - * const fs = require('fs'); - * - * async function run() { - * await pipeline( - * fs.createReadStream('lowercase.txt'), - * async function* (source, { signal }) { - * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. - * for await (const chunk of source) { - * yield await processChunk(chunk, { signal }); - * } - * }, - * fs.createWriteStream('uppercase.txt') - * ); - * console.log('Pipeline succeeded.'); - * } - * - * run().catch(console.error); - * ``` - * - * Remember to handle the `signal` argument passed into the async generator. - * Especially in the case where the async generator is the source for the - * pipeline (i.e. first argument) or the pipeline will never complete. - * - * ```js - * const { pipeline } = require('stream/promises'); - * const fs = require('fs'); - * - * async function run() { - * await pipeline( - * async function* ({ signal }) { - * await someLongRunningfn({ signal }); - * yield 'asd'; - * }, - * fs.createWriteStream('uppercase.txt') - * ); - * console.log('Pipeline succeeded.'); - * } - * - * run().catch(console.error); - * ``` + * The `pipeline` API provides a `promise version`. * * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: * @@ -1213,9 +1266,9 @@ declare module 'stream' { * See the example below: * * ```js - * const fs = require('fs'); - * const http = require('http'); - * const { pipeline } = require('stream'); + * const fs = require('node:fs'); + * const http = require('node:http'); + * const { pipeline } = require('node:stream'); * * const server = http.createServer((req, res) => { * const fileStream = fs.createReadStream('./fileNotExist.txt'); @@ -1316,19 +1369,18 @@ declare module 'stream' { ref(): void; unref(): void; } - /** * Returns whether the stream has encountered an error. - * @since v17.3.0 + * @since v17.3.0, v16.14.0 + * @experimental */ function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; - /** * Returns whether the stream is readable. - * @since v17.4.0 + * @since v17.4.0, v16.14.0 + * @experimental */ function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; - const promises: typeof streamPromises; const consumers: typeof streamConsumers; } diff --git a/node_modules/@types/node/ts4.8/stream/consumers.d.ts b/node_modules/@types/node/ts4.8/stream/consumers.d.ts index 1ebf12e..2fd9424 100644 --- a/node_modules/@types/node/ts4.8/stream/consumers.d.ts +++ b/node_modules/@types/node/ts4.8/stream/consumers.d.ts @@ -1,5 +1,5 @@ declare module 'stream/consumers' { - import { Blob as NodeBlob } from "node:buffer"; + import { Blob as NodeBlob } from 'node:buffer'; import { Readable } from 'node:stream'; function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; diff --git a/node_modules/@types/node/ts4.8/string_decoder.d.ts b/node_modules/@types/node/ts4.8/string_decoder.d.ts index a585804..a069bb8 100644 --- a/node_modules/@types/node/ts4.8/string_decoder.d.ts +++ b/node_modules/@types/node/ts4.8/string_decoder.d.ts @@ -1,16 +1,16 @@ /** - * The `string_decoder` module provides an API for decoding `Buffer` objects into - * strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 * characters. It can be accessed using: * * ```js - * const { StringDecoder } = require('string_decoder'); + * const { StringDecoder } = require('node:string_decoder'); * ``` * * The following example shows the basic use of the `StringDecoder` class. * * ```js - * const { StringDecoder } = require('string_decoder'); + * const { StringDecoder } = require('node:string_decoder'); * const decoder = new StringDecoder('utf8'); * * const cent = Buffer.from([0xC2, 0xA2]); @@ -29,14 +29,14 @@ * symbol (`€`) are written over three separate operations: * * ```js - * const { StringDecoder } = require('string_decoder'); + * const { StringDecoder } = require('node:string_decoder'); * const decoder = new StringDecoder('utf8'); * * decoder.write(Buffer.from([0xE2])); * decoder.write(Buffer.from([0x82])); * console.log(decoder.end(Buffer.from([0xAC]))); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/string_decoder.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/string_decoder.js) */ declare module 'string_decoder' { class StringDecoder { diff --git a/node_modules/@types/node/ts4.8/test.d.ts b/node_modules/@types/node/ts4.8/test.d.ts index 8e20710..5202454 100644 --- a/node_modules/@types/node/ts4.8/test.d.ts +++ b/node_modules/@types/node/ts4.8/test.d.ts @@ -1,28 +1,112 @@ /** - * The `node:test` module provides a standalone testing module. - * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/test.js) + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the`Promise` rejects, and is considered passing if the `Promise` resolves. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the`test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/test.js) */ declare module 'node:test' { + import { Readable } from 'node:stream'; /** - * Programmatically start the test runner. - * @since v18.9.0 - * @param options Configuration options for running tests. - * @returns A {@link TapStream} that emits events about the test execution. + * ```js + * import { tap } from 'node:test/reporters'; + * import process from 'node:process'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. The following properties are supported: */ - function run(options?: RunOptions): TapStream; - + function run(options?: RunOptions): TestsStream; /** - * The `test()` function is the value imported from the test module. Each invocation of this - * function results in the creation of a test point in the TAP output. + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. * - * The {@link TestContext} object passed to the fn argument can be used to perform actions - * related to the current test. Examples include skipping the test, adding additional TAP - * diagnostic information, or creating subtests. + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. * - * `test()` returns a {@link Promise} that resolves once the test completes. The return value - * can usually be discarded for top level tests. However, the return value from subtests should - * be used to prevent the parent test from finishing first and cancelling the subtest as shown - * in the following example. + * `test()` returns a `Promise` that resolves once the test completes. + * if `test()` is called within a `describe()` block, it resolve immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. * * ```js * test('top level test', async (t) => { @@ -36,90 +120,144 @@ declare module 'node:test' { * }); * }); * ``` - * @since v18.0.0 - * @param name The name of the test, which is displayed when reporting test results. - * Default: The `name` property of fn, or `''` if `fn` does not have a name. - * @param options Configuration options for the test - * @param fn The function under test. The first argument to this function is a - * {@link TestContext} object. If the test uses callbacks, the callback function is - * passed as the second argument. Default: A no-op function. - * @returns A {@link Promise} resolved with `undefined` once the test completes. + * + * The `timeout` option can be used to fail the test if it takes longer than`timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param [name='The name'] The name of the test, which is displayed when reporting test results. + * @param options Configuration options for the test. The following properties are supported: + * @param [fn='A no-op function'] The function under test. The first argument to this function is a {@link TestContext} object. If the test uses callbacks, the callback function is passed as the + * second argument. + * @return Resolved with `undefined` once the test completes, or immediately if the test runs within {@link describe}. */ function test(name?: string, fn?: TestFn): Promise; function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; function test(options?: TestOptions, fn?: TestFn): Promise; function test(fn?: TestFn): Promise; - + namespace test { + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + run, + mock, + test, + skip, + todo, + only + }; + } /** - * @since v18.6.0 - * @param name The name of the suite, which is displayed when reporting suite results. - * Default: The `name` property of fn, or `''` if `fn` does not have a name. - * @param options Configuration options for the suite - * @param fn The function under suite. Default: A no-op function. + * The `describe()` function imported from the `node:test` module. Each + * invocation of this function results in the creation of a Subtest. + * After invocation of top level `describe` functions, + * all top level tests and suites will execute. + * @param [name='The name'] The name of the suite, which is displayed when reporting test results. + * @param options Configuration options for the suite. supports the same options as `test([name][, options][, fn])`. + * @param [fn='A no-op function'] The function under suite declaring all subtests and subsuites. The first argument to this function is a {@link SuiteContext} object. + * @return `undefined`. */ function describe(name?: string, options?: TestOptions, fn?: SuiteFn): void; function describe(name?: string, fn?: SuiteFn): void; function describe(options?: TestOptions, fn?: SuiteFn): void; function describe(fn?: SuiteFn): void; namespace describe { - // Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + /** + * Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + */ function skip(name?: string, options?: TestOptions, fn?: SuiteFn): void; function skip(name?: string, fn?: SuiteFn): void; function skip(options?: TestOptions, fn?: SuiteFn): void; function skip(fn?: SuiteFn): void; - - // Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + /** + * Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + */ function todo(name?: string, options?: TestOptions, fn?: SuiteFn): void; function todo(name?: string, fn?: SuiteFn): void; function todo(options?: TestOptions, fn?: SuiteFn): void; function todo(fn?: SuiteFn): void; + /** + * Shorthand for marking a suite as `only`, same as `describe([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): void; + function only(name?: string, fn?: SuiteFn): void; + function only(options?: TestOptions, fn?: SuiteFn): void; + function only(fn?: SuiteFn): void; } - /** - * @since v18.6.0 - * @param name The name of the test, which is displayed when reporting test results. - * Default: The `name` property of fn, or `''` if `fn` does not have a name. - * @param options Configuration options for the test - * @param fn The function under test. If the test uses callbacks, the callback function is - * passed as the second argument. Default: A no-op function. + * Shorthand for `test()`. + * + * The `it()` function is imported from the `node:test` module. + * @since v18.6.0, v16.17.0 */ - function it(name?: string, options?: TestOptions, fn?: ItFn): void; - function it(name?: string, fn?: ItFn): void; - function it(options?: TestOptions, fn?: ItFn): void; - function it(fn?: ItFn): void; + function it(name?: string, options?: TestOptions, fn?: TestFn): void; + function it(name?: string, fn?: TestFn): void; + function it(options?: TestOptions, fn?: TestFn): void; + function it(fn?: TestFn): void; namespace it { - // Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. - function skip(name?: string, options?: TestOptions, fn?: ItFn): void; - function skip(name?: string, fn?: ItFn): void; - function skip(options?: TestOptions, fn?: ItFn): void; - function skip(fn?: ItFn): void; - - // Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. - function todo(name?: string, options?: TestOptions, fn?: ItFn): void; - function todo(name?: string, fn?: ItFn): void; - function todo(options?: TestOptions, fn?: ItFn): void; - function todo(fn?: ItFn): void; + /** + * Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): void; + function skip(name?: string, fn?: TestFn): void; + function skip(options?: TestOptions, fn?: TestFn): void; + function skip(fn?: TestFn): void; + /** + * Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): void; + function todo(name?: string, fn?: TestFn): void; + function todo(options?: TestOptions, fn?: TestFn): void; + function todo(fn?: TestFn): void; + /** + * Shorthand for marking a test as `only`, same as `it([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): void; + function only(name?: string, fn?: TestFn): void; + function only(options?: TestOptions, fn?: TestFn): void; + function only(fn?: TestFn): void; } - + /** + * Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): void; + function skip(name?: string, fn?: TestFn): void; + function skip(options?: TestOptions, fn?: TestFn): void; + function skip(fn?: TestFn): void; + /** + * Shorthand for marking a test as `TODO`, same as `test([name], { todo: true }[, fn])`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): void; + function todo(name?: string, fn?: TestFn): void; + function todo(options?: TestOptions, fn?: TestFn): void; + function todo(fn?: TestFn): void; + /** + * Shorthand for marking a test as `only`, same as `test([name], { only: true }[, fn])`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): void; + function only(name?: string, fn?: TestFn): void; + function only(options?: TestOptions, fn?: TestFn): void; + function only(fn?: TestFn): void; /** * The type of a function under test. The first argument to this function is a * {@link TestContext} object. If the test uses callbacks, the callback function is passed as * the second argument. */ type TestFn = (t: TestContext, done: (result?: any) => void) => any; - /** * The type of a function under Suite. * If the test uses callbacks, the callback function is passed as an argument */ type SuiteFn = (done: (result?: any) => void) => void; - - /** - * The type of a function under test. - * If the test uses callbacks, the callback function is passed as an argument - */ - type ItFn = (done: (result?: any) => void) => any; - interface RunOptions { /** * If a number is provided, then that many files would run in parallel. @@ -129,132 +267,189 @@ declare module 'node:test' { * @default true */ concurrency?: number | boolean | undefined; - /** * An array containing the list of files to run. * If unspecified, the test runner execution model will be used. */ files?: readonly string[] | undefined; - /** * Allows aborting an in-progress test execution. * @default undefined */ signal?: AbortSignal | undefined; - /** * A number of milliseconds the test will fail after. * If unspecified, subtests inherit this value from their parent. * @default Infinity */ timeout?: number | undefined; - /** * Sets inspector port of test child process. * If a nullish value is provided, each process gets its own port, * incremented from the primary's `process.debugPort`. */ inspectPort?: number | (() => number) | undefined; + /** + * That can be used to only run tests whose name matches the provided pattern. + * Test name patterns are interpreted as JavaScript regular expressions. + * For each test that is executed, any corresponding test hooks, such as `beforeEach()`, are also run. + */ + testNamePatterns?: string | RegExp | string[] | RegExp[]; } - /** - * A successful call of the `run()` method will return a new `TapStream` object, - * streaming a [TAP](https://testanything.org/) output. - * `TapStream` will emit events in the order of the tests' definitions. - * @since v18.9.0 + * A successful call to `run()` method will return a new `TestsStream` object, streaming a series of events representing the execution of the tests.`TestsStream` will emit events, in the + * order of the tests definition + * @since v18.9.0, v16.19.0 */ - interface TapStream extends NodeJS.ReadableStream { - addListener(event: 'test:diagnostic', listener: (message: string) => void): this; + class TestsStream extends Readable implements NodeJS.ReadableStream { + addListener(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; addListener(event: 'test:fail', listener: (data: TestFail) => void): this; addListener(event: 'test:pass', listener: (data: TestPass) => void): this; + addListener(event: 'test:plan', listener: (data: TestPlan) => void): this; + addListener(event: 'test:start', listener: (data: TestStart) => void): this; addListener(event: string, listener: (...args: any[]) => void): this; - emit(event: 'test:diagnostic', message: string): boolean; + emit(event: 'test:diagnostic', data: DiagnosticData): boolean; emit(event: 'test:fail', data: TestFail): boolean; emit(event: 'test:pass', data: TestPass): boolean; + emit(event: 'test:plan', data: TestPlan): boolean; + emit(event: 'test:start', data: TestStart): boolean; emit(event: string | symbol, ...args: any[]): boolean; - on(event: 'test:diagnostic', listener: (message: string) => void): this; + on(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; on(event: 'test:fail', listener: (data: TestFail) => void): this; on(event: 'test:pass', listener: (data: TestPass) => void): this; + on(event: 'test:plan', listener: (data: TestPlan) => void): this; + on(event: 'test:start', listener: (data: TestStart) => void): this; on(event: string, listener: (...args: any[]) => void): this; - once(event: 'test:diagnostic', listener: (message: string) => void): this; + once(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; once(event: 'test:fail', listener: (data: TestFail) => void): this; once(event: 'test:pass', listener: (data: TestPass) => void): this; + once(event: 'test:plan', listener: (data: TestPlan) => void): this; + once(event: 'test:start', listener: (data: TestStart) => void): this; once(event: string, listener: (...args: any[]) => void): this; - prependListener(event: 'test:diagnostic', listener: (message: string) => void): this; + prependListener(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; prependListener(event: 'test:fail', listener: (data: TestFail) => void): this; prependListener(event: 'test:pass', listener: (data: TestPass) => void): this; + prependListener(event: 'test:plan', listener: (data: TestPlan) => void): this; + prependListener(event: 'test:start', listener: (data: TestStart) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: 'test:diagnostic', listener: (message: string) => void): this; + prependOnceListener(event: 'test:diagnostic', listener: (data: DiagnosticData) => void): this; prependOnceListener(event: 'test:fail', listener: (data: TestFail) => void): this; prependOnceListener(event: 'test:pass', listener: (data: TestPass) => void): this; + prependOnceListener(event: 'test:plan', listener: (data: TestPlan) => void): this; + prependOnceListener(event: 'test:start', listener: (data: TestStart) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; } - + interface DiagnosticData { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + } interface TestFail { /** - * The test duration. + * Additional execution metadata. */ - duration: number; - - /** - * The failure casing test to fail. - */ - error: Error; - + details: { + /** + * The duration of the test in milliseconds. + */ + duration: number; + /** + * The error thrown by the test. + */ + error: Error; + }; /** * The test name. */ name: string; - + /** + * The nesting level of the test. + */ + nesting: number; /** * The ordinal number of the test. */ testNumber: number; - /** * Present if `context.todo` is called. */ - todo?: string; - + todo?: string | boolean; /** * Present if `context.skip` is called. */ - skip?: string; + skip?: string | boolean; } - interface TestPass { /** - * The test duration. + * Additional execution metadata. */ - duration: number; - + details: { + /** + * The duration of the test in milliseconds. + */ + duration: number; + }; /** * The test name. */ name: string; - + /** + * The nesting level of the test. + */ + nesting: number; /** * The ordinal number of the test. */ testNumber: number; - /** * Present if `context.todo` is called. */ - todo?: string; - + todo?: string | boolean; /** * Present if `context.skip` is called. */ - skip?: string; + skip?: string | boolean; + } + interface TestPlan { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; } - /** - * An instance of `TestContext` is passed to each test function in order to interact with the - * test runner. However, the `TestContext` constructor is not exposed as part of the API. - * @since v18.0.0 + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 */ - interface TestContext { + class TestContext { + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v20.1.0 + */ + before: typeof before; /** * This function is used to create a hook running before each subtest of the current test. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as @@ -263,7 +458,14 @@ declare module 'node:test' { * @since v18.8.0 */ beforeEach: typeof beforeEach; - + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after: typeof after; /** * This function is used to create a hook running after each subtest of the current test. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as @@ -272,54 +474,84 @@ declare module 'node:test' { * @since v18.8.0 */ afterEach: typeof afterEach; - /** - * This function is used to write TAP diagnostics to the output. Any diagnostic information is - * included at the end of the test's results. This function does not return a value. - * @param message Message to be displayed as a TAP diagnostic. - * @since v18.0.0 + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. */ diagnostic(message: string): void; - /** * The name of the test. - * @since v18.8.0 + * @since v18.8.0, v16.18.0 */ readonly name: string; - /** - * If `shouldRunOnlyTests` is truthy, the test context will only run tests that have the `only` - * option set. Otherwise, all tests are run. If Node.js was not started with the `--test-only` - * command-line option, this function is a no-op. + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 * @param shouldRunOnlyTests Whether or not to run `only` tests. - * @since v18.0.0 */ runOnly(shouldRunOnlyTests: boolean): void; - /** - * Can be used to abort test subtasks when the test has been aborted. - * @since v18.7.0 + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 */ readonly signal: AbortSignal; - /** - * This function causes the test's output to indicate the test as skipped. If `message` is - * provided, it is included in the TAP output. Calling `skip()` does not terminate execution of - * the test function. This function does not return a value. - * @param message Optional skip message to be displayed in TAP output. - * @since v18.0.0 + * This function causes the test's output to indicate the test as skipped. If`message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. */ skip(message?: string): void; - /** - * This function adds a `TODO` directive to the test's output. If `message` is provided, it is - * included in the TAP output. Calling `todo()` does not terminate execution of the test - * function. This function does not return a value. - * @param message Optional `TODO` message to be displayed in TAP output. - * @since v18.0.0 + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. */ todo(message?: string): void; - /** * This function is used to create subtests under the current test. This function behaves in * the same fashion as the top level {@link test} function. @@ -333,8 +565,11 @@ declare module 'node:test' { * @returns A {@link Promise} resolved with `undefined` once the test completes. */ test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; } - interface TestOptions { /** * If a number is provided, then that many tests would run in parallel. @@ -345,27 +580,23 @@ declare module 'node:test' { * @default false */ concurrency?: number | boolean | undefined; - /** * If truthy, and the test context is configured to run `only` tests, then this test will be * run. Otherwise, the test is skipped. * @default false */ only?: boolean | undefined; - /** * Allows aborting an in-progress test. * @since v18.8.0 */ signal?: AbortSignal | undefined; - /** * If truthy, the test is skipped. If a string is provided, that string is displayed in the * test results as the reason for skipping the test. * @default false */ skip?: boolean | string | undefined; - /** * A number of milliseconds the test will fail after. If unspecified, subtests inherit this * value from their parent. @@ -373,7 +604,6 @@ declare module 'node:test' { * @since v18.7.0 */ timeout?: number | undefined; - /** * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in * the test results as the reason why the test is `TODO`. @@ -381,49 +611,77 @@ declare module 'node:test' { */ todo?: boolean | string | undefined; } - /** * This function is used to create a hook running before running a suite. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: */ function before(fn?: HookFn, options?: HookOptions): void; - /** - * This function is used to create a hook running after running a suite. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 + * This function is used to create a hook running after running a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: */ function after(fn?: HookFn, options?: HookOptions): void; - /** - * This function is used to create a hook running before each subtest of the current suite. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 + * This function is used to create a hook running + * before each subtest of the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: */ function beforeEach(fn?: HookFn, options?: HookOptions): void; - /** - * This function is used to create a hook running after each subtest of the current test. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 + * This function is used to create a hook running + * after each subtest of the current test. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: */ function afterEach(fn?: HookFn, options?: HookOptions): void; - /** * The hook function. If the hook uses callbacks, the callback function is passed as the * second argument. */ type HookFn = (done: (result?: any) => void) => any; - /** * Configuration options for hooks. * @since v18.8.0 @@ -433,7 +691,6 @@ declare module 'node:test' { * Allows aborting an in-progress hook. */ signal?: AbortSignal | undefined; - /** * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this * value from their parent. @@ -441,6 +698,355 @@ declare module 'node:test' { */ timeout?: number | undefined; } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + type NoOpFunction = (...args: any[]) => undefined; + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's`mock` property. + * @since v19.1.0, v18.13.0 + */ + class MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param [original='A no-op function'] An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. The following properties are supported: + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn(original?: F, implementation?: Implementation, options?: MockFunctionOptions): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. The following properties are supported: + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function + ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function + ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; - export { test as default, run, test, describe, it, before, after, beforeEach, afterEach }; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter`set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter`set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the`MockTracker` instance. Once disassociated, the mocks can still be used, but the`MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's`MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T + ? T + : F extends abstract new (...args: any) => infer T + ? T + : unknown, + Args = F extends (...args: infer Y) => any + ? Y + : F extends abstract new (...args: infer Y) => any + ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new (...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + class MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: Array>; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls`is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: Function): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: Function, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + export { test as default, run, test, describe, it, before, after, beforeEach, afterEach, mock, skip, only, todo }; } diff --git a/node_modules/@types/node/ts4.8/timers.d.ts b/node_modules/@types/node/ts4.8/timers.d.ts index b26f3ce..5abcdca 100644 --- a/node_modules/@types/node/ts4.8/timers.d.ts +++ b/node_modules/@types/node/ts4.8/timers.d.ts @@ -1,12 +1,12 @@ /** * The `timer` module exposes a global API for scheduling functions to * be called at some future period of time. Because the timer functions are - * globals, there is no need to call `require('timers')` to use the API. + * globals, there is no need to call `require('node:timers')` to use the API. * * The timer functions within Node.js implement a similar API as the timers API * provided by Web Browsers but use a different internal implementation that is * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/timers.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/timers.js) */ declare module 'timers' { import { Abortable } from 'node:events'; @@ -33,7 +33,35 @@ declare module 'timers' { refresh(): this; [Symbol.toPrimitive](): number; } - interface Immediate extends RefCounted { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`functions that can be used to + * control this default behavior. + */ + class Immediate implements RefCounted { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @return a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @return a reference to `immediate` + */ + unref(): this; /** * If true, the `Immediate` object will keep the Node.js event loop active. * @since v11.0.0 @@ -41,7 +69,33 @@ declare module 'timers' { hasRef(): boolean; _onImmediate: Function; // to distinguish it from the Timeout class } - interface Timeout extends Timer { + /** + * This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the + * scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + class Timeout implements Timer { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @return a reference to `timeout` + */ + ref(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling`timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @return a reference to `timeout` + */ + unref(): this; /** * If true, the `Timeout` object will keep the Node.js event loop active. * @since v11.0.0 @@ -62,6 +116,25 @@ declare module 'timers' { [Symbol.toPrimitive](): number; } } + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay`will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearTimeout} + */ function setTimeout(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout; // util.promisify no rest args compability // tslint:disable-next-line void-return @@ -69,7 +142,27 @@ declare module 'timers' { namespace setTimeout { const __promisify__: typeof setTimeoutPromise; } + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. + */ function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be + * set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearInterval} + */ function setInterval(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer; // util.promisify no rest args compability // tslint:disable-next-line void-return @@ -77,7 +170,30 @@ declare module 'timers' { namespace setInterval { const __promisify__: typeof setIntervalPromise; } + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. + */ function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of the Node.js `Event Loop` + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearImmediate} + */ function setImmediate(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate; // util.promisify no rest args compability // tslint:disable-next-line void-return @@ -85,6 +201,11 @@ declare module 'timers' { namespace setImmediate { const __promisify__: typeof setImmediatePromise; } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by {@link setImmediate}. + */ function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; function queueMicrotask(callback: () => void): void; } diff --git a/node_modules/@types/node/ts4.8/timers/promises.d.ts b/node_modules/@types/node/ts4.8/timers/promises.d.ts index c145068..299a355 100644 --- a/node_modules/@types/node/ts4.8/timers/promises.d.ts +++ b/node_modules/@types/node/ts4.8/timers/promises.d.ts @@ -1,6 +1,6 @@ /** * The `timers/promises` API provides an alternative set of timer functions - * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * that return `Promise` objects. The API is accessible via`require('node:timers/promises')`. * * ```js * import { @@ -44,6 +44,8 @@ declare module 'timers/promises' { function setImmediate(value?: T, options?: TimerOptions): Promise; /** * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. * * ```js * import { @@ -62,7 +64,6 @@ declare module 'timers/promises' { * @since v15.9.0 */ function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; - interface Scheduler { /** * ```js @@ -85,7 +86,6 @@ declare module 'timers/promises' { */ yield: () => Promise; } - const scheduler: Scheduler; } declare module 'node:timers/promises' { diff --git a/node_modules/@types/node/ts4.8/tls.d.ts b/node_modules/@types/node/ts4.8/tls.d.ts index 2cbc716..13ee563 100644 --- a/node_modules/@types/node/ts4.8/tls.d.ts +++ b/node_modules/@types/node/ts4.8/tls.d.ts @@ -1,12 +1,12 @@ /** - * The `tls` module provides an implementation of the Transport Layer Security + * The `node:tls` module provides an implementation of the Transport Layer Security * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. * The module can be accessed using: * * ```js - * const tls = require('tls'); + * const tls = require('node:tls'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tls.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tls.js) */ declare module 'tls' { import { X509Certificate } from 'node:crypto'; @@ -41,21 +41,100 @@ declare module 'tls' { CN: string; } interface PeerCertificate { - subject: Certificate; - issuer: Certificate; - subjectaltname: string; - infoAccess: NodeJS.Dict; - modulus: string; - exponent: string; - valid_from: string; - valid_to: string; - fingerprint: string; - fingerprint256: string; - ext_key_usage: string[]; - serialNumber: string; + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve,if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; } interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ issuerCertificate: DetailedPeerCertificate; } interface CipherNameAndProtocol { @@ -133,7 +212,7 @@ declare module 'tls' { * * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. * - * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the * connection is open. * @since v0.11.4 */ @@ -180,13 +259,13 @@ declare module 'tls' { /** * Returns an object containing information on the negotiated cipher suite. * - * For example: + * For example, a TLSv1.2 protocol with AES256-SHA cipher: * * ```json * { - * "name": "AES128-SHA256", - * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", - * "version": "TLSv1.2" + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" * } * ``` * @@ -558,7 +637,8 @@ declare module 'tls' { * used. * @since v0.5.3 * @param hostname A SNI host name or wildcard (e.g. `'*'`) - * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. */ addContext(hostname: string, context: SecureContextOptions): void; /** @@ -689,12 +769,9 @@ declare module 'tls' { */ crl?: string | Buffer | Array | undefined; /** - * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use - * openssl dhparam to create the parameters. The key length must be - * greater than or equal to 1024 bits or else an error will be thrown. - * Although 1024 bits is permissible, use 2048 bits or larger for - * stronger security. If omitted or invalid, the parameters are - * silently discarded and DHE ciphers will not be available. + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. */ dhparam?: string | Buffer | undefined; /** @@ -836,14 +913,14 @@ declare module 'tls' { * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is * automatically set as a listener for the `'secureConnection'` event. * - * The `ticketKeys` options is automatically shared between `cluster` module + * The `ticketKeys` options is automatically shared between `node:cluster` module * workers. * * The following illustrates a simple echo server: * * ```js - * const tls = require('tls'); - * const fs = require('fs'); + * const tls = require('node:tls'); + * const fs = require('node:fs'); * * const options = { * key: fs.readFileSync('server-key.pem'), @@ -853,7 +930,7 @@ declare module 'tls' { * requestCert: true, * * // This is necessary only if the client uses a self-signed certificate. - * ca: [ fs.readFileSync('client-cert.pem') ] + * ca: [ fs.readFileSync('client-cert.pem') ], * }; * * const server = tls.createServer(options, (socket) => { @@ -888,8 +965,8 @@ declare module 'tls' { * * ```js * // Assumes an echo server that is listening on port 8000. - * const tls = require('tls'); - * const fs = require('fs'); + * const tls = require('node:tls'); + * const fs = require('node:fs'); * * const options = { * // Necessary only if the server requires client certificate authentication. @@ -965,12 +1042,19 @@ declare module 'tls' { * APIs that create secure contexts have no default value. * * The `tls.createSecureContext()` method creates a `SecureContext` object. It is - * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. * * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. * * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. * @since v0.11.13 */ function createSecureContext(options?: SecureContextOptions): SecureContext; @@ -1016,6 +1100,13 @@ declare module 'tls' { * are provided, the lowest minimum is used. */ let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the ciphers option of tls.createSecureContext(). + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of crypto.constants.defaultCoreCipherList, unless + * changed using CLI options using --tls-default-ciphers. + */ + let DEFAULT_CIPHERS: string; /** * An immutable array of strings representing the root certificates (in PEM * format) used for verifying peer certificates. This is the default value diff --git a/node_modules/@types/node/ts4.8/trace_events.d.ts b/node_modules/@types/node/ts4.8/trace_events.d.ts index d47aa93..ca8baed 100644 --- a/node_modules/@types/node/ts4.8/trace_events.d.ts +++ b/node_modules/@types/node/ts4.8/trace_events.d.ts @@ -1,9 +1,9 @@ /** - * The `trace_events` module provides a mechanism to centralize tracing information - * generated by V8, Node.js core, and userspace code. + * The `node:trace_events` module provides a mechanism to centralize tracing + * information generated by V8, Node.js core, and userspace code. * * Tracing can be enabled with the `--trace-event-categories` command-line flag - * or by using the `trace_events` module. The `--trace-event-categories` flag + * or by using the `node:trace_events` module. The `--trace-event-categories` flag * accepts a list of comma-separated category names. * * The available categories are: @@ -13,9 +13,19 @@ * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool + * synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool + * asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. * * `node.environment`: Enables capture of Node.js Environment milestones. * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync + * directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async + * directory methods. * * `node.perf`: Enables capture of `Performance API` measurements. * * `node.perf.usertiming`: Enables capture of only Performance API User Timing * measures and marks. @@ -23,8 +33,9 @@ * measurements. * * `node.promises.rejections`: Enables capture of trace data tracking the number * of unhandled Promise rejections and handled-after-rejections. - * * `node.vm.script`: Enables capture of trace data for the `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. * * `v8`: The `V8` events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. * * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. * @@ -43,10 +54,10 @@ * node --trace-event-categories v8,node,node.async_hooks * ``` * - * Alternatively, trace events may be enabled using the `trace_events` module: + * Alternatively, trace events may be enabled using the `node:trace_events` module: * * ```js - * const trace_events = require('trace_events'); + * const trace_events = require('node:trace_events'); * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); * tracing.enable(); // Enable trace event capture for the 'node.perf' category * @@ -83,7 +94,7 @@ * * The features from this module are not available in `Worker` threads. * @experimental - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/trace_events.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/trace_events.js) */ declare module 'trace_events' { /** @@ -132,7 +143,7 @@ declare module 'trace_events' { * Creates and returns a `Tracing` object for the given set of `categories`. * * ```js - * const trace_events = require('trace_events'); + * const trace_events = require('node:trace_events'); * const categories = ['node.perf', 'node.async_hooks']; * const tracing = trace_events.createTracing({ categories }); * tracing.enable(); @@ -152,7 +163,7 @@ declare module 'trace_events' { * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. * * ```js - * const trace_events = require('trace_events'); + * const trace_events = require('node:trace_events'); * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); * const t3 = trace_events.createTracing({ categories: ['v8'] }); diff --git a/node_modules/@types/node/ts4.8/tty.d.ts b/node_modules/@types/node/ts4.8/tty.d.ts index 6473f8d..7653bf8 100644 --- a/node_modules/@types/node/ts4.8/tty.d.ts +++ b/node_modules/@types/node/ts4.8/tty.d.ts @@ -1,10 +1,9 @@ /** - * The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. - * In most cases, it will not be necessary or possible to use this module directly. - * However, it can be accessed using: + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: * * ```js - * const tty = require('tty'); + * const tty = require('node:tty'); * ``` * * When Node.js detects that it is being run with a text terminal ("TTY") @@ -22,7 +21,7 @@ * * In most cases, there should be little to no reason for an application to * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tty.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tty.js) */ declare module 'tty' { import * as net from 'node:net'; @@ -43,7 +42,10 @@ declare module 'tty' { constructor(fd: number, options?: net.SocketConstructorOpts); /** * A `boolean` that is `true` if the TTY is currently configured to operate as a - * raw device. Defaults to `false`. + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to`setRawMode`. * @since v0.7.7 */ isRaw: boolean; diff --git a/node_modules/@types/node/ts4.8/url.d.ts b/node_modules/@types/node/ts4.8/url.d.ts index e172acb..af8123d 100644 --- a/node_modules/@types/node/ts4.8/url.d.ts +++ b/node_modules/@types/node/ts4.8/url.d.ts @@ -1,11 +1,11 @@ /** - * The `url` module provides utilities for URL resolution and parsing. It can be - * accessed using: + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: * * ```js - * import url from 'url'; + * import url from 'node:url'; * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/url.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/url.js) */ declare module 'url' { import { Blob as NodeBlob } from 'node:buffer'; @@ -54,17 +54,11 @@ declare module 'url' { * * A `URIError` is thrown if the `auth` property is present but cannot be decoded. * - * Use of the legacy `url.parse()` method is discouraged. Users should - * use the WHATWG `URL` API. Because the `url.parse()` method uses a - * lenient, non-standard algorithm for parsing URL strings, security - * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and - * incorrect handling of usernames and passwords have been identified. - * - * Deprecation of this API has been shelved for now primarily due to the the - * inability of the [WHATWG API to parse relative URLs](https://github.com/nodejs/node/issues/12682#issuecomment-1154492373). - * [Discussions are ongoing](https://github.com/whatwg/url/issues/531) for the best way to resolve this. - * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. * @param urlString The URL string to parse. * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property * on the returned URL object will be an unparsed, undecoded string. @@ -79,15 +73,15 @@ declare module 'url' { * The `url.format()` method returns a formatted URL string derived from`urlObject`. * * ```js - * const url = require('url'); + * const url = require('node:url'); * url.format({ * protocol: 'https', * hostname: 'example.com', * pathname: '/some/path', * query: { * page: 1, - * format: 'json' - * } + * format: 'json', + * }, * }); * * // => 'https://example.com/some/path?page=1&format=json' @@ -135,7 +129,7 @@ declare module 'url' { * string, an `Error` is thrown. * * `result` is returned. * @since v0.1.25 - * @deprecated Legacy: Use the WHATWG URL API instead. + * @legacy Use the WHATWG URL API instead. * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. */ function format(urlObject: URL, options?: URLFormatOptions): string; @@ -199,7 +193,7 @@ declare module 'url' { * string, an `Error` is thrown. * * `result` is returned. * @since v0.1.25 - * @deprecated Legacy: Use the WHATWG URL API instead. + * @legacy Use the WHATWG URL API instead. * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. */ function format(urlObject: UrlObject | string): string; @@ -208,7 +202,7 @@ declare module 'url' { * manner similar to that of a web browser resolving an anchor tag. * * ```js - * const url = require('url'); + * const url = require('node:url'); * url.resolve('/one/two/three', 'four'); // '/one/two/four' * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' @@ -232,7 +226,7 @@ declare module 'url' { * resolve('http://example.com/one', '/two'); // 'http://example.com/two' * ``` * @since v0.1.25 - * @deprecated Legacy: Use the WHATWG URL API instead. + * @legacy Use the WHATWG URL API instead. * @param from The base URL to use if `to` is a relative URL. * @param to The target URL to resolve. */ @@ -243,10 +237,8 @@ declare module 'url' { * * It performs the inverse operation to {@link domainToUnicode}. * - * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. - * * ```js - * import url from 'url'; + * import url from 'node:url'; * * console.log(url.domainToASCII('español.com')); * // Prints xn--espaol-zwa.com @@ -264,10 +256,8 @@ declare module 'url' { * * It performs the inverse operation to {@link domainToASCII}. * - * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. - * * ```js - * import url from 'url'; + * import url from 'node:url'; * * console.log(url.domainToUnicode('xn--espaol-zwa.com')); * // Prints español.com @@ -284,7 +274,7 @@ declare module 'url' { * well as ensuring a cross-platform valid absolute path string. * * ```js - * import { fileURLToPath } from 'url'; + * import { fileURLToPath } from 'node:url'; * * const __filename = fileURLToPath(import.meta.url); * @@ -310,7 +300,7 @@ declare module 'url' { * control characters are correctly encoded when converting into a File URL. * * ```js - * import { pathToFileURL } from 'url'; + * import { pathToFileURL } from 'node:url'; * * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) @@ -328,7 +318,7 @@ declare module 'url' { * expected by the `http.request()` and `https.request()` APIs. * * ```js - * import { urlToHttpOptions } from 'url'; + * import { urlToHttpOptions } from 'node:url'; * const myURL = new URL('https://a:b@測試?abc#foo'); * * console.log(urlToHttpOptions(myURL)); @@ -376,7 +366,7 @@ declare module 'url' { * const { * Blob, * resolveObjectURL, - * } = require('buffer'); + * } = require('node:buffer'); * * const blob = new Blob(['hello']); * const id = URL.createObjectURL(blob); @@ -398,7 +388,7 @@ declare module 'url' { static createObjectURL(blob: NodeBlob): string; /** * Removes the stored `Blob` identified by the given ID. Attempting to revoke a - * ID that isn’t registered will silently fail. + * ID that isn't registered will silently fail. * @since v16.7.0 * @experimental * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. @@ -449,7 +439,7 @@ declare module 'url' { * // Prints example.org * * // Setting the hostname does not change the port - * myURL.hostname = 'example.com:82'; + * myURL.hostname = 'example.com'; * console.log(myURL.href); * // Prints https://example.com:81/foo * @@ -512,7 +502,7 @@ declare module 'url' { * * myURL.password = '123'; * console.log(myURL.href); - * // Prints https://abc:123@example.com + * // Prints https://abc:123@example.com/ * ``` * * Invalid URL characters included in the value assigned to the `password` property @@ -656,14 +646,14 @@ declare module 'url' { * character, while `URLSearchParams` will always encode it: * * ```js - * const myUrl = new URL('https://example.org/abc?foo=~bar'); + * const myURL = new URL('https://example.org/abc?foo=~bar'); * - * console.log(myUrl.search); // prints ?foo=~bar + * console.log(myURL.search); // prints ?foo=~bar * * // Modify the URL via searchParams... - * myUrl.searchParams.sort(); + * myURL.searchParams.sort(); * - * console.log(myUrl.search); // prints ?foo=%7Ebar + * console.log(myURL.search); // prints ?foo=%7Ebar * ``` */ readonly searchParams: URLSearchParams; @@ -758,9 +748,12 @@ declare module 'url' { */ append(name: string, value: string): void; /** - * Remove all name-value pairs whose name is `name`. + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`.. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. */ - delete(name: string): void; + delete(name: string, value?: string): void; /** * Returns an ES6 `Iterator` over each of the name-value pairs in the query. * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. @@ -796,9 +789,15 @@ declare module 'url' { */ getAll(name: string): string[]; /** - * Returns `true` if there is at least one name-value pair whose name is `name`. + * Checks if the `URLSearchParams` object contains key-value pair(s) based on`name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. */ - has(name: string): boolean; + has(name: string, value?: string): boolean; /** * Returns an ES6 `Iterator` over the names of each name-value pair. * @@ -833,6 +832,11 @@ declare module 'url' { * ``` */ set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; /** * Sort all existing name-value pairs in-place by their names. Sorting is done * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs diff --git a/node_modules/@types/node/ts4.8/util.d.ts b/node_modules/@types/node/ts4.8/util.d.ts index 6d35019..228a2c8 100644 --- a/node_modules/@types/node/ts4.8/util.d.ts +++ b/node_modules/@types/node/ts4.8/util.d.ts @@ -1,12 +1,12 @@ /** - * The `util` module supports the needs of Node.js internal APIs. Many of the + * The `node:util` module supports the needs of Node.js internal APIs. Many of the * utilities are useful for application and module developers as well. To access * it: * * ```js - * const util = require('util'); + * const util = require('node:util'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/util.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/util.js) */ declare module 'util' { import * as types from 'node:util/types'; @@ -189,7 +189,7 @@ declare module 'util' { * timestamp. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.log('Timestamped message.'); * ``` @@ -208,12 +208,12 @@ declare module 'util' { * Creates and returns an `AbortController` instance whose `AbortSignal` is marked * as transferable and can be used with `structuredClone()` or `postMessage()`. * @since v18.11.0 + * @experimental * @returns A transferable AbortController */ export function transferableAbortController(): AbortController; /** - * Marks the given {AbortSignal} as transferable so that it can be used with - * `structuredClone()` and `postMessage()`. + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. * * ```js * const signal = transferableAbortSignal(AbortSignal.timeout(100)); @@ -221,10 +221,35 @@ declare module 'util' { * channel.port2.postMessage(signal, [signal]); * ``` * @since v18.11.0 + * @experimental * @param signal The AbortSignal * @returns The same AbortSignal */ export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and + * returns a promise that is fulfilled when the `signal` is + * aborted. If the passed `resource` is garbage collected before the `signal` is + * aborted, the returned promise shall remain pending indefinitely. + * + * ```js + * import { aborted } from 'node:util'; + * + * const dependent = obtainSomethingAbortable(); + * + * aborted(dependent.signal, dependent).then(() => { + * // Do something when dependent is aborted. + * }); + * + * dependent.on('event', () => { + * dependent.abort(); + * }); + * ``` + * @since v19.7.0 + * @experimental + * @param resource Any non-null entity, reference to which is held weakly. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; /** * The `util.inspect()` method returns a string representation of `object` that is * intended for debugging. The output of `util.inspect` may change at any time @@ -251,7 +276,7 @@ declare module 'util' { * Circular references point to their anchor by using a reference index: * * ```js - * const { inspect } = require('util'); + * const { inspect } = require('node:util'); * * const obj = {}; * obj.a = [obj]; @@ -269,7 +294,7 @@ declare module 'util' { * The following example inspects all properties of the `util` object: * * ```js - * const util = require('util'); + * const util = require('node:util'); * * console.log(util.inspect(util, { showHidden: true, depth: null })); * ``` @@ -277,7 +302,7 @@ declare module 'util' { * The following example highlights the effect of the `compact` option: * * ```js - * const util = require('util'); + * const util = require('node:util'); * * const o = { * a: [1, 2, [[ @@ -285,7 +310,7 @@ declare module 'util' { * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', * 'test', * 'foo']], 4], - * b: new Map([['za', 1], ['zb', 'test']]) + * b: new Map([['za', 1], ['zb', 'test']]), * }; * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); * @@ -334,7 +359,7 @@ declare module 'util' { * with no remaining strong references may be garbage collected at any time. * * ```js - * const { inspect } = require('util'); + * const { inspect } = require('node:util'); * * const obj = { a: 1 }; * const obj2 = { b: 2 }; @@ -348,13 +373,13 @@ declare module 'util' { * impact the result of `util.inspect()`. * * ```js - * const { inspect } = require('util'); - * const assert = require('assert'); + * const { inspect } = require('node:util'); + * const assert = require('node:assert'); * * const o1 = { * b: [2, 3, 1], * a: '`a` comes before `b`', - * c: new Set([2, 3, 1]) + * c: new Set([2, 3, 1]), * }; * console.log(inspect(o1, { sorted: true })); * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } @@ -364,11 +389,11 @@ declare module 'util' { * const o2 = { * c: new Set([2, 1, 3]), * a: '`a` comes before `b`', - * b: [2, 3, 1] + * b: [2, 3, 1], * }; * assert.strict.equal( * inspect(o1, { sorted: true }), - * inspect(o2, { sorted: true }) + * inspect(o2, { sorted: true }), * ); * ``` * @@ -376,7 +401,7 @@ declare module 'util' { * numbers. * * ```js - * const { inspect } = require('util'); + * const { inspect } = require('node:util'); * * const thousand = 1_000; * const million = 1_000_000; @@ -388,7 +413,7 @@ declare module 'util' { * ``` * * `util.inspect()` is a synchronous method intended for debugging. Its maximum - * output length is approximately 128 MB. Inputs that result in longer output will + * output length is approximately 128 MiB. Inputs that result in longer output will * be truncated. * @since v0.3.0 * @param object Any JavaScript primitive or `Object`. @@ -417,7 +442,7 @@ declare module 'util' { * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isArray([]); * // Returns: true @@ -434,7 +459,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isRegExp(/some regexp/); * // Returns: true @@ -451,7 +476,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isDate(new Date()); * // Returns: true @@ -468,7 +493,7 @@ declare module 'util' { * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isError(new Error()); * // Returns: true @@ -482,7 +507,7 @@ declare module 'util' { * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * const obj = { name: 'Error', message: 'an error occurred' }; * * util.isError(obj); @@ -507,8 +532,8 @@ declare module 'util' { * through the `constructor.super_` property. * * ```js - * const util = require('util'); - * const EventEmitter = require('events'); + * const util = require('node:util'); + * const EventEmitter = require('node:events'); * * function MyStream() { * EventEmitter.call(this); @@ -534,7 +559,7 @@ declare module 'util' { * ES6 example using `class` and `extends`: * * ```js - * const EventEmitter = require('events'); + * const EventEmitter = require('node:events'); * * class MyStream extends EventEmitter { * write(data) { @@ -550,7 +575,7 @@ declare module 'util' { * stream.write('With ES6'); * ``` * @since v0.3.0 - * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + * @legacy Use ES2015 class syntax and `extends` keyword instead. */ export function inherits(constructor: unknown, superConstructor: unknown): void; export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; @@ -563,7 +588,7 @@ declare module 'util' { * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. * * ```js - * const util = require('util'); + * const util = require('node:util'); * const debuglog = util.debuglog('foo'); * * debuglog('hello from foo [%d]', 123); @@ -582,7 +607,7 @@ declare module 'util' { * The `section` supports wildcard also: * * ```js - * const util = require('util'); + * const util = require('node:util'); * const debuglog = util.debuglog('foo-bar'); * * debuglog('hi there, it\'s foo-bar [%d]', 2333); @@ -602,7 +627,7 @@ declare module 'util' { * unnecessary wrapping. * * ```js - * const util = require('util'); + * const util = require('node:util'); * let debuglog = util.debuglog('internals', (debug) => { * // Replace with a logging function that optimizes out * // testing if the section is enabled @@ -620,7 +645,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isBoolean(1); * // Returns: false @@ -637,7 +662,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isBuffer({ length: 0 }); * // Returns: false @@ -654,7 +679,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * function Foo() {} * const Bar = () => {}; @@ -674,7 +699,7 @@ declare module 'util' { * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isNull(0); * // Returns: false @@ -692,7 +717,7 @@ declare module 'util' { * returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isNullOrUndefined(0); * // Returns: false @@ -709,7 +734,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isNumber(false); * // Returns: false @@ -729,7 +754,7 @@ declare module 'util' { * Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isObject(5); * // Returns: false @@ -741,14 +766,14 @@ declare module 'util' { * // Returns: false * ``` * @since v0.11.5 - * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead. */ export function isObject(object: unknown): boolean; /** * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isPrimitive(5); * // Returns: true @@ -777,7 +802,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isString(''); * // Returns: true @@ -796,7 +821,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isSymbol(5); * // Returns: false @@ -813,7 +838,7 @@ declare module 'util' { * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * const foo = undefined; * util.isUndefined(5); @@ -832,7 +857,7 @@ declare module 'util' { * such a way that it is marked as deprecated. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * exports.obsoleteFunction = util.deprecate(() => { * // Do something here. @@ -848,7 +873,7 @@ declare module 'util' { * the warning will be emitted only once for that `code`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); @@ -902,7 +927,7 @@ declare module 'util' { * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * async function fn() { * return 'hello world'; @@ -985,8 +1010,8 @@ declare module 'util' { * that returns promises. * * ```js - * const util = require('util'); - * const fs = require('fs'); + * const util = require('node:util'); + * const fs = require('node:fs'); * * const stat = util.promisify(fs.stat); * stat('.').then((stats) => { @@ -999,8 +1024,8 @@ declare module 'util' { * Or, equivalently using `async function`s: * * ```js - * const util = require('util'); - * const fs = require('fs'); + * const util = require('node:util'); + * const fs = require('node:fs'); * * const stat = util.promisify(fs.stat); * @@ -1021,7 +1046,7 @@ declare module 'util' { * work as expected unless handled specially: * * ```js - * const util = require('util'); + * const util = require('node:util'); * * class Foo { * constructor() { @@ -1110,7 +1135,7 @@ declare module 'util' { * internally and emitted after the next call to `textDecoder.decode()`. * * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. - * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. */ decode( input?: NodeJS.ArrayBufferView | ArrayBuffer | null, @@ -1170,7 +1195,6 @@ declare module 'util' { */ encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; } - import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from 'util'; global { /** @@ -1178,19 +1202,18 @@ declare module 'util' { * https://nodejs.org/api/globals.html#textdecoder * @since v11.0.0 */ - var TextDecoder: typeof globalThis extends { + var TextDecoder: typeof globalThis extends { onmessage: any; TextDecoder: infer TextDecoder; } ? TextDecoder : typeof _TextDecoder; - /** * `TextEncoder` class is a global reference for `require('util').TextEncoder` * https://nodejs.org/api/globals.html#textencoder * @since v11.0.0 */ - var TextEncoder: typeof globalThis extends { + var TextEncoder: typeof globalThis extends { onmessage: any; TextEncoder: infer TextEncoder; } @@ -1200,48 +1223,34 @@ declare module 'util' { //// parseArgs /** - * Provides a high-level API for command-line argument parsing. Takes a - * specification for the expected arguments and returns a structured object - * with the parsed values and positionals. - * - * `config` provides arguments for parsing and configures the parser. It - * supports the following properties: - * - * - `args` The array of argument strings. **Default:** `process.argv` with - * `execPath` and `filename` removed. - * - `options` Arguments known to the parser. Keys of `options` are the long - * names of options and values are objects accepting the following properties: - * - * - `type` Type of argument, which must be either `boolean` (for options - * which do not take values) or `string` (for options which do). - * - `multiple` Whether this option can be provided multiple - * times. If `true`, all values will be collected in an array. If - * `false`, values for the option are last-wins. **Default:** `false`. - * - `short` A single character alias for the option. - * - `default` The default option value when it is not set by args. It - * must be of the same type as the `type` property. When `multiple` - * is `true`, it must be an array. - * - * - `strict`: Whether an error should be thrown when unknown arguments - * are encountered, or when arguments are passed that do not match the - * `type` configured in `options`. **Default:** `true`. - * - `allowPositionals`: Whether this command accepts positional arguments. - * **Default:** `false` if `strict` is `true`, otherwise `true`. - * - `tokens`: Whether tokens {boolean} Return the parsed tokens. This is useful - * for extending the built-in behavior, from adding additional checks through - * to reprocessing the tokens in different ways. - * **Default:** `false`. - * - * @returns The parsed command line arguments: - * - * - `values` A mapping of parsed option names with their string - * or boolean values. - * - `positionals` Positional arguments. - * - `tokens` Detailed parse information (only if `tokens` was specified). + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: */ export function parseArgs(config?: T): ParsedResults; - interface ParseArgsOptionConfig { /** * Type of argument. @@ -1266,11 +1275,9 @@ declare module 'util' { */ default?: string | boolean | string[] | boolean[] | undefined; } - interface ParseArgsOptionsConfig { [longOption: string]: ParseArgsOptionConfig; } - export interface ParseArgsConfig { /** * Array of argument strings. @@ -1297,7 +1304,6 @@ declare module 'util' { */ tokens?: boolean | undefined; } - /* IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 @@ -1421,11 +1427,103 @@ declare module 'util' { // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. type ParsedResults = ParseArgsConfig extends T ? { - values: { [longOption: string]: undefined | string | boolean | Array }; + values: { + [longOption: string]: undefined | string | boolean | Array; + }; positionals: string[]; tokens?: Token[]; } : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + * @experimental + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + */ + subtype: string; + /** + * Gets the essence of the MIME. + * + * Use `mime.type` or `mime.subtype` to alter the MIME. + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the parameters of the MIME. + */ + readonly params: MIMEParams; + /** + * Returns the serialized MIME. + * + * Because of the need for standard compliance, this method + * does not allow users to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * @since v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + entries(): IterableIterator<[string, string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. + * If there are no such pairs, `null` is returned. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + */ + keys(): IterableIterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. + * If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): IterableIterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator]: typeof MIMEParams.prototype.entries; + } } declare module 'util/types' { export * from 'util/types'; @@ -1723,12 +1821,40 @@ declare module 'util/types' { */ function isModuleNamespaceObject(value: unknown): boolean; /** - * Returns `true` if the value is an instance of a built-in `Error` type. + * Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). * * ```js - * util.types.isNativeError(new Error()); // Returns true - * util.types.isNativeError(new TypeError()); // Returns true - * util.types.isNativeError(new RangeError()); // Returns true + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()`returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false`for these errors: + * + * ```js + * const vm = require('node:vm'); + * const context = vm.createContext({}); + * const myError = vm.runInContext('new Error()', context); + * console.log(util.types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true * ``` * @since v10.0.0 */ diff --git a/node_modules/@types/node/ts4.8/v8.d.ts b/node_modules/@types/node/ts4.8/v8.d.ts index 6685dc2..064f5d5 100644 --- a/node_modules/@types/node/ts4.8/v8.d.ts +++ b/node_modules/@types/node/ts4.8/v8.d.ts @@ -1,10 +1,10 @@ /** - * The `v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: * * ```js - * const v8 = require('v8'); + * const v8 = require('node:v8'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/v8.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/v8.js) */ declare module 'v8' { import { Readable } from 'node:stream'; @@ -29,6 +29,9 @@ declare module 'v8' { does_zap_garbage: DoesZapCodeSpaceFlag; number_of_native_contexts: number; number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; } interface HeapCodeStatistics { code_and_metadata_size: number; @@ -68,6 +71,15 @@ declare module 'v8' { * of contexts that were detached and not yet garbage collected. This number * being non-zero indicates a potential memory leak. * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * * ```js * { * total_heap_size: 7326976, @@ -80,7 +92,10 @@ declare module 'v8' { * peak_malloced_memory: 1127496, * does_zap_garbage: 0, * number_of_native_contexts: 1, - * number_of_detached_contexts: 0 + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 * } * ``` * @since v1.0.0 @@ -149,7 +164,7 @@ declare module 'v8' { * * ```js * // Print GC events to stdout for one minute. - * const v8 = require('v8'); + * const v8 = require('node:v8'); * v8.setFlagsFromString('--trace_gc'); * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); * ``` @@ -172,12 +187,12 @@ declare module 'v8' { * * ```js * // Print heap snapshot to the console - * const v8 = require('v8'); + * const v8 = require('node:v8'); * const stream = v8.getHeapSnapshot(); * stream.pipe(process.stdout); * ``` * @since v11.13.0 - * @return A Readable Stream containing the V8 heap snapshot + * @return A Readable containing the V8 heap snapshot. */ function getHeapSnapshot(): Readable; /** @@ -197,12 +212,12 @@ declare module 'v8' { * for a duration depending on the heap size. * * ```js - * const { writeHeapSnapshot } = require('v8'); + * const { writeHeapSnapshot } = require('node:v8'); * const { * Worker, * isMainThread, - * parentPort - * } = require('worker_threads'); + * parentPort, + * } = require('node:worker_threads'); * * if (isMainThread) { * const worker = new Worker(__filename); @@ -233,13 +248,16 @@ declare module 'v8' { */ function writeHeapSnapshot(filename?: string): string; /** - * Returns an object with the following properties: + * Get statistics about code and its metadata in the heap, see + * V8[`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: * * ```js * { * code_and_metadata_size: 212208, * bytecode_and_metadata_size: 161368, - * external_script_source_size: 1410794 + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, * } * ``` * @since v12.8.0 @@ -289,7 +307,7 @@ declare module 'v8' { */ writeDouble(value: number): void; /** - * Write raw bytes into the serializer’s internal buffer. The deserializer + * Write raw bytes into the serializer's internal buffer. The deserializer * will require a way to compute the length of the buffer. * For use inside of a custom `serializer._writeHostObject()`. */ @@ -345,7 +363,7 @@ declare module 'v8' { */ readDouble(): number; /** - * Read raw bytes from the deserializer’s internal buffer. The `length` parameter + * Read raw bytes from the deserializer's internal buffer. The `length` parameter * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. * For use inside of a custom `deserializer._readHostObject()`. */ @@ -390,6 +408,227 @@ declare module 'v8' { * @since v15.1.0, v14.18.0, v12.22.0 */ function stopCoverage(): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object.The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * const { GCProfiler } = require('v8'); + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; } declare module 'node:v8' { export * from 'v8'; diff --git a/node_modules/@types/node/ts4.8/vm.d.ts b/node_modules/@types/node/ts4.8/vm.d.ts index c96513a..e293a50 100644 --- a/node_modules/@types/node/ts4.8/vm.d.ts +++ b/node_modules/@types/node/ts4.8/vm.d.ts @@ -1,8 +1,8 @@ /** - * The `vm` module enables compiling and running code within V8 Virtual + * The `node:vm` module enables compiling and running code within V8 Virtual * Machine contexts. * - * **The `vm` module is not a security** + * **The `node:vm` module is not a security** * **mechanism. Do not use it to run untrusted code.** * * JavaScript code can be compiled and run immediately or @@ -17,7 +17,7 @@ * code are reflected in the context object. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const x = 1; * @@ -34,7 +34,7 @@ * * console.log(x); // 1; y is not defined. * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/vm.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/vm.js) */ declare module 'vm' { interface Context extends NodeJS.Dict {} @@ -56,11 +56,17 @@ declare module 'vm' { columnOffset?: number | undefined; } interface ScriptOptions extends BaseOptions { - displayErrors?: boolean | undefined; - timeout?: number | undefined; - cachedData?: Buffer | undefined; + /** + * V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; /** @deprecated in favor of `script.createCachedData()` */ produceCachedData?: boolean | undefined; + /** + * Called during evaluation of this module when `import()` is called. + * If this option is not specified, calls to `import()` will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`. + */ + importModuleDynamically?: ((specifier: string, script: Script, importAssertions: Object) => Module) | undefined; } interface RunningScriptOptions extends BaseOptions { /** @@ -80,10 +86,31 @@ declare module 'vm' { * Default: `false`. */ breakOnSigint?: boolean | undefined; + } + interface RunningScriptInNewContextOptions extends RunningScriptOptions { + /** + * Human-readable name of the newly created context. + */ + contextName?: CreateContextOptions['name']; + /** + * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, + * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + */ + contextOrigin?: CreateContextOptions['origin']; + contextCodeGeneration?: CreateContextOptions['codeGeneration']; /** * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. */ - microtaskMode?: 'afterEvaluate' | undefined; + microtaskMode?: CreateContextOptions['microtaskMode']; + } + interface RunningCodeOptions extends RunningScriptOptions { + cachedData?: ScriptOptions['cachedData']; + importModuleDynamically?: ScriptOptions['importModuleDynamically']; + } + interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { + cachedData?: ScriptOptions['cachedData']; + importModuleDynamically?: ScriptOptions['importModuleDynamically']; } interface CompileFunctionOptions extends BaseOptions { /** @@ -144,7 +171,10 @@ declare module 'vm' { * @default 'summary' */ mode?: MeasureMemoryMode | undefined; - context?: Context | undefined; + /** + * @default 'default' + */ + execution?: 'default' | 'eager' | undefined; } interface MemoryMeasurement { total: { @@ -158,7 +188,7 @@ declare module 'vm' { * @since v0.3.1 */ class Script { - constructor(code: string, options?: ScriptOptions); + constructor(code: string, options?: ScriptOptions | string); /** * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access * to local scope. @@ -168,11 +198,11 @@ declare module 'vm' { * The globals are contained in the `context` object. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const context = { * animal: 'cat', - * count: 2 + * count: 2, * }; * * const script = new vm.Script('count += 1; name = "kitty";'); @@ -204,7 +234,7 @@ declare module 'vm' { * contained within each individual `context`. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const script = new vm.Script('globalVar = "set"'); * @@ -220,7 +250,7 @@ declare module 'vm' { * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. * @return the result of the very last statement executed in the script. */ - runInNewContext(contextObject?: Context, options?: RunningScriptOptions): any; + runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any; /** * Runs the compiled code contained by the `vm.Script` within the context of the * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. @@ -229,7 +259,7 @@ declare module 'vm' { * executes that code multiple times: * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * global.globalVar = 0; * @@ -251,6 +281,16 @@ declare module 'vm' { * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any * time and any number of times. * + * The code cache of the `Script` doesn't contain any JavaScript observable + * states. The code cache is safe to be saved along side the script source and + * used to construct new `Script` instances multiple times. + * + * Functions in the `Script` source can be marked as lazily compiled and they are + * not compiled at construction of the `Script`. These functions are going to be + * compiled when they are invoked the first time. The code cache serializes the + * metadata that V8 currently knows about the `Script` that it can use to speed up + * future compilations. + * * ```js * const script = new vm.Script(` * function add(a, b) { @@ -260,19 +300,46 @@ declare module 'vm' { * const x = add(1, 2); * `); * - * const cacheWithoutX = script.createCachedData(); + * const cacheWithoutAdd = script.createCachedData(); + * // In `cacheWithoutAdd` the function `add()` is marked for full compilation + * // upon invocation. * * script.runInThisContext(); * - * const cacheWithX = script.createCachedData(); + * const cacheWithAdd = script.createCachedData(); + * // `cacheWithAdd` contains fully compiled function `add()`. * ``` * @since v10.6.0 */ createCachedData(): Buffer; /** @deprecated in favor of `script.createCachedData()` */ cachedDataProduced?: boolean | undefined; + /** + * When `cachedData` is supplied to create the `vm.Script`, this value will be set + * to either `true` or `false` depending on acceptance of the data by V8\. + * Otherwise the value is `undefined`. + * @since v5.7.0 + */ cachedDataRejected?: boolean | undefined; cachedData?: Buffer | undefined; + /** + * When the script is compiled from a source that contains a source map magic + * comment, this property will be set to the URL of the source map. + * + * ```js + * import vm from 'node:vm'; + * + * const script = new vm.Script(` + * function myFunc() {} + * //# sourceMappingURL=sourcemap.json + * `); + * + * console.log(script.sourceMapURL); + * // Prints: sourcemap.json + * ``` + * @since v19.1.0, v18.13.0 + */ + sourceMapURL?: string | undefined; } /** * If given a `contextObject`, the `vm.createContext()` method will `prepare @@ -282,7 +349,7 @@ declare module 'vm' { * will remain unchanged. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * global.globalVar = 3; * @@ -329,7 +396,7 @@ declare module 'vm' { * The following example compiles and executes different scripts using a single `contextified` object: * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const contextObject = { globalVar: 1 }; * vm.createContext(contextObject); @@ -345,7 +412,7 @@ declare module 'vm' { * @param contextifiedObject The `contextified` object that will be used as the `global` when the `code` is compiled and run. * @return the result of the very last statement executed in the script. */ - function runInContext(code: string, contextifiedObject: Context, options?: RunningScriptOptions | string): any; + function runInContext(code: string, contextifiedObject: Context, options?: RunningCodeOptions | string): any; /** * The `vm.runInNewContext()` first contextifies the given `contextObject` (or * creates a new `contextObject` if passed as `undefined`), compiles the `code`, @@ -358,11 +425,11 @@ declare module 'vm' { * variable and sets a new one. These globals are contained in the `contextObject`. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const contextObject = { * animal: 'cat', - * count: 2 + * count: 2, * }; * * vm.runInNewContext('count += 1; name = "kitty"', contextObject); @@ -374,7 +441,7 @@ declare module 'vm' { * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. * @return the result of the very last statement executed in the script. */ - function runInNewContext(code: string, contextObject?: Context, options?: RunningScriptOptions | string): any; + function runInNewContext(code: string, contextObject?: Context, options?: RunningCodeInNewContextOptions | string): any; /** * `vm.runInThisContext()` compiles `code`, runs it within the context of the * current `global` and returns the result. Running code does not have access to @@ -386,7 +453,7 @@ declare module 'vm' { * the JavaScript [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function to run the same code: * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * let localVar = 'initial value'; * * const vmResult = vm.runInThisContext('localVar = "vm";'); @@ -407,17 +474,17 @@ declare module 'vm' { * When using either `script.runInThisContext()` or {@link runInThisContext}, the code is executed within the current V8 global * context. The code passed to this VM context will have its own isolated scope. * - * In order to run a simple web server using the `http` module the code passed to - * the context must either call `require('http')` on its own, or have a reference - * to the `http` module passed to it. For instance: + * In order to run a simple web server using the `node:http` module the code passed + * to the context must either call `require('node:http')` on its own, or have a + * reference to the `node:http` module passed to it. For instance: * * ```js * 'use strict'; - * const vm = require('vm'); + * const vm = require('node:vm'); * * const code = ` * ((require) => { - * const http = require('http'); + * const http = require('node:http'); * * http.createServer((request, response) => { * response.writeHead(200, { 'Content-Type': 'text/plain' }); @@ -437,7 +504,7 @@ declare module 'vm' { * @param code The JavaScript code to compile and run. * @return the result of the very last statement executed in the script. */ - function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + function runInThisContext(code: string, options?: RunningCodeOptions | string): any; /** * Compiles the given code into the provided context (if no context is * supplied, the current context is used), and returns it wrapped inside a @@ -446,7 +513,15 @@ declare module 'vm' { * @param code The body of the function to compile. * @param params An array of strings containing all parameters for the function. */ - function compileFunction(code: string, params?: ReadonlyArray, options?: CompileFunctionOptions): Function; + function compileFunction( + code: string, + params?: ReadonlyArray, + options?: CompileFunctionOptions + ): Function & { + cachedData?: Script['cachedData'] | undefined; + cachedDataProduced?: Script['cachedDataProduced'] | undefined; + cachedDataRejected?: Script['cachedDataRejected'] | undefined; + }; /** * Measure the memory known to V8 and used by all contexts known to the * current V8 isolate, or the main context. @@ -460,7 +535,7 @@ declare module 'vm' { * the memory occupied by each heap space in the current V8 instance. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * // Measure the memory used by the main context. * vm.measureMemory({ mode: 'summary' }) * // This is the same as vm.measureMemory() @@ -503,6 +578,316 @@ declare module 'vm' { * @experimental */ function measureMemory(options?: MeasureMemoryOptions): Promise; + interface ModuleEvaluateOptions { + timeout?: RunningScriptOptions['timeout'] | undefined; + breakOnSigint?: RunningScriptOptions['breakOnSigint'] | undefined; + } + type ModuleLinker = ( + specifier: string, + referencingModule: Module, + extra: { + assert: Object; + } + ) => Module | Promise; + type ModuleStatus = 'unlinked' | 'linking' | 'linked' | 'evaluating' | 'evaluated' | 'errored'; + /** + * This feature is only available with the `--experimental-vm-modules` command + * flag enabled. + * + * The `vm.Module` class provides a low-level interface for using + * ECMAScript modules in VM contexts. It is the counterpart of the `vm.Script`class that closely mirrors [Module Record](https://www.ecma-international.org/ecma-262/#sec-abstract-module-records) + * s as defined in the ECMAScript + * specification. + * + * Unlike `vm.Script` however, every `vm.Module` object is bound to a context from + * its creation. Operations on `vm.Module` objects are intrinsically asynchronous, + * in contrast with the synchronous nature of `vm.Script` objects. The use of + * 'async' functions can help with manipulating `vm.Module` objects. + * + * Using a `vm.Module` object requires three distinct steps: creation/parsing, + * linking, and evaluation. These three steps are illustrated in the following + * example. + * + * This implementation lies at a lower level than the `ECMAScript Module + * loader`. There is also no way to interact with the Loader yet, though + * support is planned. + * + * ```js + * import vm from 'node:vm'; + * + * const contextifiedObject = vm.createContext({ + * secret: 42, + * print: console.log, + * }); + * + * // Step 1 + * // + * // Create a Module by constructing a new `vm.SourceTextModule` object. This + * // parses the provided source text, throwing a `SyntaxError` if anything goes + * // wrong. By default, a Module is created in the top context. But here, we + * // specify `contextifiedObject` as the context this Module belongs to. + * // + * // Here, we attempt to obtain the default export from the module "foo", and + * // put it into local binding "secret". + * + * const bar = new vm.SourceTextModule(` + * import s from 'foo'; + * s; + * print(s); + * `, { context: contextifiedObject }); + * + * // Step 2 + * // + * // "Link" the imported dependencies of this Module to it. + * // + * // The provided linking callback (the "linker") accepts two arguments: the + * // parent module (`bar` in this case) and the string that is the specifier of + * // the imported module. The callback is expected to return a Module that + * // corresponds to the provided specifier, with certain requirements documented + * // in `module.link()`. + * // + * // If linking has not started for the returned Module, the same linker + * // callback will be called on the returned Module. + * // + * // Even top-level Modules without dependencies must be explicitly linked. The + * // callback provided would never be called, however. + * // + * // The link() method returns a Promise that will be resolved when all the + * // Promises returned by the linker resolve. + * // + * // Note: This is a contrived example in that the linker function creates a new + * // "foo" module every time it is called. In a full-fledged module system, a + * // cache would probably be used to avoid duplicated modules. + * + * async function linker(specifier, referencingModule) { + * if (specifier === 'foo') { + * return new vm.SourceTextModule(` + * // The "secret" variable refers to the global variable we added to + * // "contextifiedObject" when creating the context. + * export default secret; + * `, { context: referencingModule.context }); + * + * // Using `contextifiedObject` instead of `referencingModule.context` + * // here would work as well. + * } + * throw new Error(`Unable to resolve dependency: ${specifier}`); + * } + * await bar.link(linker); + * + * // Step 3 + * // + * // Evaluate the Module. The evaluate() method returns a promise which will + * // resolve after the module has finished evaluating. + * + * // Prints 42. + * await bar.evaluate(); + * ``` + * @since v13.0.0, v12.16.0 + * @experimental + */ + class Module { + /** + * The specifiers of all dependencies of this module. The returned array is frozen + * to disallow any changes to it. + * + * Corresponds to the `[[RequestedModules]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in + * the ECMAScript specification. + */ + dependencySpecifiers: readonly string[]; + /** + * If the `module.status` is `'errored'`, this property contains the exception + * thrown by the module during evaluation. If the status is anything else, + * accessing this property will result in a thrown exception. + * + * The value `undefined` cannot be used for cases where there is not a thrown + * exception due to possible ambiguity with `throw undefined;`. + * + * Corresponds to the `[[EvaluationError]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s + * in the ECMAScript specification. + */ + error: any; + /** + * The identifier of the current module, as set in the constructor. + */ + identifier: string; + context: Context; + /** + * The namespace object of the module. This is only available after linking + * (`module.link()`) has completed. + * + * Corresponds to the [GetModuleNamespace](https://tc39.es/ecma262/#sec-getmodulenamespace) abstract operation in the ECMAScript + * specification. + */ + namespace: Object; + /** + * The current status of the module. Will be one of: + * + * * `'unlinked'`: `module.link()` has not yet been called. + * * `'linking'`: `module.link()` has been called, but not all Promises returned + * by the linker function have been resolved yet. + * * `'linked'`: The module has been linked successfully, and all of its + * dependencies are linked, but `module.evaluate()` has not yet been called. + * * `'evaluating'`: The module is being evaluated through a `module.evaluate()` on + * itself or a parent module. + * * `'evaluated'`: The module has been successfully evaluated. + * * `'errored'`: The module has been evaluated, but an exception was thrown. + * + * Other than `'errored'`, this status string corresponds to the specification's [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)'s `[[Status]]` field. `'errored'` + * corresponds to`'evaluated'` in the specification, but with `[[EvaluationError]]` set to a + * value that is not `undefined`. + */ + status: ModuleStatus; + /** + * Evaluate the module. + * + * This must be called after the module has been linked; otherwise it will reject. + * It could be called also when the module has already been evaluated, in which + * case it will either do nothing if the initial evaluation ended in success + * (`module.status` is `'evaluated'`) or it will re-throw the exception that the + * initial evaluation resulted in (`module.status` is `'errored'`). + * + * This method cannot be called while the module is being evaluated + * (`module.status` is `'evaluating'`). + * + * Corresponds to the [Evaluate() concrete method](https://tc39.es/ecma262/#sec-moduleevaluation) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in the + * ECMAScript specification. + * @return Fulfills with `undefined` upon success. + */ + evaluate(options?: ModuleEvaluateOptions): Promise; + /** + * Link module dependencies. This method must be called before evaluation, and + * can only be called once per module. + * + * The function is expected to return a `Module` object or a `Promise` that + * eventually resolves to a `Module` object. The returned `Module` must satisfy the + * following two invariants: + * + * * It must belong to the same context as the parent `Module`. + * * Its `status` must not be `'errored'`. + * + * If the returned `Module`'s `status` is `'unlinked'`, this method will be + * recursively called on the returned `Module` with the same provided `linker`function. + * + * `link()` returns a `Promise` that will either get resolved when all linking + * instances resolve to a valid `Module`, or rejected if the linker function either + * throws an exception or returns an invalid `Module`. + * + * The linker function roughly corresponds to the implementation-defined [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) abstract operation in the + * ECMAScript + * specification, with a few key differences: + * + * * The linker function is allowed to be asynchronous while [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) is synchronous. + * + * The actual [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation used during module + * linking is one that returns the modules linked during linking. Since at + * that point all modules would have been fully linked already, the [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation is fully synchronous per + * specification. + * + * Corresponds to the [Link() concrete method](https://tc39.es/ecma262/#sec-moduledeclarationlinking) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in + * the ECMAScript specification. + */ + link(linker: ModuleLinker): Promise; + } + interface SourceTextModuleOptions { + /** + * String used in stack traces. + * @default 'vm:module(i)' where i is a context-specific ascending index. + */ + identifier?: string | undefined; + cachedData?: ScriptOptions['cachedData'] | undefined; + context?: Context | undefined; + lineOffset?: BaseOptions['lineOffset'] | undefined; + columnOffset?: BaseOptions['columnOffset'] | undefined; + /** + * Called during evaluation of this module to initialize the `import.meta`. + */ + initializeImportMeta?: ((meta: ImportMeta, module: SourceTextModule) => void) | undefined; + importModuleDynamically?: ScriptOptions['importModuleDynamically'] | undefined; + } + /** + * This feature is only available with the `--experimental-vm-modules` command + * flag enabled. + * + * + * + * The `vm.SourceTextModule` class provides the [Source Text Module Record](https://tc39.es/ecma262/#sec-source-text-module-records) as + * defined in the ECMAScript specification. + * @since v9.6.0 + * @experimental + */ + class SourceTextModule extends Module { + /** + * Creates a new `SourceTextModule` instance. + * @param code JavaScript Module code to parse + */ + constructor(code: string, options?: SourceTextModuleOptions); + } + interface SyntheticModuleOptions { + /** + * String used in stack traces. + * @default 'vm:module(i)' where i is a context-specific ascending index. + */ + identifier?: string | undefined; + /** + * The contextified object as returned by the `vm.createContext()` method, to compile and evaluate this module in. + */ + context?: Context | undefined; + } + /** + * This feature is only available with the `--experimental-vm-modules` command + * flag enabled. + * + * + * + * The `vm.SyntheticModule` class provides the [Synthetic Module Record](https://heycam.github.io/webidl/#synthetic-module-records) as + * defined in the WebIDL specification. The purpose of synthetic modules is to + * provide a generic interface for exposing non-JavaScript sources to ECMAScript + * module graphs. + * + * ```js + * const vm = require('node:vm'); + * + * const source = '{ "a": 1 }'; + * const module = new vm.SyntheticModule(['default'], function() { + * const obj = JSON.parse(source); + * this.setExport('default', obj); + * }); + * + * // Use `module` in linking... + * ``` + * @since v13.0.0, v12.16.0 + * @experimental + */ + class SyntheticModule extends Module { + /** + * Creates a new `SyntheticModule` instance. + * @param exportNames Array of names that will be exported from the module. + * @param evaluateCallback Called when the module is evaluated. + */ + constructor(exportNames: string[], evaluateCallback: (this: SyntheticModule) => void, options?: SyntheticModuleOptions); + /** + * This method is used after the module is linked to set the values of exports. If + * it is called before the module is linked, an `ERR_VM_MODULE_STATUS` error + * will be thrown. + * + * ```js + * import vm from 'node:vm'; + * + * const m = new vm.SyntheticModule(['x'], () => { + * m.setExport('x', 1); + * }); + * + * await m.link(() => {}); + * await m.evaluate(); + * + * assert.strictEqual(m.namespace.x, 1); + * ``` + * @since v13.0.0, v12.16.0 + * @param name Name of the export to set. + * @param value The value to set the export to. + */ + setExport(name: string, value: any): void; + } } declare module 'node:vm' { export * from 'vm'; diff --git a/node_modules/@types/node/ts4.8/wasi.d.ts b/node_modules/@types/node/ts4.8/wasi.d.ts index d20b66b..b430b3a 100644 --- a/node_modules/@types/node/ts4.8/wasi.d.ts +++ b/node_modules/@types/node/ts4.8/wasi.d.ts @@ -3,26 +3,23 @@ * underlying operating system via a collection of POSIX-like functions. * * ```js - * import { readFile } from 'fs/promises'; + * import { readFile } from 'node:fs/promises'; * import { WASI } from 'wasi'; - * import { argv, env } from 'process'; + * import { argv, env } from 'node:process'; * * const wasi = new WASI({ + * version: 'preview1', * args: argv, * env, * preopens: { - * '/sandbox': '/some/real/path/that/wasm/can/access' - * } + * '/sandbox': '/some/real/path/that/wasm/can/access', + * }, * }); * - * // Some WASI binaries require: - * // const importObject = { wasi_unstable: wasi.wasiImport }; - * const importObject = { wasi_snapshot_preview1: wasi.wasiImport }; - * * const wasm = await WebAssembly.compile( - * await readFile(new URL('./demo.wasm', import.meta.url)) + * await readFile(new URL('./demo.wasm', import.meta.url)), * ); - * const instance = await WebAssembly.instantiate(wasm, importObject); + * const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject()); * * wasi.start(instance); * ``` @@ -61,14 +58,11 @@ * * Use [wabt](https://github.com/WebAssembly/wabt) to compile `.wat` to `.wasm` * - * ```console - * $ wat2wasm demo.wat + * ```bash + * wat2wasm demo.wat * ``` - * - * The `--experimental-wasi-unstable-preview1` CLI argument is needed for this - * example to run. * @experimental - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/wasi.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/wasi.js) */ declare module 'wasi' { interface WASIOptions { @@ -91,11 +85,11 @@ declare module 'wasi' { */ preopens?: NodeJS.Dict | undefined; /** - * By default, WASI applications terminate the Node.js - * process via the `__wasi_proc_exit()` function. Setting this option to `true` - * causes `wasi.start()` to return the exit code rather than terminate the - * process. - * @default false + * By default, when WASI applications call `__wasi_proc_exit()` + * `wasi.start()` will return with the exit code specified rather than terminatng the process. + * Setting this option to `false` will cause the Node.js process to exit with + * the specified exit code instead. + * @default true */ returnOnExit?: boolean | undefined; /** diff --git a/node_modules/@types/node/ts4.8/worker_threads.d.ts b/node_modules/@types/node/ts4.8/worker_threads.d.ts index 52f4384..e11932e 100644 --- a/node_modules/@types/node/ts4.8/worker_threads.d.ts +++ b/node_modules/@types/node/ts4.8/worker_threads.d.ts @@ -1,9 +1,9 @@ /** - * The `worker_threads` module enables the use of threads that execute JavaScript - * in parallel. To access it: + * The `node:worker_threads` module enables the use of threads that execute + * JavaScript in parallel. To access it: * * ```js - * const worker = require('worker_threads'); + * const worker = require('node:worker_threads'); * ``` * * Workers (threads) are useful for performing CPU-intensive JavaScript operations. @@ -15,14 +15,14 @@ * * ```js * const { - * Worker, isMainThread, parentPort, workerData - * } = require('worker_threads'); + * Worker, isMainThread, parentPort, workerData, + * } = require('node:worker_threads'); * * if (isMainThread) { * module.exports = function parseJSAsync(script) { * return new Promise((resolve, reject) => { * const worker = new Worker(__filename, { - * workerData: script + * workerData: script, * }); * worker.on('message', resolve); * worker.on('error', reject); @@ -49,7 +49,7 @@ * * Worker threads inherit non-process-specific options by default. Refer to `Worker constructor options` to know how to customize worker thread options, * specifically `argv` and `execArgv` options. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/worker_threads.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/worker_threads.js) */ declare module 'worker_threads' { import { Blob } from 'node:buffer'; @@ -72,7 +72,7 @@ declare module 'worker_threads' { * The `MessageChannel` has no methods of its own. `new MessageChannel()`yields an object with `port1` and `port2` properties, which refer to linked `MessagePort` instances. * * ```js - * const { MessageChannel } = require('worker_threads'); + * const { MessageChannel } = require('node:worker_threads'); * * const { port1, port2 } = new MessageChannel(); * port1.on('message', (message) => console.log('received', message)); @@ -121,7 +121,7 @@ declare module 'worker_threads' { * * `value` may not contain native (C++-backed) objects other than: * * ```js - * const { MessageChannel } = require('worker_threads'); + * const { MessageChannel } = require('node:worker_threads'); * const { port1, port2 } = new MessageChannel(); * * port1.on('message', (message) => console.log(message)); @@ -132,7 +132,7 @@ declare module 'worker_threads' { * port2.postMessage(circularData); * ``` * - * `transferList` may be a list of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), `MessagePort` and `FileHandle` objects. + * `transferList` may be a list of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), `MessagePort`, and `FileHandle` objects. * After transferring, they are not usable on the sending side of the channel * anymore (even if they are not contained in `value`). Unlike with `child processes`, transferring handles such as network sockets is currently * not supported. @@ -143,7 +143,7 @@ declare module 'worker_threads' { * `value` may still contain `ArrayBuffer` instances that are not in`transferList`; in that case, the underlying memory is copied rather than moved. * * ```js - * const { MessageChannel } = require('worker_threads'); + * const { MessageChannel } = require('node:worker_threads'); * const { port1, port2 } = new MessageChannel(); * * port1.on('message', (message) => console.log(message)); @@ -170,7 +170,7 @@ declare module 'worker_threads' { * posting without having side effects. * * For more information on the serialization and deserialization mechanisms - * behind this API, see the `serialization API of the v8 module`. + * behind this API, see the `serialization API of the node:v8 module`. * @since v10.5.0 */ postMessage(value: any, transferList?: ReadonlyArray): void; @@ -262,6 +262,12 @@ declare module 'worker_threads' { * @default true */ trackUnmanagedFds?: boolean | undefined; + /** + * An optional `name` to be appended to the worker title + * for debuggin/identification purposes, making the final title as + * `[worker ${id}] ${name}`. + */ + name?: string | undefined; } interface ResourceLimits { /** @@ -288,9 +294,9 @@ declare module 'worker_threads' { * * Notable differences inside a Worker environment are: * - * * The `process.stdin`, `process.stdout` and `process.stderr` may be redirected by the parent thread. - * * The `require('worker_threads').isMainThread` property is set to `false`. - * * The `require('worker_threads').parentPort` message port is available. + * * The `process.stdin`, `process.stdout`, and `process.stderr` streams may be redirected by the parent thread. + * * The `require('node:worker_threads').isMainThread` property is set to `false`. + * * The `require('node:worker_threads').parentPort` message port is available. * * `process.exit()` does not stop the whole program, just the single thread, * and `process.abort()` is not available. * * `process.chdir()` and `process` methods that set group or user ids @@ -307,11 +313,11 @@ declare module 'worker_threads' { * * Creating `Worker` instances inside of other `Worker`s is possible. * - * Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `cluster module`, two-way communication can be - * achieved through inter-thread message passing. Internally, a `Worker` has a - * built-in pair of `MessagePort` s that are already associated with each other - * when the `Worker` is created. While the `MessagePort` object on the parent side - * is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event + * Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `node:cluster module`, two-way communication + * can be achieved through inter-thread message passing. Internally, a `Worker` has + * a built-in pair of `MessagePort` s that are already associated with each + * other when the `Worker` is created. While the `MessagePort` object on the parent + * side is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event * on the `Worker` object for the parent thread. * * To create custom messaging channels (which is encouraged over using the default @@ -324,10 +330,10 @@ declare module 'worker_threads' { * the thread barrier. * * ```js - * const assert = require('assert'); + * const assert = require('node:assert'); * const { - * Worker, MessageChannel, MessagePort, isMainThread, parentPort - * } = require('worker_threads'); + * Worker, MessageChannel, MessagePort, isMainThread, parentPort, + * } = require('node:worker_threads'); * if (isMainThread) { * const worker = new Worker(__filename); * const subChannel = new MessageChannel(); @@ -367,7 +373,7 @@ declare module 'worker_threads' { readonly stderr: Readable; /** * An integer identifier for the referenced thread. Inside the worker thread, - * it is available as `require('worker_threads').threadId`. + * it is available as `require('node:worker_threads').threadId`. * This value is unique for each `Worker` instance inside a single process. * @since v10.5.0 */ @@ -394,7 +400,7 @@ declare module 'worker_threads' { */ constructor(filename: string | URL, options?: WorkerOptions); /** - * Send a message to the worker that is received via `require('worker_threads').parentPort.on('message')`. + * Send a message to the worker that is received via `require('node:worker_threads').parentPort.on('message')`. * See `port.postMessage()` for more details. * @since v10.5.0 */ @@ -488,8 +494,8 @@ declare module 'worker_threads' { * const { * isMainThread, * BroadcastChannel, - * Worker - * } = require('worker_threads'); + * Worker, + * } = require('node:worker_threads'); * * const bc = new BroadcastChannel('hello'); * @@ -543,7 +549,7 @@ declare module 'worker_threads' { * This operation cannot be undone. * * ```js - * const { MessageChannel, markAsUntransferable } = require('worker_threads'); + * const { MessageChannel, markAsUntransferable } = require('node:worker_threads'); * * const pooledBuffer = new ArrayBuffer(8); * const typedArray1 = new Uint8Array(pooledBuffer); @@ -585,10 +591,10 @@ declare module 'worker_threads' { function moveMessagePortToContext(port: MessagePort, contextifiedSandbox: Context): MessagePort; /** * Receive a single message from a given `MessagePort`. If no message is available,`undefined` is returned, otherwise an object with a single `message` property - * that contains the message payload, corresponding to the oldest message in the`MessagePort`’s queue. + * that contains the message payload, corresponding to the oldest message in the`MessagePort`'s queue. * * ```js - * const { MessageChannel, receiveMessageOnPort } = require('worker_threads'); + * const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads'); * const { port1, port2 } = new MessageChannel(); * port1.postMessage({ hello: 'world' }); * @@ -619,7 +625,7 @@ declare module 'worker_threads' { * isMainThread, * setEnvironmentData, * getEnvironmentData, - * } = require('worker_threads'); + * } = require('node:worker_threads'); * * if (isMainThread) { * setEnvironmentData('Hello', 'World!'); @@ -658,7 +664,6 @@ declare module 'worker_threads' { } ? T : typeof _BroadcastChannel; - /** * `MessageChannel` class is a global reference for `require('worker_threads').MessageChannel` * https://nodejs.org/api/globals.html#messagechannel @@ -670,13 +675,12 @@ declare module 'worker_threads' { } ? T : typeof _MessageChannel; - /** * `MessagePort` class is a global reference for `require('worker_threads').MessagePort` * https://nodejs.org/api/globals.html#messageport * @since v15.0.0 */ - var MessagePort: typeof globalThis extends { + var MessagePort: typeof globalThis extends { onmessage: any; MessagePort: infer T; } diff --git a/node_modules/@types/node/ts4.8/zlib.d.ts b/node_modules/@types/node/ts4.8/zlib.d.ts index 1d7f0c0..9d74cd2 100644 --- a/node_modules/@types/node/ts4.8/zlib.d.ts +++ b/node_modules/@types/node/ts4.8/zlib.d.ts @@ -1,11 +1,11 @@ /** - * The `zlib` module provides compression functionality implemented using Gzip, - * Deflate/Inflate, and Brotli. + * The `node:zlib` module provides compression functionality implemented using + * Gzip, Deflate/Inflate, and Brotli. * * To access it: * * ```js - * const zlib = require('zlib'); + * const zlib = require('node:zlib'); * ``` * * Compression and decompression are built around the Node.js `Streams API`. @@ -15,12 +15,12 @@ * stream: * * ```js - * const { createGzip } = require('zlib'); - * const { pipeline } = require('stream'); + * const { createGzip } = require('node:zlib'); + * const { pipeline } = require('node:stream'); * const { * createReadStream, - * createWriteStream - * } = require('fs'); + * createWriteStream, + * } = require('node:fs'); * * const gzip = createGzip(); * const source = createReadStream('input.txt'); @@ -35,7 +35,7 @@ * * // Or, Promisified * - * const { promisify } = require('util'); + * const { promisify } = require('node:util'); * const pipe = promisify(pipeline); * * async function do_gzip(input, output) { @@ -55,7 +55,7 @@ * It is also possible to compress or decompress data in a single step: * * ```js - * const { deflate, unzip } = require('zlib'); + * const { deflate, unzip } = require('node:zlib'); * * const input = '.................................'; * deflate(input, (err, buffer) => { @@ -77,7 +77,7 @@ * * // Or, Promisified * - * const { promisify } = require('util'); + * const { promisify } = require('node:util'); * const do_unzip = promisify(unzip); * * do_unzip(buffer) @@ -88,7 +88,7 @@ * }); * ``` * @since v0.5.8 - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/zlib.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/zlib.js) */ declare module 'zlib' { import * as stream from 'node:stream'; diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts index 6473f8d..7653bf8 100644 --- a/node_modules/@types/node/tty.d.ts +++ b/node_modules/@types/node/tty.d.ts @@ -1,10 +1,9 @@ /** - * The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. - * In most cases, it will not be necessary or possible to use this module directly. - * However, it can be accessed using: + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: * * ```js - * const tty = require('tty'); + * const tty = require('node:tty'); * ``` * * When Node.js detects that it is being run with a text terminal ("TTY") @@ -22,7 +21,7 @@ * * In most cases, there should be little to no reason for an application to * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tty.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tty.js) */ declare module 'tty' { import * as net from 'node:net'; @@ -43,7 +42,10 @@ declare module 'tty' { constructor(fd: number, options?: net.SocketConstructorOpts); /** * A `boolean` that is `true` if the TTY is currently configured to operate as a - * raw device. Defaults to `false`. + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to`setRawMode`. * @since v0.7.7 */ isRaw: boolean; diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts index e172acb..af8123d 100644 --- a/node_modules/@types/node/url.d.ts +++ b/node_modules/@types/node/url.d.ts @@ -1,11 +1,11 @@ /** - * The `url` module provides utilities for URL resolution and parsing. It can be - * accessed using: + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: * * ```js - * import url from 'url'; + * import url from 'node:url'; * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/url.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/url.js) */ declare module 'url' { import { Blob as NodeBlob } from 'node:buffer'; @@ -54,17 +54,11 @@ declare module 'url' { * * A `URIError` is thrown if the `auth` property is present but cannot be decoded. * - * Use of the legacy `url.parse()` method is discouraged. Users should - * use the WHATWG `URL` API. Because the `url.parse()` method uses a - * lenient, non-standard algorithm for parsing URL strings, security - * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and - * incorrect handling of usernames and passwords have been identified. - * - * Deprecation of this API has been shelved for now primarily due to the the - * inability of the [WHATWG API to parse relative URLs](https://github.com/nodejs/node/issues/12682#issuecomment-1154492373). - * [Discussions are ongoing](https://github.com/whatwg/url/issues/531) for the best way to resolve this. - * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. * @param urlString The URL string to parse. * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property * on the returned URL object will be an unparsed, undecoded string. @@ -79,15 +73,15 @@ declare module 'url' { * The `url.format()` method returns a formatted URL string derived from`urlObject`. * * ```js - * const url = require('url'); + * const url = require('node:url'); * url.format({ * protocol: 'https', * hostname: 'example.com', * pathname: '/some/path', * query: { * page: 1, - * format: 'json' - * } + * format: 'json', + * }, * }); * * // => 'https://example.com/some/path?page=1&format=json' @@ -135,7 +129,7 @@ declare module 'url' { * string, an `Error` is thrown. * * `result` is returned. * @since v0.1.25 - * @deprecated Legacy: Use the WHATWG URL API instead. + * @legacy Use the WHATWG URL API instead. * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. */ function format(urlObject: URL, options?: URLFormatOptions): string; @@ -199,7 +193,7 @@ declare module 'url' { * string, an `Error` is thrown. * * `result` is returned. * @since v0.1.25 - * @deprecated Legacy: Use the WHATWG URL API instead. + * @legacy Use the WHATWG URL API instead. * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. */ function format(urlObject: UrlObject | string): string; @@ -208,7 +202,7 @@ declare module 'url' { * manner similar to that of a web browser resolving an anchor tag. * * ```js - * const url = require('url'); + * const url = require('node:url'); * url.resolve('/one/two/three', 'four'); // '/one/two/four' * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' @@ -232,7 +226,7 @@ declare module 'url' { * resolve('http://example.com/one', '/two'); // 'http://example.com/two' * ``` * @since v0.1.25 - * @deprecated Legacy: Use the WHATWG URL API instead. + * @legacy Use the WHATWG URL API instead. * @param from The base URL to use if `to` is a relative URL. * @param to The target URL to resolve. */ @@ -243,10 +237,8 @@ declare module 'url' { * * It performs the inverse operation to {@link domainToUnicode}. * - * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. - * * ```js - * import url from 'url'; + * import url from 'node:url'; * * console.log(url.domainToASCII('español.com')); * // Prints xn--espaol-zwa.com @@ -264,10 +256,8 @@ declare module 'url' { * * It performs the inverse operation to {@link domainToASCII}. * - * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. - * * ```js - * import url from 'url'; + * import url from 'node:url'; * * console.log(url.domainToUnicode('xn--espaol-zwa.com')); * // Prints español.com @@ -284,7 +274,7 @@ declare module 'url' { * well as ensuring a cross-platform valid absolute path string. * * ```js - * import { fileURLToPath } from 'url'; + * import { fileURLToPath } from 'node:url'; * * const __filename = fileURLToPath(import.meta.url); * @@ -310,7 +300,7 @@ declare module 'url' { * control characters are correctly encoded when converting into a File URL. * * ```js - * import { pathToFileURL } from 'url'; + * import { pathToFileURL } from 'node:url'; * * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) @@ -328,7 +318,7 @@ declare module 'url' { * expected by the `http.request()` and `https.request()` APIs. * * ```js - * import { urlToHttpOptions } from 'url'; + * import { urlToHttpOptions } from 'node:url'; * const myURL = new URL('https://a:b@測試?abc#foo'); * * console.log(urlToHttpOptions(myURL)); @@ -376,7 +366,7 @@ declare module 'url' { * const { * Blob, * resolveObjectURL, - * } = require('buffer'); + * } = require('node:buffer'); * * const blob = new Blob(['hello']); * const id = URL.createObjectURL(blob); @@ -398,7 +388,7 @@ declare module 'url' { static createObjectURL(blob: NodeBlob): string; /** * Removes the stored `Blob` identified by the given ID. Attempting to revoke a - * ID that isn’t registered will silently fail. + * ID that isn't registered will silently fail. * @since v16.7.0 * @experimental * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. @@ -449,7 +439,7 @@ declare module 'url' { * // Prints example.org * * // Setting the hostname does not change the port - * myURL.hostname = 'example.com:82'; + * myURL.hostname = 'example.com'; * console.log(myURL.href); * // Prints https://example.com:81/foo * @@ -512,7 +502,7 @@ declare module 'url' { * * myURL.password = '123'; * console.log(myURL.href); - * // Prints https://abc:123@example.com + * // Prints https://abc:123@example.com/ * ``` * * Invalid URL characters included in the value assigned to the `password` property @@ -656,14 +646,14 @@ declare module 'url' { * character, while `URLSearchParams` will always encode it: * * ```js - * const myUrl = new URL('https://example.org/abc?foo=~bar'); + * const myURL = new URL('https://example.org/abc?foo=~bar'); * - * console.log(myUrl.search); // prints ?foo=~bar + * console.log(myURL.search); // prints ?foo=~bar * * // Modify the URL via searchParams... - * myUrl.searchParams.sort(); + * myURL.searchParams.sort(); * - * console.log(myUrl.search); // prints ?foo=%7Ebar + * console.log(myURL.search); // prints ?foo=%7Ebar * ``` */ readonly searchParams: URLSearchParams; @@ -758,9 +748,12 @@ declare module 'url' { */ append(name: string, value: string): void; /** - * Remove all name-value pairs whose name is `name`. + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`.. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. */ - delete(name: string): void; + delete(name: string, value?: string): void; /** * Returns an ES6 `Iterator` over each of the name-value pairs in the query. * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. @@ -796,9 +789,15 @@ declare module 'url' { */ getAll(name: string): string[]; /** - * Returns `true` if there is at least one name-value pair whose name is `name`. + * Checks if the `URLSearchParams` object contains key-value pair(s) based on`name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. */ - has(name: string): boolean; + has(name: string, value?: string): boolean; /** * Returns an ES6 `Iterator` over the names of each name-value pair. * @@ -833,6 +832,11 @@ declare module 'url' { * ``` */ set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; /** * Sort all existing name-value pairs in-place by their names. Sorting is done * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts index 6d35019..ce46cb7 100644 --- a/node_modules/@types/node/util.d.ts +++ b/node_modules/@types/node/util.d.ts @@ -1,12 +1,12 @@ /** - * The `util` module supports the needs of Node.js internal APIs. Many of the + * The `node:util` module supports the needs of Node.js internal APIs. Many of the * utilities are useful for application and module developers as well. To access * it: * * ```js - * const util = require('util'); + * const util = require('node:util'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/util.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/util.js) */ declare module 'util' { import * as types from 'node:util/types'; @@ -189,7 +189,7 @@ declare module 'util' { * timestamp. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.log('Timestamped message.'); * ``` @@ -208,12 +208,12 @@ declare module 'util' { * Creates and returns an `AbortController` instance whose `AbortSignal` is marked * as transferable and can be used with `structuredClone()` or `postMessage()`. * @since v18.11.0 + * @experimental * @returns A transferable AbortController */ export function transferableAbortController(): AbortController; /** - * Marks the given {AbortSignal} as transferable so that it can be used with - * `structuredClone()` and `postMessage()`. + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. * * ```js * const signal = transferableAbortSignal(AbortSignal.timeout(100)); @@ -221,10 +221,35 @@ declare module 'util' { * channel.port2.postMessage(signal, [signal]); * ``` * @since v18.11.0 + * @experimental * @param signal The AbortSignal * @returns The same AbortSignal */ export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and + * returns a promise that is fulfilled when the `signal` is + * aborted. If the passed `resource` is garbage collected before the `signal` is + * aborted, the returned promise shall remain pending indefinitely. + * + * ```js + * import { aborted } from 'node:util'; + * + * const dependent = obtainSomethingAbortable(); + * + * aborted(dependent.signal, dependent).then(() => { + * // Do something when dependent is aborted. + * }); + * + * dependent.on('event', () => { + * dependent.abort(); + * }); + * ``` + * @since v19.7.0 + * @experimental + * @param resource Any non-null entity, reference to which is held weakly. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; /** * The `util.inspect()` method returns a string representation of `object` that is * intended for debugging. The output of `util.inspect` may change at any time @@ -251,7 +276,7 @@ declare module 'util' { * Circular references point to their anchor by using a reference index: * * ```js - * const { inspect } = require('util'); + * const { inspect } = require('node:util'); * * const obj = {}; * obj.a = [obj]; @@ -269,7 +294,7 @@ declare module 'util' { * The following example inspects all properties of the `util` object: * * ```js - * const util = require('util'); + * const util = require('node:util'); * * console.log(util.inspect(util, { showHidden: true, depth: null })); * ``` @@ -277,7 +302,7 @@ declare module 'util' { * The following example highlights the effect of the `compact` option: * * ```js - * const util = require('util'); + * const util = require('node:util'); * * const o = { * a: [1, 2, [[ @@ -285,7 +310,7 @@ declare module 'util' { * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', * 'test', * 'foo']], 4], - * b: new Map([['za', 1], ['zb', 'test']]) + * b: new Map([['za', 1], ['zb', 'test']]), * }; * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); * @@ -334,7 +359,7 @@ declare module 'util' { * with no remaining strong references may be garbage collected at any time. * * ```js - * const { inspect } = require('util'); + * const { inspect } = require('node:util'); * * const obj = { a: 1 }; * const obj2 = { b: 2 }; @@ -348,13 +373,13 @@ declare module 'util' { * impact the result of `util.inspect()`. * * ```js - * const { inspect } = require('util'); - * const assert = require('assert'); + * const { inspect } = require('node:util'); + * const assert = require('node:assert'); * * const o1 = { * b: [2, 3, 1], * a: '`a` comes before `b`', - * c: new Set([2, 3, 1]) + * c: new Set([2, 3, 1]), * }; * console.log(inspect(o1, { sorted: true })); * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } @@ -364,11 +389,11 @@ declare module 'util' { * const o2 = { * c: new Set([2, 1, 3]), * a: '`a` comes before `b`', - * b: [2, 3, 1] + * b: [2, 3, 1], * }; * assert.strict.equal( * inspect(o1, { sorted: true }), - * inspect(o2, { sorted: true }) + * inspect(o2, { sorted: true }), * ); * ``` * @@ -376,7 +401,7 @@ declare module 'util' { * numbers. * * ```js - * const { inspect } = require('util'); + * const { inspect } = require('node:util'); * * const thousand = 1_000; * const million = 1_000_000; @@ -388,7 +413,7 @@ declare module 'util' { * ``` * * `util.inspect()` is a synchronous method intended for debugging. Its maximum - * output length is approximately 128 MB. Inputs that result in longer output will + * output length is approximately 128 MiB. Inputs that result in longer output will * be truncated. * @since v0.3.0 * @param object Any JavaScript primitive or `Object`. @@ -417,7 +442,7 @@ declare module 'util' { * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isArray([]); * // Returns: true @@ -434,7 +459,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isRegExp(/some regexp/); * // Returns: true @@ -451,7 +476,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isDate(new Date()); * // Returns: true @@ -468,7 +493,7 @@ declare module 'util' { * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isError(new Error()); * // Returns: true @@ -482,7 +507,7 @@ declare module 'util' { * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * const obj = { name: 'Error', message: 'an error occurred' }; * * util.isError(obj); @@ -507,8 +532,8 @@ declare module 'util' { * through the `constructor.super_` property. * * ```js - * const util = require('util'); - * const EventEmitter = require('events'); + * const util = require('node:util'); + * const EventEmitter = require('node:events'); * * function MyStream() { * EventEmitter.call(this); @@ -534,7 +559,7 @@ declare module 'util' { * ES6 example using `class` and `extends`: * * ```js - * const EventEmitter = require('events'); + * const EventEmitter = require('node:events'); * * class MyStream extends EventEmitter { * write(data) { @@ -550,7 +575,7 @@ declare module 'util' { * stream.write('With ES6'); * ``` * @since v0.3.0 - * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + * @legacy Use ES2015 class syntax and `extends` keyword instead. */ export function inherits(constructor: unknown, superConstructor: unknown): void; export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; @@ -563,7 +588,7 @@ declare module 'util' { * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. * * ```js - * const util = require('util'); + * const util = require('node:util'); * const debuglog = util.debuglog('foo'); * * debuglog('hello from foo [%d]', 123); @@ -582,7 +607,7 @@ declare module 'util' { * The `section` supports wildcard also: * * ```js - * const util = require('util'); + * const util = require('node:util'); * const debuglog = util.debuglog('foo-bar'); * * debuglog('hi there, it\'s foo-bar [%d]', 2333); @@ -602,7 +627,7 @@ declare module 'util' { * unnecessary wrapping. * * ```js - * const util = require('util'); + * const util = require('node:util'); * let debuglog = util.debuglog('internals', (debug) => { * // Replace with a logging function that optimizes out * // testing if the section is enabled @@ -620,7 +645,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isBoolean(1); * // Returns: false @@ -637,7 +662,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isBuffer({ length: 0 }); * // Returns: false @@ -654,7 +679,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * function Foo() {} * const Bar = () => {}; @@ -674,7 +699,7 @@ declare module 'util' { * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isNull(0); * // Returns: false @@ -692,7 +717,7 @@ declare module 'util' { * returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isNullOrUndefined(0); * // Returns: false @@ -709,7 +734,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isNumber(false); * // Returns: false @@ -729,7 +754,7 @@ declare module 'util' { * Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isObject(5); * // Returns: false @@ -741,14 +766,14 @@ declare module 'util' { * // Returns: false * ``` * @since v0.11.5 - * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead. */ export function isObject(object: unknown): boolean; /** * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isPrimitive(5); * // Returns: true @@ -777,7 +802,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isString(''); * // Returns: true @@ -796,7 +821,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isSymbol(5); * // Returns: false @@ -813,7 +838,7 @@ declare module 'util' { * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * const foo = undefined; * util.isUndefined(5); @@ -832,7 +857,7 @@ declare module 'util' { * such a way that it is marked as deprecated. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * exports.obsoleteFunction = util.deprecate(() => { * // Do something here. @@ -848,7 +873,7 @@ declare module 'util' { * the warning will be emitted only once for that `code`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); @@ -902,7 +927,7 @@ declare module 'util' { * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * async function fn() { * return 'hello world'; @@ -985,8 +1010,8 @@ declare module 'util' { * that returns promises. * * ```js - * const util = require('util'); - * const fs = require('fs'); + * const util = require('node:util'); + * const fs = require('node:fs'); * * const stat = util.promisify(fs.stat); * stat('.').then((stats) => { @@ -999,8 +1024,8 @@ declare module 'util' { * Or, equivalently using `async function`s: * * ```js - * const util = require('util'); - * const fs = require('fs'); + * const util = require('node:util'); + * const fs = require('node:fs'); * * const stat = util.promisify(fs.stat); * @@ -1021,7 +1046,7 @@ declare module 'util' { * work as expected unless handled specially: * * ```js - * const util = require('util'); + * const util = require('node:util'); * * class Foo { * constructor() { @@ -1110,7 +1135,7 @@ declare module 'util' { * internally and emitted after the next call to `textDecoder.decode()`. * * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. - * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. */ decode( input?: NodeJS.ArrayBufferView | ArrayBuffer | null, @@ -1170,7 +1195,6 @@ declare module 'util' { */ encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; } - import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from 'util'; global { /** @@ -1178,19 +1202,18 @@ declare module 'util' { * https://nodejs.org/api/globals.html#textdecoder * @since v11.0.0 */ - var TextDecoder: typeof globalThis extends { + var TextDecoder: typeof globalThis extends { onmessage: any; TextDecoder: infer TextDecoder; } ? TextDecoder : typeof _TextDecoder; - /** * `TextEncoder` class is a global reference for `require('util').TextEncoder` * https://nodejs.org/api/globals.html#textencoder * @since v11.0.0 */ - var TextEncoder: typeof globalThis extends { + var TextEncoder: typeof globalThis extends { onmessage: any; TextEncoder: infer TextEncoder; } @@ -1200,48 +1223,34 @@ declare module 'util' { //// parseArgs /** - * Provides a high-level API for command-line argument parsing. Takes a - * specification for the expected arguments and returns a structured object - * with the parsed values and positionals. - * - * `config` provides arguments for parsing and configures the parser. It - * supports the following properties: - * - * - `args` The array of argument strings. **Default:** `process.argv` with - * `execPath` and `filename` removed. - * - `options` Arguments known to the parser. Keys of `options` are the long - * names of options and values are objects accepting the following properties: - * - * - `type` Type of argument, which must be either `boolean` (for options - * which do not take values) or `string` (for options which do). - * - `multiple` Whether this option can be provided multiple - * times. If `true`, all values will be collected in an array. If - * `false`, values for the option are last-wins. **Default:** `false`. - * - `short` A single character alias for the option. - * - `default` The default option value when it is not set by args. It - * must be of the same type as the `type` property. When `multiple` - * is `true`, it must be an array. - * - * - `strict`: Whether an error should be thrown when unknown arguments - * are encountered, or when arguments are passed that do not match the - * `type` configured in `options`. **Default:** `true`. - * - `allowPositionals`: Whether this command accepts positional arguments. - * **Default:** `false` if `strict` is `true`, otherwise `true`. - * - `tokens`: Whether tokens {boolean} Return the parsed tokens. This is useful - * for extending the built-in behavior, from adding additional checks through - * to reprocessing the tokens in different ways. - * **Default:** `false`. - * - * @returns The parsed command line arguments: - * - * - `values` A mapping of parsed option names with their string - * or boolean values. - * - `positionals` Positional arguments. - * - `tokens` Detailed parse information (only if `tokens` was specified). + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: */ export function parseArgs(config?: T): ParsedResults; - interface ParseArgsOptionConfig { /** * Type of argument. @@ -1266,11 +1275,9 @@ declare module 'util' { */ default?: string | boolean | string[] | boolean[] | undefined; } - interface ParseArgsOptionsConfig { [longOption: string]: ParseArgsOptionConfig; } - export interface ParseArgsConfig { /** * Array of argument strings. @@ -1297,7 +1304,6 @@ declare module 'util' { */ tokens?: boolean | undefined; } - /* IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 @@ -1421,11 +1427,103 @@ declare module 'util' { // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. type ParsedResults = ParseArgsConfig extends T ? { - values: { [longOption: string]: undefined | string | boolean | Array }; + values: { + [longOption: string]: undefined | string | boolean | Array; + }; positionals: string[]; tokens?: Token[]; } : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + * @experimental + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + */ + subtype: string; + /** + * Gets the essence of the MIME. + * + * Use `mime.type` or `mime.subtype` to alter the MIME. + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the parameters of the MIME. + */ + readonly params: MIMEParams; + /** + * Returns the serialized MIME. + * + * Because of the need for standard compliance, this method + * does not allow users to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * @since v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + entries(): IterableIterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. + * If there are no such pairs, `null` is returned. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + */ + keys(): IterableIterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. + * If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): IterableIterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator]: typeof MIMEParams.prototype.entries; + } } declare module 'util/types' { export * from 'util/types'; @@ -1723,12 +1821,40 @@ declare module 'util/types' { */ function isModuleNamespaceObject(value: unknown): boolean; /** - * Returns `true` if the value is an instance of a built-in `Error` type. + * Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). * * ```js - * util.types.isNativeError(new Error()); // Returns true - * util.types.isNativeError(new TypeError()); // Returns true - * util.types.isNativeError(new RangeError()); // Returns true + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()`returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false`for these errors: + * + * ```js + * const vm = require('node:vm'); + * const context = vm.createContext({}); + * const myError = vm.runInContext('new Error()', context); + * console.log(util.types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true * ``` * @since v10.0.0 */ diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts index 6685dc2..064f5d5 100644 --- a/node_modules/@types/node/v8.d.ts +++ b/node_modules/@types/node/v8.d.ts @@ -1,10 +1,10 @@ /** - * The `v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: * * ```js - * const v8 = require('v8'); + * const v8 = require('node:v8'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/v8.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/v8.js) */ declare module 'v8' { import { Readable } from 'node:stream'; @@ -29,6 +29,9 @@ declare module 'v8' { does_zap_garbage: DoesZapCodeSpaceFlag; number_of_native_contexts: number; number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; } interface HeapCodeStatistics { code_and_metadata_size: number; @@ -68,6 +71,15 @@ declare module 'v8' { * of contexts that were detached and not yet garbage collected. This number * being non-zero indicates a potential memory leak. * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * * ```js * { * total_heap_size: 7326976, @@ -80,7 +92,10 @@ declare module 'v8' { * peak_malloced_memory: 1127496, * does_zap_garbage: 0, * number_of_native_contexts: 1, - * number_of_detached_contexts: 0 + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 * } * ``` * @since v1.0.0 @@ -149,7 +164,7 @@ declare module 'v8' { * * ```js * // Print GC events to stdout for one minute. - * const v8 = require('v8'); + * const v8 = require('node:v8'); * v8.setFlagsFromString('--trace_gc'); * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); * ``` @@ -172,12 +187,12 @@ declare module 'v8' { * * ```js * // Print heap snapshot to the console - * const v8 = require('v8'); + * const v8 = require('node:v8'); * const stream = v8.getHeapSnapshot(); * stream.pipe(process.stdout); * ``` * @since v11.13.0 - * @return A Readable Stream containing the V8 heap snapshot + * @return A Readable containing the V8 heap snapshot. */ function getHeapSnapshot(): Readable; /** @@ -197,12 +212,12 @@ declare module 'v8' { * for a duration depending on the heap size. * * ```js - * const { writeHeapSnapshot } = require('v8'); + * const { writeHeapSnapshot } = require('node:v8'); * const { * Worker, * isMainThread, - * parentPort - * } = require('worker_threads'); + * parentPort, + * } = require('node:worker_threads'); * * if (isMainThread) { * const worker = new Worker(__filename); @@ -233,13 +248,16 @@ declare module 'v8' { */ function writeHeapSnapshot(filename?: string): string; /** - * Returns an object with the following properties: + * Get statistics about code and its metadata in the heap, see + * V8[`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: * * ```js * { * code_and_metadata_size: 212208, * bytecode_and_metadata_size: 161368, - * external_script_source_size: 1410794 + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, * } * ``` * @since v12.8.0 @@ -289,7 +307,7 @@ declare module 'v8' { */ writeDouble(value: number): void; /** - * Write raw bytes into the serializer’s internal buffer. The deserializer + * Write raw bytes into the serializer's internal buffer. The deserializer * will require a way to compute the length of the buffer. * For use inside of a custom `serializer._writeHostObject()`. */ @@ -345,7 +363,7 @@ declare module 'v8' { */ readDouble(): number; /** - * Read raw bytes from the deserializer’s internal buffer. The `length` parameter + * Read raw bytes from the deserializer's internal buffer. The `length` parameter * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. * For use inside of a custom `deserializer._readHostObject()`. */ @@ -390,6 +408,227 @@ declare module 'v8' { * @since v15.1.0, v14.18.0, v12.22.0 */ function stopCoverage(): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object.The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * const { GCProfiler } = require('v8'); + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; } declare module 'node:v8' { export * from 'v8'; diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts index c96513a..e293a50 100644 --- a/node_modules/@types/node/vm.d.ts +++ b/node_modules/@types/node/vm.d.ts @@ -1,8 +1,8 @@ /** - * The `vm` module enables compiling and running code within V8 Virtual + * The `node:vm` module enables compiling and running code within V8 Virtual * Machine contexts. * - * **The `vm` module is not a security** + * **The `node:vm` module is not a security** * **mechanism. Do not use it to run untrusted code.** * * JavaScript code can be compiled and run immediately or @@ -17,7 +17,7 @@ * code are reflected in the context object. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const x = 1; * @@ -34,7 +34,7 @@ * * console.log(x); // 1; y is not defined. * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/vm.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/vm.js) */ declare module 'vm' { interface Context extends NodeJS.Dict {} @@ -56,11 +56,17 @@ declare module 'vm' { columnOffset?: number | undefined; } interface ScriptOptions extends BaseOptions { - displayErrors?: boolean | undefined; - timeout?: number | undefined; - cachedData?: Buffer | undefined; + /** + * V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; /** @deprecated in favor of `script.createCachedData()` */ produceCachedData?: boolean | undefined; + /** + * Called during evaluation of this module when `import()` is called. + * If this option is not specified, calls to `import()` will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`. + */ + importModuleDynamically?: ((specifier: string, script: Script, importAssertions: Object) => Module) | undefined; } interface RunningScriptOptions extends BaseOptions { /** @@ -80,10 +86,31 @@ declare module 'vm' { * Default: `false`. */ breakOnSigint?: boolean | undefined; + } + interface RunningScriptInNewContextOptions extends RunningScriptOptions { + /** + * Human-readable name of the newly created context. + */ + contextName?: CreateContextOptions['name']; + /** + * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, + * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + */ + contextOrigin?: CreateContextOptions['origin']; + contextCodeGeneration?: CreateContextOptions['codeGeneration']; /** * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. */ - microtaskMode?: 'afterEvaluate' | undefined; + microtaskMode?: CreateContextOptions['microtaskMode']; + } + interface RunningCodeOptions extends RunningScriptOptions { + cachedData?: ScriptOptions['cachedData']; + importModuleDynamically?: ScriptOptions['importModuleDynamically']; + } + interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { + cachedData?: ScriptOptions['cachedData']; + importModuleDynamically?: ScriptOptions['importModuleDynamically']; } interface CompileFunctionOptions extends BaseOptions { /** @@ -144,7 +171,10 @@ declare module 'vm' { * @default 'summary' */ mode?: MeasureMemoryMode | undefined; - context?: Context | undefined; + /** + * @default 'default' + */ + execution?: 'default' | 'eager' | undefined; } interface MemoryMeasurement { total: { @@ -158,7 +188,7 @@ declare module 'vm' { * @since v0.3.1 */ class Script { - constructor(code: string, options?: ScriptOptions); + constructor(code: string, options?: ScriptOptions | string); /** * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access * to local scope. @@ -168,11 +198,11 @@ declare module 'vm' { * The globals are contained in the `context` object. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const context = { * animal: 'cat', - * count: 2 + * count: 2, * }; * * const script = new vm.Script('count += 1; name = "kitty";'); @@ -204,7 +234,7 @@ declare module 'vm' { * contained within each individual `context`. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const script = new vm.Script('globalVar = "set"'); * @@ -220,7 +250,7 @@ declare module 'vm' { * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. * @return the result of the very last statement executed in the script. */ - runInNewContext(contextObject?: Context, options?: RunningScriptOptions): any; + runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any; /** * Runs the compiled code contained by the `vm.Script` within the context of the * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. @@ -229,7 +259,7 @@ declare module 'vm' { * executes that code multiple times: * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * global.globalVar = 0; * @@ -251,6 +281,16 @@ declare module 'vm' { * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any * time and any number of times. * + * The code cache of the `Script` doesn't contain any JavaScript observable + * states. The code cache is safe to be saved along side the script source and + * used to construct new `Script` instances multiple times. + * + * Functions in the `Script` source can be marked as lazily compiled and they are + * not compiled at construction of the `Script`. These functions are going to be + * compiled when they are invoked the first time. The code cache serializes the + * metadata that V8 currently knows about the `Script` that it can use to speed up + * future compilations. + * * ```js * const script = new vm.Script(` * function add(a, b) { @@ -260,19 +300,46 @@ declare module 'vm' { * const x = add(1, 2); * `); * - * const cacheWithoutX = script.createCachedData(); + * const cacheWithoutAdd = script.createCachedData(); + * // In `cacheWithoutAdd` the function `add()` is marked for full compilation + * // upon invocation. * * script.runInThisContext(); * - * const cacheWithX = script.createCachedData(); + * const cacheWithAdd = script.createCachedData(); + * // `cacheWithAdd` contains fully compiled function `add()`. * ``` * @since v10.6.0 */ createCachedData(): Buffer; /** @deprecated in favor of `script.createCachedData()` */ cachedDataProduced?: boolean | undefined; + /** + * When `cachedData` is supplied to create the `vm.Script`, this value will be set + * to either `true` or `false` depending on acceptance of the data by V8\. + * Otherwise the value is `undefined`. + * @since v5.7.0 + */ cachedDataRejected?: boolean | undefined; cachedData?: Buffer | undefined; + /** + * When the script is compiled from a source that contains a source map magic + * comment, this property will be set to the URL of the source map. + * + * ```js + * import vm from 'node:vm'; + * + * const script = new vm.Script(` + * function myFunc() {} + * //# sourceMappingURL=sourcemap.json + * `); + * + * console.log(script.sourceMapURL); + * // Prints: sourcemap.json + * ``` + * @since v19.1.0, v18.13.0 + */ + sourceMapURL?: string | undefined; } /** * If given a `contextObject`, the `vm.createContext()` method will `prepare @@ -282,7 +349,7 @@ declare module 'vm' { * will remain unchanged. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * global.globalVar = 3; * @@ -329,7 +396,7 @@ declare module 'vm' { * The following example compiles and executes different scripts using a single `contextified` object: * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const contextObject = { globalVar: 1 }; * vm.createContext(contextObject); @@ -345,7 +412,7 @@ declare module 'vm' { * @param contextifiedObject The `contextified` object that will be used as the `global` when the `code` is compiled and run. * @return the result of the very last statement executed in the script. */ - function runInContext(code: string, contextifiedObject: Context, options?: RunningScriptOptions | string): any; + function runInContext(code: string, contextifiedObject: Context, options?: RunningCodeOptions | string): any; /** * The `vm.runInNewContext()` first contextifies the given `contextObject` (or * creates a new `contextObject` if passed as `undefined`), compiles the `code`, @@ -358,11 +425,11 @@ declare module 'vm' { * variable and sets a new one. These globals are contained in the `contextObject`. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * * const contextObject = { * animal: 'cat', - * count: 2 + * count: 2, * }; * * vm.runInNewContext('count += 1; name = "kitty"', contextObject); @@ -374,7 +441,7 @@ declare module 'vm' { * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. * @return the result of the very last statement executed in the script. */ - function runInNewContext(code: string, contextObject?: Context, options?: RunningScriptOptions | string): any; + function runInNewContext(code: string, contextObject?: Context, options?: RunningCodeInNewContextOptions | string): any; /** * `vm.runInThisContext()` compiles `code`, runs it within the context of the * current `global` and returns the result. Running code does not have access to @@ -386,7 +453,7 @@ declare module 'vm' { * the JavaScript [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function to run the same code: * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * let localVar = 'initial value'; * * const vmResult = vm.runInThisContext('localVar = "vm";'); @@ -407,17 +474,17 @@ declare module 'vm' { * When using either `script.runInThisContext()` or {@link runInThisContext}, the code is executed within the current V8 global * context. The code passed to this VM context will have its own isolated scope. * - * In order to run a simple web server using the `http` module the code passed to - * the context must either call `require('http')` on its own, or have a reference - * to the `http` module passed to it. For instance: + * In order to run a simple web server using the `node:http` module the code passed + * to the context must either call `require('node:http')` on its own, or have a + * reference to the `node:http` module passed to it. For instance: * * ```js * 'use strict'; - * const vm = require('vm'); + * const vm = require('node:vm'); * * const code = ` * ((require) => { - * const http = require('http'); + * const http = require('node:http'); * * http.createServer((request, response) => { * response.writeHead(200, { 'Content-Type': 'text/plain' }); @@ -437,7 +504,7 @@ declare module 'vm' { * @param code The JavaScript code to compile and run. * @return the result of the very last statement executed in the script. */ - function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + function runInThisContext(code: string, options?: RunningCodeOptions | string): any; /** * Compiles the given code into the provided context (if no context is * supplied, the current context is used), and returns it wrapped inside a @@ -446,7 +513,15 @@ declare module 'vm' { * @param code The body of the function to compile. * @param params An array of strings containing all parameters for the function. */ - function compileFunction(code: string, params?: ReadonlyArray, options?: CompileFunctionOptions): Function; + function compileFunction( + code: string, + params?: ReadonlyArray, + options?: CompileFunctionOptions + ): Function & { + cachedData?: Script['cachedData'] | undefined; + cachedDataProduced?: Script['cachedDataProduced'] | undefined; + cachedDataRejected?: Script['cachedDataRejected'] | undefined; + }; /** * Measure the memory known to V8 and used by all contexts known to the * current V8 isolate, or the main context. @@ -460,7 +535,7 @@ declare module 'vm' { * the memory occupied by each heap space in the current V8 instance. * * ```js - * const vm = require('vm'); + * const vm = require('node:vm'); * // Measure the memory used by the main context. * vm.measureMemory({ mode: 'summary' }) * // This is the same as vm.measureMemory() @@ -503,6 +578,316 @@ declare module 'vm' { * @experimental */ function measureMemory(options?: MeasureMemoryOptions): Promise; + interface ModuleEvaluateOptions { + timeout?: RunningScriptOptions['timeout'] | undefined; + breakOnSigint?: RunningScriptOptions['breakOnSigint'] | undefined; + } + type ModuleLinker = ( + specifier: string, + referencingModule: Module, + extra: { + assert: Object; + } + ) => Module | Promise; + type ModuleStatus = 'unlinked' | 'linking' | 'linked' | 'evaluating' | 'evaluated' | 'errored'; + /** + * This feature is only available with the `--experimental-vm-modules` command + * flag enabled. + * + * The `vm.Module` class provides a low-level interface for using + * ECMAScript modules in VM contexts. It is the counterpart of the `vm.Script`class that closely mirrors [Module Record](https://www.ecma-international.org/ecma-262/#sec-abstract-module-records) + * s as defined in the ECMAScript + * specification. + * + * Unlike `vm.Script` however, every `vm.Module` object is bound to a context from + * its creation. Operations on `vm.Module` objects are intrinsically asynchronous, + * in contrast with the synchronous nature of `vm.Script` objects. The use of + * 'async' functions can help with manipulating `vm.Module` objects. + * + * Using a `vm.Module` object requires three distinct steps: creation/parsing, + * linking, and evaluation. These three steps are illustrated in the following + * example. + * + * This implementation lies at a lower level than the `ECMAScript Module + * loader`. There is also no way to interact with the Loader yet, though + * support is planned. + * + * ```js + * import vm from 'node:vm'; + * + * const contextifiedObject = vm.createContext({ + * secret: 42, + * print: console.log, + * }); + * + * // Step 1 + * // + * // Create a Module by constructing a new `vm.SourceTextModule` object. This + * // parses the provided source text, throwing a `SyntaxError` if anything goes + * // wrong. By default, a Module is created in the top context. But here, we + * // specify `contextifiedObject` as the context this Module belongs to. + * // + * // Here, we attempt to obtain the default export from the module "foo", and + * // put it into local binding "secret". + * + * const bar = new vm.SourceTextModule(` + * import s from 'foo'; + * s; + * print(s); + * `, { context: contextifiedObject }); + * + * // Step 2 + * // + * // "Link" the imported dependencies of this Module to it. + * // + * // The provided linking callback (the "linker") accepts two arguments: the + * // parent module (`bar` in this case) and the string that is the specifier of + * // the imported module. The callback is expected to return a Module that + * // corresponds to the provided specifier, with certain requirements documented + * // in `module.link()`. + * // + * // If linking has not started for the returned Module, the same linker + * // callback will be called on the returned Module. + * // + * // Even top-level Modules without dependencies must be explicitly linked. The + * // callback provided would never be called, however. + * // + * // The link() method returns a Promise that will be resolved when all the + * // Promises returned by the linker resolve. + * // + * // Note: This is a contrived example in that the linker function creates a new + * // "foo" module every time it is called. In a full-fledged module system, a + * // cache would probably be used to avoid duplicated modules. + * + * async function linker(specifier, referencingModule) { + * if (specifier === 'foo') { + * return new vm.SourceTextModule(` + * // The "secret" variable refers to the global variable we added to + * // "contextifiedObject" when creating the context. + * export default secret; + * `, { context: referencingModule.context }); + * + * // Using `contextifiedObject` instead of `referencingModule.context` + * // here would work as well. + * } + * throw new Error(`Unable to resolve dependency: ${specifier}`); + * } + * await bar.link(linker); + * + * // Step 3 + * // + * // Evaluate the Module. The evaluate() method returns a promise which will + * // resolve after the module has finished evaluating. + * + * // Prints 42. + * await bar.evaluate(); + * ``` + * @since v13.0.0, v12.16.0 + * @experimental + */ + class Module { + /** + * The specifiers of all dependencies of this module. The returned array is frozen + * to disallow any changes to it. + * + * Corresponds to the `[[RequestedModules]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in + * the ECMAScript specification. + */ + dependencySpecifiers: readonly string[]; + /** + * If the `module.status` is `'errored'`, this property contains the exception + * thrown by the module during evaluation. If the status is anything else, + * accessing this property will result in a thrown exception. + * + * The value `undefined` cannot be used for cases where there is not a thrown + * exception due to possible ambiguity with `throw undefined;`. + * + * Corresponds to the `[[EvaluationError]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s + * in the ECMAScript specification. + */ + error: any; + /** + * The identifier of the current module, as set in the constructor. + */ + identifier: string; + context: Context; + /** + * The namespace object of the module. This is only available after linking + * (`module.link()`) has completed. + * + * Corresponds to the [GetModuleNamespace](https://tc39.es/ecma262/#sec-getmodulenamespace) abstract operation in the ECMAScript + * specification. + */ + namespace: Object; + /** + * The current status of the module. Will be one of: + * + * * `'unlinked'`: `module.link()` has not yet been called. + * * `'linking'`: `module.link()` has been called, but not all Promises returned + * by the linker function have been resolved yet. + * * `'linked'`: The module has been linked successfully, and all of its + * dependencies are linked, but `module.evaluate()` has not yet been called. + * * `'evaluating'`: The module is being evaluated through a `module.evaluate()` on + * itself or a parent module. + * * `'evaluated'`: The module has been successfully evaluated. + * * `'errored'`: The module has been evaluated, but an exception was thrown. + * + * Other than `'errored'`, this status string corresponds to the specification's [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)'s `[[Status]]` field. `'errored'` + * corresponds to`'evaluated'` in the specification, but with `[[EvaluationError]]` set to a + * value that is not `undefined`. + */ + status: ModuleStatus; + /** + * Evaluate the module. + * + * This must be called after the module has been linked; otherwise it will reject. + * It could be called also when the module has already been evaluated, in which + * case it will either do nothing if the initial evaluation ended in success + * (`module.status` is `'evaluated'`) or it will re-throw the exception that the + * initial evaluation resulted in (`module.status` is `'errored'`). + * + * This method cannot be called while the module is being evaluated + * (`module.status` is `'evaluating'`). + * + * Corresponds to the [Evaluate() concrete method](https://tc39.es/ecma262/#sec-moduleevaluation) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in the + * ECMAScript specification. + * @return Fulfills with `undefined` upon success. + */ + evaluate(options?: ModuleEvaluateOptions): Promise; + /** + * Link module dependencies. This method must be called before evaluation, and + * can only be called once per module. + * + * The function is expected to return a `Module` object or a `Promise` that + * eventually resolves to a `Module` object. The returned `Module` must satisfy the + * following two invariants: + * + * * It must belong to the same context as the parent `Module`. + * * Its `status` must not be `'errored'`. + * + * If the returned `Module`'s `status` is `'unlinked'`, this method will be + * recursively called on the returned `Module` with the same provided `linker`function. + * + * `link()` returns a `Promise` that will either get resolved when all linking + * instances resolve to a valid `Module`, or rejected if the linker function either + * throws an exception or returns an invalid `Module`. + * + * The linker function roughly corresponds to the implementation-defined [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) abstract operation in the + * ECMAScript + * specification, with a few key differences: + * + * * The linker function is allowed to be asynchronous while [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) is synchronous. + * + * The actual [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation used during module + * linking is one that returns the modules linked during linking. Since at + * that point all modules would have been fully linked already, the [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation is fully synchronous per + * specification. + * + * Corresponds to the [Link() concrete method](https://tc39.es/ecma262/#sec-moduledeclarationlinking) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in + * the ECMAScript specification. + */ + link(linker: ModuleLinker): Promise; + } + interface SourceTextModuleOptions { + /** + * String used in stack traces. + * @default 'vm:module(i)' where i is a context-specific ascending index. + */ + identifier?: string | undefined; + cachedData?: ScriptOptions['cachedData'] | undefined; + context?: Context | undefined; + lineOffset?: BaseOptions['lineOffset'] | undefined; + columnOffset?: BaseOptions['columnOffset'] | undefined; + /** + * Called during evaluation of this module to initialize the `import.meta`. + */ + initializeImportMeta?: ((meta: ImportMeta, module: SourceTextModule) => void) | undefined; + importModuleDynamically?: ScriptOptions['importModuleDynamically'] | undefined; + } + /** + * This feature is only available with the `--experimental-vm-modules` command + * flag enabled. + * + * + * + * The `vm.SourceTextModule` class provides the [Source Text Module Record](https://tc39.es/ecma262/#sec-source-text-module-records) as + * defined in the ECMAScript specification. + * @since v9.6.0 + * @experimental + */ + class SourceTextModule extends Module { + /** + * Creates a new `SourceTextModule` instance. + * @param code JavaScript Module code to parse + */ + constructor(code: string, options?: SourceTextModuleOptions); + } + interface SyntheticModuleOptions { + /** + * String used in stack traces. + * @default 'vm:module(i)' where i is a context-specific ascending index. + */ + identifier?: string | undefined; + /** + * The contextified object as returned by the `vm.createContext()` method, to compile and evaluate this module in. + */ + context?: Context | undefined; + } + /** + * This feature is only available with the `--experimental-vm-modules` command + * flag enabled. + * + * + * + * The `vm.SyntheticModule` class provides the [Synthetic Module Record](https://heycam.github.io/webidl/#synthetic-module-records) as + * defined in the WebIDL specification. The purpose of synthetic modules is to + * provide a generic interface for exposing non-JavaScript sources to ECMAScript + * module graphs. + * + * ```js + * const vm = require('node:vm'); + * + * const source = '{ "a": 1 }'; + * const module = new vm.SyntheticModule(['default'], function() { + * const obj = JSON.parse(source); + * this.setExport('default', obj); + * }); + * + * // Use `module` in linking... + * ``` + * @since v13.0.0, v12.16.0 + * @experimental + */ + class SyntheticModule extends Module { + /** + * Creates a new `SyntheticModule` instance. + * @param exportNames Array of names that will be exported from the module. + * @param evaluateCallback Called when the module is evaluated. + */ + constructor(exportNames: string[], evaluateCallback: (this: SyntheticModule) => void, options?: SyntheticModuleOptions); + /** + * This method is used after the module is linked to set the values of exports. If + * it is called before the module is linked, an `ERR_VM_MODULE_STATUS` error + * will be thrown. + * + * ```js + * import vm from 'node:vm'; + * + * const m = new vm.SyntheticModule(['x'], () => { + * m.setExport('x', 1); + * }); + * + * await m.link(() => {}); + * await m.evaluate(); + * + * assert.strictEqual(m.namespace.x, 1); + * ``` + * @since v13.0.0, v12.16.0 + * @param name Name of the export to set. + * @param value The value to set the export to. + */ + setExport(name: string, value: any): void; + } } declare module 'node:vm' { export * from 'vm'; diff --git a/node_modules/@types/node/wasi.d.ts b/node_modules/@types/node/wasi.d.ts index d20b66b..b430b3a 100644 --- a/node_modules/@types/node/wasi.d.ts +++ b/node_modules/@types/node/wasi.d.ts @@ -3,26 +3,23 @@ * underlying operating system via a collection of POSIX-like functions. * * ```js - * import { readFile } from 'fs/promises'; + * import { readFile } from 'node:fs/promises'; * import { WASI } from 'wasi'; - * import { argv, env } from 'process'; + * import { argv, env } from 'node:process'; * * const wasi = new WASI({ + * version: 'preview1', * args: argv, * env, * preopens: { - * '/sandbox': '/some/real/path/that/wasm/can/access' - * } + * '/sandbox': '/some/real/path/that/wasm/can/access', + * }, * }); * - * // Some WASI binaries require: - * // const importObject = { wasi_unstable: wasi.wasiImport }; - * const importObject = { wasi_snapshot_preview1: wasi.wasiImport }; - * * const wasm = await WebAssembly.compile( - * await readFile(new URL('./demo.wasm', import.meta.url)) + * await readFile(new URL('./demo.wasm', import.meta.url)), * ); - * const instance = await WebAssembly.instantiate(wasm, importObject); + * const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject()); * * wasi.start(instance); * ``` @@ -61,14 +58,11 @@ * * Use [wabt](https://github.com/WebAssembly/wabt) to compile `.wat` to `.wasm` * - * ```console - * $ wat2wasm demo.wat + * ```bash + * wat2wasm demo.wat * ``` - * - * The `--experimental-wasi-unstable-preview1` CLI argument is needed for this - * example to run. * @experimental - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/wasi.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/wasi.js) */ declare module 'wasi' { interface WASIOptions { @@ -91,11 +85,11 @@ declare module 'wasi' { */ preopens?: NodeJS.Dict | undefined; /** - * By default, WASI applications terminate the Node.js - * process via the `__wasi_proc_exit()` function. Setting this option to `true` - * causes `wasi.start()` to return the exit code rather than terminate the - * process. - * @default false + * By default, when WASI applications call `__wasi_proc_exit()` + * `wasi.start()` will return with the exit code specified rather than terminatng the process. + * Setting this option to `false` will cause the Node.js process to exit with + * the specified exit code instead. + * @default true */ returnOnExit?: boolean | undefined; /** diff --git a/node_modules/@types/node/worker_threads.d.ts b/node_modules/@types/node/worker_threads.d.ts index 52f4384..e11932e 100644 --- a/node_modules/@types/node/worker_threads.d.ts +++ b/node_modules/@types/node/worker_threads.d.ts @@ -1,9 +1,9 @@ /** - * The `worker_threads` module enables the use of threads that execute JavaScript - * in parallel. To access it: + * The `node:worker_threads` module enables the use of threads that execute + * JavaScript in parallel. To access it: * * ```js - * const worker = require('worker_threads'); + * const worker = require('node:worker_threads'); * ``` * * Workers (threads) are useful for performing CPU-intensive JavaScript operations. @@ -15,14 +15,14 @@ * * ```js * const { - * Worker, isMainThread, parentPort, workerData - * } = require('worker_threads'); + * Worker, isMainThread, parentPort, workerData, + * } = require('node:worker_threads'); * * if (isMainThread) { * module.exports = function parseJSAsync(script) { * return new Promise((resolve, reject) => { * const worker = new Worker(__filename, { - * workerData: script + * workerData: script, * }); * worker.on('message', resolve); * worker.on('error', reject); @@ -49,7 +49,7 @@ * * Worker threads inherit non-process-specific options by default. Refer to `Worker constructor options` to know how to customize worker thread options, * specifically `argv` and `execArgv` options. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/worker_threads.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/worker_threads.js) */ declare module 'worker_threads' { import { Blob } from 'node:buffer'; @@ -72,7 +72,7 @@ declare module 'worker_threads' { * The `MessageChannel` has no methods of its own. `new MessageChannel()`yields an object with `port1` and `port2` properties, which refer to linked `MessagePort` instances. * * ```js - * const { MessageChannel } = require('worker_threads'); + * const { MessageChannel } = require('node:worker_threads'); * * const { port1, port2 } = new MessageChannel(); * port1.on('message', (message) => console.log('received', message)); @@ -121,7 +121,7 @@ declare module 'worker_threads' { * * `value` may not contain native (C++-backed) objects other than: * * ```js - * const { MessageChannel } = require('worker_threads'); + * const { MessageChannel } = require('node:worker_threads'); * const { port1, port2 } = new MessageChannel(); * * port1.on('message', (message) => console.log(message)); @@ -132,7 +132,7 @@ declare module 'worker_threads' { * port2.postMessage(circularData); * ``` * - * `transferList` may be a list of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), `MessagePort` and `FileHandle` objects. + * `transferList` may be a list of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), `MessagePort`, and `FileHandle` objects. * After transferring, they are not usable on the sending side of the channel * anymore (even if they are not contained in `value`). Unlike with `child processes`, transferring handles such as network sockets is currently * not supported. @@ -143,7 +143,7 @@ declare module 'worker_threads' { * `value` may still contain `ArrayBuffer` instances that are not in`transferList`; in that case, the underlying memory is copied rather than moved. * * ```js - * const { MessageChannel } = require('worker_threads'); + * const { MessageChannel } = require('node:worker_threads'); * const { port1, port2 } = new MessageChannel(); * * port1.on('message', (message) => console.log(message)); @@ -170,7 +170,7 @@ declare module 'worker_threads' { * posting without having side effects. * * For more information on the serialization and deserialization mechanisms - * behind this API, see the `serialization API of the v8 module`. + * behind this API, see the `serialization API of the node:v8 module`. * @since v10.5.0 */ postMessage(value: any, transferList?: ReadonlyArray): void; @@ -262,6 +262,12 @@ declare module 'worker_threads' { * @default true */ trackUnmanagedFds?: boolean | undefined; + /** + * An optional `name` to be appended to the worker title + * for debuggin/identification purposes, making the final title as + * `[worker ${id}] ${name}`. + */ + name?: string | undefined; } interface ResourceLimits { /** @@ -288,9 +294,9 @@ declare module 'worker_threads' { * * Notable differences inside a Worker environment are: * - * * The `process.stdin`, `process.stdout` and `process.stderr` may be redirected by the parent thread. - * * The `require('worker_threads').isMainThread` property is set to `false`. - * * The `require('worker_threads').parentPort` message port is available. + * * The `process.stdin`, `process.stdout`, and `process.stderr` streams may be redirected by the parent thread. + * * The `require('node:worker_threads').isMainThread` property is set to `false`. + * * The `require('node:worker_threads').parentPort` message port is available. * * `process.exit()` does not stop the whole program, just the single thread, * and `process.abort()` is not available. * * `process.chdir()` and `process` methods that set group or user ids @@ -307,11 +313,11 @@ declare module 'worker_threads' { * * Creating `Worker` instances inside of other `Worker`s is possible. * - * Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `cluster module`, two-way communication can be - * achieved through inter-thread message passing. Internally, a `Worker` has a - * built-in pair of `MessagePort` s that are already associated with each other - * when the `Worker` is created. While the `MessagePort` object on the parent side - * is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event + * Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `node:cluster module`, two-way communication + * can be achieved through inter-thread message passing. Internally, a `Worker` has + * a built-in pair of `MessagePort` s that are already associated with each + * other when the `Worker` is created. While the `MessagePort` object on the parent + * side is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event * on the `Worker` object for the parent thread. * * To create custom messaging channels (which is encouraged over using the default @@ -324,10 +330,10 @@ declare module 'worker_threads' { * the thread barrier. * * ```js - * const assert = require('assert'); + * const assert = require('node:assert'); * const { - * Worker, MessageChannel, MessagePort, isMainThread, parentPort - * } = require('worker_threads'); + * Worker, MessageChannel, MessagePort, isMainThread, parentPort, + * } = require('node:worker_threads'); * if (isMainThread) { * const worker = new Worker(__filename); * const subChannel = new MessageChannel(); @@ -367,7 +373,7 @@ declare module 'worker_threads' { readonly stderr: Readable; /** * An integer identifier for the referenced thread. Inside the worker thread, - * it is available as `require('worker_threads').threadId`. + * it is available as `require('node:worker_threads').threadId`. * This value is unique for each `Worker` instance inside a single process. * @since v10.5.0 */ @@ -394,7 +400,7 @@ declare module 'worker_threads' { */ constructor(filename: string | URL, options?: WorkerOptions); /** - * Send a message to the worker that is received via `require('worker_threads').parentPort.on('message')`. + * Send a message to the worker that is received via `require('node:worker_threads').parentPort.on('message')`. * See `port.postMessage()` for more details. * @since v10.5.0 */ @@ -488,8 +494,8 @@ declare module 'worker_threads' { * const { * isMainThread, * BroadcastChannel, - * Worker - * } = require('worker_threads'); + * Worker, + * } = require('node:worker_threads'); * * const bc = new BroadcastChannel('hello'); * @@ -543,7 +549,7 @@ declare module 'worker_threads' { * This operation cannot be undone. * * ```js - * const { MessageChannel, markAsUntransferable } = require('worker_threads'); + * const { MessageChannel, markAsUntransferable } = require('node:worker_threads'); * * const pooledBuffer = new ArrayBuffer(8); * const typedArray1 = new Uint8Array(pooledBuffer); @@ -585,10 +591,10 @@ declare module 'worker_threads' { function moveMessagePortToContext(port: MessagePort, contextifiedSandbox: Context): MessagePort; /** * Receive a single message from a given `MessagePort`. If no message is available,`undefined` is returned, otherwise an object with a single `message` property - * that contains the message payload, corresponding to the oldest message in the`MessagePort`’s queue. + * that contains the message payload, corresponding to the oldest message in the`MessagePort`'s queue. * * ```js - * const { MessageChannel, receiveMessageOnPort } = require('worker_threads'); + * const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads'); * const { port1, port2 } = new MessageChannel(); * port1.postMessage({ hello: 'world' }); * @@ -619,7 +625,7 @@ declare module 'worker_threads' { * isMainThread, * setEnvironmentData, * getEnvironmentData, - * } = require('worker_threads'); + * } = require('node:worker_threads'); * * if (isMainThread) { * setEnvironmentData('Hello', 'World!'); @@ -658,7 +664,6 @@ declare module 'worker_threads' { } ? T : typeof _BroadcastChannel; - /** * `MessageChannel` class is a global reference for `require('worker_threads').MessageChannel` * https://nodejs.org/api/globals.html#messagechannel @@ -670,13 +675,12 @@ declare module 'worker_threads' { } ? T : typeof _MessageChannel; - /** * `MessagePort` class is a global reference for `require('worker_threads').MessagePort` * https://nodejs.org/api/globals.html#messageport * @since v15.0.0 */ - var MessagePort: typeof globalThis extends { + var MessagePort: typeof globalThis extends { onmessage: any; MessagePort: infer T; } diff --git a/node_modules/@types/node/zlib.d.ts b/node_modules/@types/node/zlib.d.ts index 1d7f0c0..9d74cd2 100644 --- a/node_modules/@types/node/zlib.d.ts +++ b/node_modules/@types/node/zlib.d.ts @@ -1,11 +1,11 @@ /** - * The `zlib` module provides compression functionality implemented using Gzip, - * Deflate/Inflate, and Brotli. + * The `node:zlib` module provides compression functionality implemented using + * Gzip, Deflate/Inflate, and Brotli. * * To access it: * * ```js - * const zlib = require('zlib'); + * const zlib = require('node:zlib'); * ``` * * Compression and decompression are built around the Node.js `Streams API`. @@ -15,12 +15,12 @@ * stream: * * ```js - * const { createGzip } = require('zlib'); - * const { pipeline } = require('stream'); + * const { createGzip } = require('node:zlib'); + * const { pipeline } = require('node:stream'); * const { * createReadStream, - * createWriteStream - * } = require('fs'); + * createWriteStream, + * } = require('node:fs'); * * const gzip = createGzip(); * const source = createReadStream('input.txt'); @@ -35,7 +35,7 @@ * * // Or, Promisified * - * const { promisify } = require('util'); + * const { promisify } = require('node:util'); * const pipe = promisify(pipeline); * * async function do_gzip(input, output) { @@ -55,7 +55,7 @@ * It is also possible to compress or decompress data in a single step: * * ```js - * const { deflate, unzip } = require('zlib'); + * const { deflate, unzip } = require('node:zlib'); * * const input = '.................................'; * deflate(input, (err, buffer) => { @@ -77,7 +77,7 @@ * * // Or, Promisified * - * const { promisify } = require('util'); + * const { promisify } = require('node:util'); * const do_unzip = promisify(unzip); * * do_unzip(buffer) @@ -88,7 +88,7 @@ * }); * ``` * @since v0.5.8 - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/zlib.js) + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/zlib.js) */ declare module 'zlib' { import * as stream from 'node:stream'; diff --git a/node_modules/@types/ws/README.md b/node_modules/@types/ws/README.md index a077205..0d81018 100644 --- a/node_modules/@types/ws/README.md +++ b/node_modules/@types/ws/README.md @@ -8,7 +8,7 @@ This package contains type definitions for ws (https://github.com/websockets/ws) Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ws. ### Additional Details - * Last updated: Fri, 30 Dec 2022 00:32:41 GMT + * Last updated: Thu, 08 Jun 2023 20:02:52 GMT * Dependencies: [@types/node](https://npmjs.com/package/@types/node) * Global values: none diff --git a/node_modules/@types/ws/index.d.ts b/node_modules/@types/ws/index.d.ts index 7a8182a..5cf4748 100644 --- a/node_modules/@types/ws/index.d.ts +++ b/node_modules/@types/ws/index.d.ts @@ -231,15 +231,19 @@ declare namespace WebSocket { * incoming message. The return value (boolean) of the function determines * whether or not to accept the handshake. */ - type VerifyClientCallbackSync = (info: { origin: string; secure: boolean; req: IncomingMessage }) => boolean; + type VerifyClientCallbackSync = (info: { + origin: string; + secure: boolean; + req: Request; + }) => boolean; /** * VerifyClientCallbackAsync is an asynchronous callback used to inspect the * incoming message. The return value (boolean) of the function determines * whether or not to accept the handshake. */ - type VerifyClientCallbackAsync = ( - info: { origin: string; secure: boolean; req: IncomingMessage }, + type VerifyClientCallbackAsync = ( + info: { origin: string; secure: boolean; req: Request }, callback: (res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void, ) => void; @@ -314,20 +318,26 @@ declare namespace WebSocket { once?: boolean | undefined; } - interface ServerOptions { + interface ServerOptions< + U extends typeof WebSocket.WebSocket = typeof WebSocket.WebSocket, + V extends typeof IncomingMessage = typeof IncomingMessage, + > { host?: string | undefined; port?: number | undefined; backlog?: number | undefined; - server?: HTTPServer | HTTPSServer | undefined; - verifyClient?: VerifyClientCallbackAsync | VerifyClientCallbackSync | undefined; - handleProtocols?: (protocols: Set, request: IncomingMessage) => string | false; + server?: HTTPServer | HTTPSServer | undefined; + verifyClient?: + | VerifyClientCallbackAsync> + | VerifyClientCallbackSync> + | undefined; + handleProtocols?: (protocols: Set, request: InstanceType) => string | false; path?: string | undefined; noServer?: boolean | undefined; clientTracking?: boolean | undefined; perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined; maxPayload?: number | undefined; skipUTF8Validation?: boolean | undefined; - WebSocket?: typeof WebSocket.WebSocket | undefined; + WebSocket?: U | undefined; } interface AddressInfo { @@ -337,51 +347,54 @@ declare namespace WebSocket { } // WebSocket Server - class Server extends EventEmitter { - options: ServerOptions; + class Server< + T extends typeof WebSocket.WebSocket = typeof WebSocket.WebSocket, + U extends typeof IncomingMessage = typeof IncomingMessage, + > extends EventEmitter { + options: ServerOptions; path: string; - clients: Set; + clients: Set>; - constructor(options?: ServerOptions, callback?: () => void); + constructor(options?: ServerOptions, callback?: () => void); address(): AddressInfo | string; close(cb?: (err?: Error) => void): void; handleUpgrade( - request: IncomingMessage, + request: InstanceType, socket: Duplex, upgradeHead: Buffer, - callback: (client: T, request: IncomingMessage) => void, + callback: (client: InstanceType, request: InstanceType) => void, ): void; - shouldHandle(request: IncomingMessage): boolean | Promise; + shouldHandle(request: InstanceType): boolean | Promise; // Events - on(event: "connection", cb: (this: Server, socket: T, request: IncomingMessage) => void): this; + on(event: "connection", cb: (this: Server, socket: InstanceType, request: InstanceType) => void): this; on(event: "error", cb: (this: Server, error: Error) => void): this; - on(event: "headers", cb: (this: Server, headers: string[], request: IncomingMessage) => void): this; + on(event: "headers", cb: (this: Server, headers: string[], request: InstanceType) => void): this; on(event: "close" | "listening", cb: (this: Server) => void): this; on(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; - once(event: "connection", cb: (this: Server, socket: T, request: IncomingMessage) => void): this; + once(event: "connection", cb: (this: Server, socket: InstanceType, request: InstanceType) => void): this; once(event: "error", cb: (this: Server, error: Error) => void): this; - once(event: "headers", cb: (this: Server, headers: string[], request: IncomingMessage) => void): this; + once(event: "headers", cb: (this: Server, headers: string[], request: InstanceType) => void): this; once(event: "close" | "listening", cb: (this: Server) => void): this; once(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; - off(event: "connection", cb: (this: Server, socket: T, request: IncomingMessage) => void): this; + off(event: "connection", cb: (this: Server, socket: InstanceType, request: InstanceType) => void): this; off(event: "error", cb: (this: Server, error: Error) => void): this; - off(event: "headers", cb: (this: Server, headers: string[], request: IncomingMessage) => void): this; + off(event: "headers", cb: (this: Server, headers: string[], request: InstanceType) => void): this; off(event: "close" | "listening", cb: (this: Server) => void): this; off(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; - addListener(event: "connection", cb: (client: T, request: IncomingMessage) => void): this; + addListener(event: "connection", cb: (client: InstanceType, request: InstanceType) => void): this; addListener(event: "error", cb: (err: Error) => void): this; - addListener(event: "headers", cb: (headers: string[], request: IncomingMessage) => void): this; + addListener(event: "headers", cb: (headers: string[], request: InstanceType) => void): this; addListener(event: "close" | "listening", cb: () => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: "connection", cb: (client: T) => void): this; + removeListener(event: "connection", cb: (client: InstanceType, request: InstanceType) => void): this; removeListener(event: "error", cb: (err: Error) => void): this; - removeListener(event: "headers", cb: (headers: string[], request: IncomingMessage) => void): this; + removeListener(event: "headers", cb: (headers: string[], request: InstanceType) => void): this; removeListener(event: "close" | "listening", cb: () => void): this; removeListener(event: string | symbol, listener: (...args: any[]) => void): this; } diff --git a/node_modules/@types/ws/package.json b/node_modules/@types/ws/package.json index b214c62..1b945c7 100644 --- a/node_modules/@types/ws/package.json +++ b/node_modules/@types/ws/package.json @@ -1,6 +1,6 @@ { "name": "@types/ws", - "version": "8.5.4", + "version": "8.5.5", "description": "TypeScript definitions for ws", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ws", "license": "MIT", @@ -57,8 +57,8 @@ "dependencies": { "@types/node": "*" }, - "typesPublisherContentHash": "d78ccf27d7710f245ab25f9d4957067c8fc0f7aadc035919f7a890427d7360ca", - "typeScriptVersion": "4.2", + "typesPublisherContentHash": "6eea0ac9982d9cb29e842a5be3f7d3e0103c444a7b96a324c0ce4a86980da93f", + "typeScriptVersion": "4.3", "exports": { ".": { "types": { diff --git a/node_modules/@vladfrangu/async_event_emitter/CHANGELOG.md b/node_modules/@vladfrangu/async_event_emitter/CHANGELOG.md new file mode 100644 index 0000000..eb7a4bf --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/CHANGELOG.md @@ -0,0 +1,63 @@ +# Changelog +All notable changes to this project will be documented in this file. + +# [2.2.2](https://github.com/vladfrangu/async_event_emitter/compare/v2.2.1...v2.2.2) - (2023-05-11) + +## 🐛 Bug Fixes + +- Listener count was always 0 for one listener ([9b78e19](https://github.com/vladfrangu/async_event_emitter/commit/9b78e1992db649004dee852359240b3d0baaac2d)) + +# [2.2.1](https://github.com/vladfrangu/async_event_emitter/compare/v2.2.0...v2.2.1) - (2023-04-08) + +## 🐛 Bug Fixes + +- Include comment for throwing error on emit ([19de045](https://github.com/vladfrangu/async_event_emitter/commit/19de0452702a0d9e35e9241259d100ca6d6f5447)) + +# [2.2.0](https://github.com/vladfrangu/async_event_emitter/compare/v2.1.4...v2.2.0) - (2023-04-07) + +## 🚀 Features + +- Speed 🚀 ([23eb908](https://github.com/vladfrangu/async_event_emitter/commit/23eb90852ff8a6ceb4d6105c6df44c646642efae)) + +# [2.1.4](https://github.com/vladfrangu/async_event_emitter/compare/v2.1.3...v2.1.4) - (2023-02-18) + +## 🐛 Bug Fixes + +- Remove predefined error event to allow extensions ([4224bbe](https://github.com/vladfrangu/async_event_emitter/commit/4224bbeae5c25cb94d4073600a9dff7ae3abcceb)) + +# [2.1.2](https://github.com/vladfrangu/async_event_emitter/compare/v2.1.1...v2.1.2) - (2022-09-19) + +## 🐛 Bug Fixes + +- Don't use any `@types/node` types ([e4babce](https://github.com/vladfrangu/async_event_emitter/commit/e4babce88c17befdb6f84c73c0de2e0602260681)) + +# [2.1.1](https://github.com/vladfrangu/async_event_emitter/compare/v2.1.0...v2.1.1) - (2022-09-19) + +## 🐛 Bug Fixes + +- Correct type errors when building with other types too ([72a03ae](https://github.com/vladfrangu/async_event_emitter/commit/72a03ae1ac30456241b4003a7c2ea93d27e8de5e)) + +# [2.1.0](https://github.com/vladfrangu/async_event_emitter/compare/v2.0.1...v2.1.0) - (2022-09-18) + +## 🚀 Features + +- Bring in line with nodejs EventEmitters ([5a14ed0](https://github.com/vladfrangu/async_event_emitter/commit/5a14ed04bf87ec6a34cd33e26e3f25f101f87bcd)) + +# [2.0.1](https://github.com/vladfrangu/async_event_emitter/compare/v2.0.0...v2.0.1) - (2022-07-09) + +## 🐛 Bug Fixes + +- Error event not properly emitting ([b849b38](https://github.com/vladfrangu/async_event_emitter/commit/b849b387c36515c60234c06681bfd4ec32ee5336)) + +# [2.0.0](https://github.com/vladfrangu/async_event_emitter/compare/v1.0.1...v2.0.0) - (2022-06-29) + +## 🚀 Features + +- Use stringified bigints instead of uuids for promise map ([8c69419](https://github.com/vladfrangu/async_event_emitter/commit/8c694199da1a0a231feb1be3b0d7cfdb18cefd0b)) + + ### 💥 Breaking Changes: + + +# Changelog + +All notable changes to this project will be documented in this file. diff --git a/node_modules/@vladfrangu/async_event_emitter/LICENSE.md b/node_modules/@vladfrangu/async_event_emitter/LICENSE.md new file mode 100644 index 0000000..6bd5831 --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/LICENSE.md @@ -0,0 +1,24 @@ +# The MIT License (MIT) + +Copyright © `2022` `Vlad Frangu` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@vladfrangu/async_event_emitter/README.md b/node_modules/@vladfrangu/async_event_emitter/README.md new file mode 100644 index 0000000..ceb0d20 --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/README.md @@ -0,0 +1,51 @@ +

+ +# @vladfrangu/async_event_emitter + +**Simple to use event emitter implementation with async support in mind.** + +[![GitHub](https://img.shields.io/github/license/vladfrangu/async_event_emitter)](https://github.com/vladfrangu/async_event_emitter/blob/main/LICENSE.md) +[![codecov](https://codecov.io/gh/vladfrangu/async_event_emitter/branch/main/graph/badge.svg?token=0MSAyoZNxz)](https://codecov.io/gh/vladfrangu/async_event_emitter) +[![npm](https://img.shields.io/npm/v/@vladfrangu/async_event_emitter?color=crimson&logo=npm&style=flat-square)](https://www.npmjs.com/package/@vladfrangu/async_event_emitter) + +
+ +## Description + +A very small, lightweight and simple re-implementation of event emitters, with support for async event handlers in mind. + +> **Note**: `@vladfrangu/async_event_emitter` requires Node.js v14 or higher to work, or a browser that has async/await support. + +## Features + +- TypeScript friendly +- Offers CJS, ESM and UMD builds +- Consistent interface with what is expected from an event emitter +- Simple handling of asynchronous event handlers to allow waiting for their execution to finish if you want to exit the process + +## Buy me some doughnuts + +Most of my projects are and always will be open source, even if I don't get donations. That being said, I know there are amazing people who may still want to donate just to show their appreciation. Thank you very much in advance! + +I accept donations through Ko-fi, PayPal, Patreon and GitHub Sponsorships. You can use the buttons below to donate through your method of choice. + +| Donate With | Address | +| :-------------: | :------------------------------------------------------: | +| GitHub Sponsors | [Click Here](https://github.com/sponsors/vladfrangu) | +| Ko-fi | [Click Here](https://ko-fi.com/wolfgalvlad) | +| Patreon | [Click Here](https://patreon.com/vladfrangu) | +| PayPal | [Click Here](https://www.paypal.com/paypalme/franguvlad) | + +## Contributors ✨ + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! diff --git a/node_modules/mysql/node_modules/safe-buffer/LICENSE b/node_modules/@vladfrangu/async_event_emitter/THIRD_PARTY_LICENSE.md similarity index 54% rename from node_modules/mysql/node_modules/safe-buffer/LICENSE rename to node_modules/@vladfrangu/async_event_emitter/THIRD_PARTY_LICENSE.md index 0c068ce..7e35926 100644 --- a/node_modules/mysql/node_modules/safe-buffer/LICENSE +++ b/node_modules/@vladfrangu/async_event_emitter/THIRD_PARTY_LICENSE.md @@ -1,12 +1,14 @@ -The MIT License (MIT) +# Most parts of this code are from node.js, specifically from https://github.com/nodejs/node/blob/main/lib/events.js -Copyright (c) Feross Aboukhadijeh +As such, a lot of the code is licensed under the following license: + +Copyright Node.js contributors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is +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 @@ -16,6 +18,6 @@ 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. +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/@vladfrangu/async_event_emitter/dist/index.d.ts b/node_modules/@vladfrangu/async_event_emitter/dist/index.d.ts new file mode 100644 index 0000000..ef909d8 --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/dist/index.d.ts @@ -0,0 +1,57 @@ +/// +declare class AsyncEventEmitter = Record & AsyncEventEmitterPredefinedEvents> { + private _events; + private _eventCount; + private _maxListeners; + private _internalPromiseMap; + private _wrapperId; + addListener(eventName: K, listener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void): this; + on(eventName: K, listener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void): this; + once(eventName: K, listener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void): this; + removeListener(eventName: K, listener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void): this; + off(eventName: K, listener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void): this; + removeAllListeners(event?: K | undefined): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(eventName: K): Listener['listener'][]; + rawListeners(eventName: K): Listener[]; + emit(eventName: K, ...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]): boolean; + listenerCount(eventName: K): number; + prependListener(eventName: K, listener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void): this; + prependOnceListener(eventName: K, listener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void): this; + eventNames(): (keyof Events | keyof AsyncEventEmitterPredefinedEvents)[]; + waitForAllListenersToComplete(): Promise; + private _addListener; + private _wrapListener; + static listenerCount, EventNames = Emitter extends AsyncEventEmitter ? Events : never, EventName extends PropertyKey = EventNames extends never ? string | symbol : keyof EventNames>(emitter: Emitter, eventName: EventName | keyof AsyncEventEmitterPredefinedEvents): number; + static once, EventNames extends Record = Emitter extends AsyncEventEmitter ? Events : Record, EventName extends PropertyKey = keyof EventNames | keyof AsyncEventEmitterPredefinedEvents, EventResult extends unknown[] = EventName extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[EventName] : EventNames[EventName]>(emitter: Emitter, eventName: EventName, options?: AbortableMethods): Promise; + static on, EventNames extends Record = Emitter extends AsyncEventEmitter ? Events : Record, EventName extends PropertyKey = keyof EventNames | keyof AsyncEventEmitterPredefinedEvents, EventResult extends unknown[] = EventName extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[EventName] : EventNames[EventName]>(emitter: Emitter, eventName: EventName, options?: AbortableMethods): AsyncGenerator; +} +interface AsyncEventEmitterPredefinedEvents { + newListener: [eventName: string | symbol, listener: (...args: any[]) => Awaitable]; + removeListener: [eventName: string | symbol, listener: (...args: any[]) => Awaitable]; +} +interface WrappedOnce { + (...args: Args): Awaitable; + listener: (...args: Args) => Awaitable; + _hasWarnedAboutMaxListeners?: boolean; +} +interface Listener { + (...args: Args): Awaitable; + listener: (...args: Args) => Awaitable; + _hasWarnedAboutMaxListeners?: boolean; +} +type Awaitable = T | Promise; +interface AbortableMethods { + signal?: AbortSignal; +} +interface AbortErrorOptions { + cause?: unknown; +} +declare class AbortError extends Error { + readonly code = "ABORT_ERR"; + readonly name = "AbortError"; + constructor(message?: string, options?: AbortErrorOptions | undefined); +} + +export { AbortError, AbortErrorOptions, AbortableMethods, AsyncEventEmitter, AsyncEventEmitterPredefinedEvents, Awaitable, Listener, WrappedOnce }; diff --git a/node_modules/@vladfrangu/async_event_emitter/dist/index.global.js b/node_modules/@vladfrangu/async_event_emitter/dist/index.global.js new file mode 100644 index 0000000..b528f19 --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/dist/index.global.js @@ -0,0 +1,568 @@ +"use strict"; +var AsyncEventEmitter = (() => { + 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, { + AbortError: () => AbortError, + AsyncEventEmitter: () => AsyncEventEmitter + }); + function validateListener(input) { + if (typeof input !== "function") { + throw new TypeError(`The listener argument must be a function. Received ${typeof input}`); + } + } + __name(validateListener, "validateListener"); + function validateAbortSignal(input) { + if (input && !(input instanceof AbortSignal)) { + throw new TypeError(`The signal option must be an AbortSignal. Received ${input}`); + } + } + __name(validateAbortSignal, "validateAbortSignal"); + function spliceOne(list, index) { + for (; index + 1 < list.length; index++) { + list[index] = list[index + 1]; + } + list.pop(); + } + __name(spliceOne, "spliceOne"); + function arrayClone(arr) { + switch (arr.length) { + case 2: + return [arr[0], arr[1]]; + case 3: + return [arr[0], arr[1], arr[2]]; + case 4: + return [arr[0], arr[1], arr[2], arr[3]]; + case 5: + return [arr[0], arr[1], arr[2], arr[3], arr[4]]; + case 6: + return [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]]; + } + return arr.slice(); + } + __name(arrayClone, "arrayClone"); + function identicalSequenceRange(a, b) { + for (let i = 0; i < a.length - 3; i++) { + const pos = b.indexOf(a[i]); + if (pos !== -1) { + const rest = b.length - pos; + if (rest > 3) { + let len = 1; + const maxLen = Math.min(a.length - i, rest); + while (maxLen > len && a[i + len] === b[pos + len]) { + len++; + } + if (len > 3) { + return [len, i]; + } + } + } + } + return [0, 0]; + } + __name(identicalSequenceRange, "identicalSequenceRange"); + function enhanceStackTrace(err, own) { + let ctorInfo = ""; + try { + const { name } = this.constructor; + if (name !== "AsyncEventEmitter") + ctorInfo = ` on ${name} instance`; + } catch { + } + const sep = ` +Emitted 'error' event${ctorInfo} at: +`; + const errStack = err.stack.split("\n").slice(1); + const ownStack = own.stack.split("\n").slice(1); + const { 0: len, 1: off } = identicalSequenceRange(ownStack, errStack); + if (len > 0) { + ownStack.splice(off + 1, len - 2, " [... lines matching original stack trace ...]"); + } + return err.stack + sep + ownStack.join("\n"); + } + __name(enhanceStackTrace, "enhanceStackTrace"); + var AsyncEventEmitter = class { + constructor() { + this._events = { + __proto__: null + }; + this._eventCount = 0; + this._maxListeners = 10; + this._internalPromiseMap = /* @__PURE__ */ new Map(); + this._wrapperId = 0n; + } + addListener(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, false); + this._addListener(eventName, wrapped, false); + return this; + } + on(eventName, listener) { + return this.addListener(eventName, listener); + } + once(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, true); + this._addListener(eventName, wrapped, false); + return this; + } + removeListener(eventName, listener) { + validateListener(listener); + const events = this._events; + const eventList = events[eventName]; + if (eventList === void 0) { + return this; + } + if (eventList === listener || eventList.listener === listener) { + if (--this._eventCount === 0) { + this._events = { __proto__: null }; + } else { + delete events[eventName]; + if (events.removeListener) { + this.emit("removeListener", eventName, eventList.listener ?? eventList); + } + } + } else if (typeof eventList !== "function") { + let position = -1; + for (let i = eventList.length - 1; i >= 0; i--) { + if (eventList[i] === listener || eventList[i].listener === listener) { + position = i; + break; + } + } + if (position < 0) { + return this; + } + if (position === 0) { + eventList.shift(); + } else { + spliceOne(eventList, position); + } + if (eventList.length === 0) { + delete events[eventName]; + --this._eventCount; + } + if (events.removeListener !== void 0) { + this.emit("removeListener", eventName, listener); + } + } + return this; + } + off(eventName, listener) { + return this.removeListener(eventName, listener); + } + removeAllListeners(event) { + const events = this._events; + if (events.removeListener === void 0) { + if (!event) { + this._events = { __proto__: null }; + this._eventCount = 0; + } else if (events[event] !== void 0) { + if (--this._eventCount === 0) { + this._events = { __proto__: null }; + } else { + delete events[event]; + } + } + return this; + } + if (!event) { + for (const key of Reflect.ownKeys(events)) { + if (key === "removeListener") { + continue; + } + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = { __proto__: null }; + this._eventCount = 0; + return this; + } + const listeners = events[event]; + if (typeof listeners === "function") { + this.removeListener(event, listeners); + } else if (listeners !== void 0) { + for (let i = listeners.length - 1; i >= 0; i--) { + this.removeListener(event, listeners[i]); + } + } + return this; + } + setMaxListeners(n) { + if (typeof n !== "number" || n < 0 || Number.isNaN(n)) { + throw new RangeError(`Expected to get a non-negative number for "setMaxListeners", got ${n} instead`); + } + this._maxListeners = n; + return this; + } + getMaxListeners() { + return this._maxListeners; + } + listeners(eventName) { + const eventList = this._events[eventName]; + if (eventList === void 0) { + return []; + } + if (typeof eventList === "function") { + return [eventList.listener ?? eventList]; + } + const ret = arrayClone(eventList); + for (let i = 0; i < ret.length; ++i) { + const orig = ret[i].listener; + if (typeof orig === "function") { + ret[i] = orig; + } + } + return ret; + } + rawListeners(eventName) { + const eventList = this._events[eventName]; + if (eventList === void 0) { + return []; + } + if (typeof eventList === "function") { + return [eventList]; + } + return arrayClone(eventList); + } + emit(eventName, ...args) { + let doError = eventName === "error"; + const events = this._events; + if (events !== void 0) { + doError = doError && events.error === void 0; + } else if (!doError) { + return false; + } + if (doError) { + let er; + if (args.length > 0) { + er = args[0]; + } + if (er instanceof Error) { + try { + const capture = {}; + Error.captureStackTrace(capture, AsyncEventEmitter.prototype.emit); + Object.defineProperty(er, "stack", { + value: enhanceStackTrace.call(this, er, capture), + configurable: true + }); + } catch { + } + throw er; // Unhandled 'error' event + } + const stringifiedError = String(er); + const err = new Error(`Unhandled 'error' event emitted, received ${stringifiedError}`); + err.context = er; + throw err; // Unhandled 'error' event + } + const handlers = events[eventName]; + if (handlers === void 0) { + return false; + } + if (typeof handlers === "function") { + const result = handlers.apply(this, args); + if (result !== void 0 && result !== null) { + handleMaybeAsync(this, result); + } + } else { + const len = handlers.length; + const listeners = arrayClone(handlers); + for (let i = 0; i < len; ++i) { + const result = listeners[i].apply(this, args); + if (result !== void 0 && result !== null) { + handleMaybeAsync(this, result); + } + } + } + return true; + } + listenerCount(eventName) { + const events = this._events; + if (events === void 0) { + return 0; + } + const eventListeners = events[eventName]; + if (typeof eventListeners === "function") { + return 1; + } + return eventListeners?.length ?? 0; + } + prependListener(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, false); + this._addListener(eventName, wrapped, true); + return this; + } + prependOnceListener(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, true); + this._addListener(eventName, wrapped, true); + return this; + } + eventNames() { + return this._eventCount > 0 ? Reflect.ownKeys(this._events) : []; + } + async waitForAllListenersToComplete() { + const promises = [...this._internalPromiseMap.values()]; + if (promises.length === 0) { + return false; + } + await Promise.all(promises); + return true; + } + _addListener(eventName, wrappedListener, prepend) { + if (this._events.newListener !== void 0) { + this.emit("newListener", eventName, wrappedListener.listener ?? wrappedListener); + } + let existing = this._events[eventName]; + if (existing === void 0) { + existing = this._events[eventName] = wrappedListener; + ++this._eventCount; + } else if (typeof existing === "function") { + existing = this._events[eventName] = prepend ? [wrappedListener, existing] : [existing, wrappedListener]; + } else if (prepend) { + existing.unshift(wrappedListener); + } else { + existing.push(wrappedListener); + } + if (this._maxListeners > 0 && existing.length > this._maxListeners && !existing._hasWarnedAboutMaxListeners) { + existing._hasWarnedAboutMaxListeners = true; + const warningMessage = [ + `Possible AsyncEventEmitter memory leak detected. ${existing.length} ${String(eventName)} listeners added to ${this.constructor.name}.`, + `Use emitter.setMaxListeners() to increase the limit.` + ].join(" "); + console.warn(warningMessage); + } + } + _wrapListener(eventName, listener, once) { + if (!once) { + return listener; + } + const state = { + fired: false, + wrapFn: void 0, + eventEmitter: this, + eventName, + listener + }; + const aliased = onceWrapper; + const wrapped = aliased.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; + } + static listenerCount(emitter, eventName) { + return emitter.listenerCount(eventName); + } + static async once(emitter, eventName, options = {}) { + const signal = options?.signal; + validateAbortSignal(signal); + if (signal?.aborted) { + throw new AbortError(void 0, { cause: getReason(signal) }); + } + return new Promise((resolve, reject) => { + const errorListener = /* @__PURE__ */ __name((err) => { + emitter.removeListener(eventName, resolver); + if (signal) { + eventTargetAgnosticRemoveListener(emitter, eventName, abortListener); + } + reject(err); + }, "errorListener"); + const resolver = /* @__PURE__ */ __name((...args) => { + emitter.removeListener("error", errorListener); + if (signal) { + eventTargetAgnosticRemoveListener(signal, "abort", abortListener); + } + resolve(args); + }, "resolver"); + emitter.once(eventName, resolver); + if (eventName !== "error") { + emitter.once("error", errorListener); + } + const abortListener = /* @__PURE__ */ __name(() => { + eventTargetAgnosticRemoveListener(emitter, eventName, resolver); + eventTargetAgnosticRemoveListener(emitter, "error", errorListener); + reject(new AbortError(void 0, { cause: getReason(signal) })); + }, "abortListener"); + if (signal) { + eventTargetAgnosticAddListener(signal, "abort", abortListener, { once: true }); + } + }); + } + static on(emitter, eventName, options = {}) { + const signal = options?.signal; + validateAbortSignal(signal); + if (signal?.aborted) { + throw new AbortError(void 0, { cause: getReason(signal) }); + } + const unconsumedEvents = []; + const unconsumedPromises = []; + let error = null; + let finished = false; + const abortListener = /* @__PURE__ */ __name(() => { + errorHandler(new AbortError(void 0, { cause: getReason(signal) })); + }, "abortListener"); + const eventHandler = /* @__PURE__ */ __name((...args) => { + const promise = unconsumedPromises.shift(); + if (promise) { + promise.resolve(createIterResult(args, false)); + } else { + unconsumedEvents.push(args); + } + }, "eventHandler"); + const errorHandler = /* @__PURE__ */ __name((err) => { + finished = true; + const toError = unconsumedPromises.shift(); + if (toError) { + toError.reject(err); + } else { + error = err; + } + void iterator.return(); + }, "errorHandler"); + const iterator = Object.setPrototypeOf( + { + next() { + const value = unconsumedEvents.shift(); + if (value) { + return Promise.resolve(createIterResult(value, false)); + } + if (error) { + const p = Promise.reject(error); + error = null; + return p; + } + if (finished) { + return Promise.resolve(createIterResult(void 0, true)); + } + return new Promise((resolve, reject) => { + unconsumedPromises.push({ resolve, reject }); + }); + }, + return() { + emitter.off(eventName, eventHandler); + emitter.off("error", errorHandler); + if (signal) { + eventTargetAgnosticRemoveListener(signal, "abort", abortListener); + } + finished = true; + const doneResult = createIterResult(void 0, true); + for (const promise of unconsumedPromises) { + promise.resolve(doneResult); + } + return Promise.resolve(doneResult); + }, + throw(err) { + if (!err || !(err instanceof Error)) { + throw new TypeError(`Expected Error instance to be thrown in AsyncEventEmitter.AsyncIterator. Got ${err}`); + } + error = err; + emitter.off(eventName, eventHandler); + emitter.off("error", errorHandler); + }, + [Symbol.asyncIterator]() { + return this; + } + }, + AsyncIteratorPrototype + ); + emitter.on(eventName, eventHandler); + if (eventName !== "error") { + emitter.on("error", errorHandler); + } + if (signal) { + eventTargetAgnosticAddListener(signal, "abort", abortListener); + } + return iterator; + } + }; + __name(AsyncEventEmitter, "AsyncEventEmitter"); + function onceWrapper() { + if (!this.fired) { + this.eventEmitter.removeListener(this.eventName, this.wrapFn); + this.fired = true; + if (arguments.length === 0) { + return this.listener.call(this.eventEmitter); + } + return this.listener.apply(this.eventEmitter, arguments); + } + } + __name(onceWrapper, "onceWrapper"); + function getReason(signal) { + return signal?.reason; + } + __name(getReason, "getReason"); + function eventTargetAgnosticRemoveListener(emitter, name, listener, flags) { + if (typeof emitter.off === "function") { + emitter.off(name, listener); + } else if (typeof emitter.removeEventListener === "function") { + emitter.removeEventListener(name, listener, flags); + } + } + __name(eventTargetAgnosticRemoveListener, "eventTargetAgnosticRemoveListener"); + function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === "function") { + if (flags?.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name, listener, flags); + } + } + __name(eventTargetAgnosticAddListener, "eventTargetAgnosticAddListener"); + var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { + }).prototype); + function createIterResult(value, done) { + return { value, done }; + } + __name(createIterResult, "createIterResult"); + var AbortError = class extends Error { + constructor(message = "The operation was aborted", options = void 0) { + if (options !== void 0 && typeof options !== "object") { + throw new TypeError(`Failed to create AbortError: options is not an object or undefined`); + } + super(message, options); + this.code = "ABORT_ERR"; + this.name = "AbortError"; + } + }; + __name(AbortError, "AbortError"); + function handleMaybeAsync(emitter, result) { + try { + const fin = result.finally; + if (typeof fin === "function") { + const promiseId = String(++emitter["_wrapperId"]); + emitter["_internalPromiseMap"].set(promiseId, result); + fin.call(result, /* @__PURE__ */ __name(function final() { + emitter["_internalPromiseMap"].delete(promiseId); + }, "final")); + } + } catch (err) { + emitter.emit("error", err); + } + } + __name(handleMaybeAsync, "handleMaybeAsync"); + return __toCommonJS(src_exports); +})(); +//# sourceMappingURL=index.global.js.map \ No newline at end of file diff --git a/node_modules/@vladfrangu/async_event_emitter/dist/index.global.js.map b/node_modules/@vladfrangu/async_event_emitter/dist/index.global.js.map new file mode 100644 index 0000000..25a5ce7 --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/dist/index.global.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/dot-notation */\nfunction validateListener(input: unknown): asserts input is (...args: unknown[]) => Awaitable {\n\tif (typeof input !== 'function') {\n\t\tthrow new TypeError(`The listener argument must be a function. Received ${typeof input}`);\n\t}\n}\n\nfunction validateAbortSignal(input: unknown): asserts input is AbortSignal | undefined {\n\t// Only validate that the signal is a signal if its defined\n\tif (input && !(input instanceof AbortSignal)) {\n\t\tthrow new TypeError(`The signal option must be an AbortSignal. Received ${input}`);\n\t}\n}\n\n// Inspired from https://github.com/nodejs/node/blob/42ad967d68137df1a80a877e7b5ad56403fc157f/lib/internal/util.js#L397\nfunction spliceOne(list: unknown[], index: number) {\n\tfor (; index + 1 < list.length; index++) {\n\t\tlist[index] = list[index + 1];\n\t}\n\n\tlist.pop();\n}\n\n// Inspired from https://github.com/nodejs/node/blob/42ad967d68137df1a80a877e7b5ad56403fc157f/lib/events.js#L889\nfunction arrayClone(arr: T): T {\n\t// At least since V8 8.3, this implementation is faster than the previous\n\t// which always used a simple for-loop\n\tswitch (arr.length) {\n\t\tcase 2:\n\t\t\treturn [arr[0], arr[1]] as T;\n\t\tcase 3:\n\t\t\treturn [arr[0], arr[1], arr[2]] as T;\n\t\tcase 4:\n\t\t\treturn [arr[0], arr[1], arr[2], arr[3]] as T;\n\t\tcase 5:\n\t\t\treturn [arr[0], arr[1], arr[2], arr[3], arr[4]] as T;\n\t\tcase 6:\n\t\t\treturn [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]] as T;\n\t}\n\n\treturn arr.slice() as T;\n}\n\n// Inspired from https://github.com/nodejs/node/blob/42ad967d68137df1a80a877e7b5ad56403fc157f/lib/events.js#L427-L475\nfunction identicalSequenceRange(a: unknown[], b: unknown[]): [number, number] {\n\tfor (let i = 0; i < a.length - 3; i++) {\n\t\t// Find the first entry of b that matches the current entry of a.\n\t\tconst pos = b.indexOf(a[i]);\n\t\tif (pos !== -1) {\n\t\t\tconst rest = b.length - pos;\n\t\t\tif (rest > 3) {\n\t\t\t\tlet len = 1;\n\t\t\t\tconst maxLen = Math.min(a.length - i, rest);\n\t\t\t\t// Count the number of consecutive entries.\n\t\t\t\twhile (maxLen > len && a[i + len] === b[pos + len]) {\n\t\t\t\t\tlen++;\n\t\t\t\t}\n\t\t\t\tif (len > 3) {\n\t\t\t\t\treturn [len, i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [0, 0];\n}\n\nfunction enhanceStackTrace(this: AsyncEventEmitter, err: Error, own: Error) {\n\tlet ctorInfo = '';\n\ttry {\n\t\tconst { name } = this.constructor;\n\t\tif (name !== 'AsyncEventEmitter') ctorInfo = ` on ${name} instance`;\n\t} catch {\n\t\t// Continue regardless of error.\n\t}\n\tconst sep = `\\nEmitted 'error' event${ctorInfo} at:\\n`;\n\n\tconst errStack = err.stack!.split('\\n').slice(1);\n\tconst ownStack = own.stack!.split('\\n').slice(1);\n\n\tconst { 0: len, 1: off } = identicalSequenceRange(ownStack, errStack);\n\tif (len > 0) {\n\t\townStack.splice(off + 1, len - 2, ' [... lines matching original stack trace ...]');\n\t}\n\n\treturn err.stack + sep + ownStack.join('\\n');\n}\n\ninterface InternalEventMap extends Array {\n\t_hasWarnedAboutMaxListeners?: boolean;\n}\n\nexport class AsyncEventEmitter = Record & AsyncEventEmitterPredefinedEvents> {\n\tprivate _events: Record = {\n\t\t__proto__: null\n\t} as Record;\n\n\tprivate _eventCount = 0;\n\tprivate _maxListeners = 10;\n\tprivate _internalPromiseMap: Map> = new Map();\n\tprivate _wrapperId = 0n;\n\n\tpublic addListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, false);\n\n\t\tthis._addListener(eventName, wrapped, false);\n\n\t\treturn this;\n\t}\n\n\tpublic on(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\treturn this.addListener(eventName, listener);\n\t}\n\n\tpublic once(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, true);\n\n\t\tthis._addListener(eventName, wrapped, false);\n\n\t\treturn this;\n\t}\n\n\tpublic removeListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst events = this._events;\n\t\tconst eventList = events[eventName];\n\n\t\tif (eventList === undefined) {\n\t\t\treturn this;\n\t\t}\n\n\t\tif (eventList === listener || (eventList as WrappedOnce).listener === listener) {\n\t\t\tif (--this._eventCount === 0) {\n\t\t\t\tthis._events = { __proto__: null } as Record<\n\t\t\t\t\tkeyof Events | keyof AsyncEventEmitterPredefinedEvents,\n\t\t\t\t\tListener | WrappedOnce | InternalEventMap\n\t\t\t\t>;\n\t\t\t} else {\n\t\t\t\tdelete events[eventName];\n\t\t\t\tif (events.removeListener) {\n\t\t\t\t\tthis.emit('removeListener', eventName as string, (eventList as WrappedOnce).listener ?? eventList);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (typeof eventList !== 'function') {\n\t\t\tlet position = -1;\n\n\t\t\tfor (let i = eventList.length - 1; i >= 0; i--) {\n\t\t\t\tif (eventList[i] === listener || (eventList[i] as WrappedOnce).listener === listener) {\n\t\t\t\t\tposition = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (position < 0) {\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tif (position === 0) {\n\t\t\t\teventList.shift();\n\t\t\t} else {\n\t\t\t\tspliceOne(eventList, position);\n\t\t\t}\n\n\t\t\tif (eventList.length === 0) {\n\t\t\t\tdelete events[eventName];\n\t\t\t\t--this._eventCount;\n\t\t\t}\n\n\t\t\tif (events.removeListener !== undefined) {\n\t\t\t\t// Thanks TypeScript for the cast...\n\t\t\t\tthis.emit('removeListener', eventName as string | symbol, listener);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic off(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\treturn this.removeListener(eventName, listener);\n\t}\n\n\tpublic removeAllListeners(event?: K | undefined): this {\n\t\tconst events = this._events;\n\n\t\t// Not listening for removeListener, no need to emit\n\t\tif (events.removeListener === undefined) {\n\t\t\tif (!event) {\n\t\t\t\tthis._events = { __proto__: null } as Record;\n\t\t\t\tthis._eventCount = 0;\n\t\t\t} else if (events[event] !== undefined) {\n\t\t\t\tif (--this._eventCount === 0) {\n\t\t\t\t\tthis._events = { __proto__: null } as Record;\n\t\t\t\t} else {\n\t\t\t\t\tdelete events[event];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this;\n\t\t}\n\n\t\t// Emit removeListener for all listeners on all events\n\t\tif (!event) {\n\t\t\tfor (const key of Reflect.ownKeys(events)) {\n\t\t\t\tif (key === 'removeListener') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis.removeAllListeners(key);\n\t\t\t}\n\n\t\t\tthis.removeAllListeners('removeListener');\n\t\t\tthis._events = { __proto__: null } as Record;\n\t\t\tthis._eventCount = 0;\n\n\t\t\treturn this;\n\t\t}\n\n\t\tconst listeners = events[event];\n\n\t\tif (typeof listeners === 'function') {\n\t\t\tthis.removeListener(event, listeners);\n\t\t} else if (listeners !== undefined) {\n\t\t\t// LIFO order\n\t\t\tfor (let i = listeners.length - 1; i >= 0; i--) {\n\t\t\t\tthis.removeListener(event, listeners[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic setMaxListeners(n: number): this {\n\t\tif (typeof n !== 'number' || n < 0 || Number.isNaN(n)) {\n\t\t\tthrow new RangeError(`Expected to get a non-negative number for \"setMaxListeners\", got ${n} instead`);\n\t\t}\n\n\t\tthis._maxListeners = n;\n\n\t\treturn this;\n\t}\n\n\tpublic getMaxListeners(): number {\n\t\treturn this._maxListeners;\n\t}\n\n\tpublic listeners(eventName: K): Listener['listener'][] {\n\t\tconst eventList = this._events[eventName];\n\n\t\tif (eventList === undefined) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (typeof eventList === 'function') {\n\t\t\treturn [eventList.listener ?? eventList];\n\t\t}\n\n\t\tconst ret = arrayClone(eventList) as Listener['listener'][];\n\n\t\tfor (let i = 0; i < ret.length; ++i) {\n\t\t\tconst orig = (ret[i] as WrappedOnce).listener;\n\t\t\tif (typeof orig === 'function') {\n\t\t\t\tret[i] = orig;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic rawListeners(eventName: K): Listener[] {\n\t\tconst eventList = this._events[eventName];\n\n\t\tif (eventList === undefined) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (typeof eventList === 'function') {\n\t\t\treturn [eventList];\n\t\t}\n\n\t\treturn arrayClone(eventList) as Listener[];\n\t}\n\n\tpublic emit(\n\t\teventName: K,\n\t\t...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]\n\t): boolean {\n\t\tlet doError = eventName === 'error';\n\n\t\tconst events = this._events;\n\t\tif (events !== undefined) {\n\t\t\tdoError = doError && events.error === undefined;\n\t\t} else if (!doError) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (doError) {\n\t\t\tlet er: unknown;\n\n\t\t\tif (args.length > 0) {\n\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\ter = args[0];\n\t\t\t}\n\n\t\t\tif (er instanceof Error) {\n\t\t\t\ttry {\n\t\t\t\t\tconst capture = {};\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\t\t\t\t\tError.captureStackTrace(capture, AsyncEventEmitter.prototype.emit);\n\t\t\t\t\tObject.defineProperty(er, 'stack', {\n\t\t\t\t\t\tvalue: enhanceStackTrace.call(this, er, capture as Error),\n\t\t\t\t\t\tconfigurable: true\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// Continue regardless of error\n\t\t\t\t}\n\n\t\t\t\tthrow er; // Unhandled 'error' event\n\t\t\t}\n\n\t\t\tconst stringifiedError = String(er);\n\n\t\t\t// Give some error to user\n\t\t\tconst err = new Error(`Unhandled 'error' event emitted, received ${stringifiedError}`);\n\t\t\t// @ts-expect-error Add context to error too\n\t\t\terr.context = er;\n\n\t\t\tthrow err; // Unhandled 'error' event\n\t\t}\n\n\t\tconst handlers = events[eventName];\n\n\t\tif (handlers === undefined) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (typeof handlers === 'function') {\n\t\t\tconst result = handlers.apply(this, args);\n\n\t\t\tif (result !== undefined && result !== null) {\n\t\t\t\thandleMaybeAsync(this, result);\n\t\t\t}\n\t\t} else {\n\t\t\tconst len = handlers.length;\n\t\t\tconst listeners = arrayClone(handlers as InternalEventMap);\n\n\t\t\tfor (let i = 0; i < len; ++i) {\n\t\t\t\t// We call all listeners regardless of the result, as we already handle possible error emits in the wrapped func\n\t\t\t\tconst result = listeners[i].apply(this, args);\n\n\t\t\t\tif (result !== undefined && result !== null) {\n\t\t\t\t\thandleMaybeAsync(this, result);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic listenerCount(eventName: K): number {\n\t\tconst events = this._events;\n\n\t\tif (events === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst eventListeners = events[eventName];\n\n\t\tif (typeof eventListeners === 'function') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn eventListeners?.length ?? 0;\n\t}\n\n\tpublic prependListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, false);\n\n\t\tthis._addListener(eventName, wrapped, true);\n\n\t\treturn this;\n\t}\n\n\tpublic prependOnceListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, true);\n\n\t\tthis._addListener(eventName, wrapped, true);\n\n\t\treturn this;\n\t}\n\n\tpublic eventNames(): (keyof Events | keyof AsyncEventEmitterPredefinedEvents)[] {\n\t\treturn this._eventCount > 0 ? Reflect.ownKeys(this._events) : [];\n\t}\n\n\tpublic async waitForAllListenersToComplete() {\n\t\tconst promises = [...this._internalPromiseMap.values()];\n\n\t\tif (promises.length === 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tawait Promise.all(promises);\n\n\t\treturn true;\n\t}\n\n\tprivate _addListener(\n\t\teventName: K,\n\t\twrappedListener: Listener | WrappedOnce,\n\t\tprepend: boolean\n\t) {\n\t\t// Emit newListener first in the event someone is listening for it\n\t\tif (this._events.newListener !== undefined) {\n\t\t\t// Thanks TypeScript for the cast...\n\t\t\tthis.emit('newListener', eventName as string | symbol, (wrappedListener as WrappedOnce).listener ?? wrappedListener);\n\t\t}\n\n\t\tlet existing = this._events[eventName];\n\n\t\tif (existing === undefined) {\n\t\t\t// eslint-disable-next-line no-multi-assign\n\t\t\texisting = this._events[eventName] = wrappedListener;\n\t\t\t++this._eventCount;\n\t\t} else if (typeof existing === 'function') {\n\t\t\t// Adding the second element, need to change to array.\n\t\t\t// eslint-disable-next-line no-multi-assign\n\t\t\texisting = this._events[eventName] = prepend ? [wrappedListener, existing] : [existing, wrappedListener];\n\t\t\t// If we've already got an array, just append.\n\t\t} else if (prepend) {\n\t\t\texisting.unshift(wrappedListener);\n\t\t} else {\n\t\t\texisting.push(wrappedListener);\n\t\t}\n\n\t\tif (this._maxListeners > 0 && existing.length > this._maxListeners && !existing._hasWarnedAboutMaxListeners) {\n\t\t\texisting._hasWarnedAboutMaxListeners = true;\n\t\t\tconst warningMessage = [\n\t\t\t\t`Possible AsyncEventEmitter memory leak detected. ${existing.length} ${String(eventName)} listeners added to ${\n\t\t\t\t\tthis.constructor.name\n\t\t\t\t}.`,\n\t\t\t\t`Use emitter.setMaxListeners() to increase the limit.`\n\t\t\t].join(' ');\n\t\t\tconsole.warn(warningMessage);\n\t\t}\n\t}\n\n\tprivate _wrapListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => Awaitable,\n\t\tonce: boolean\n\t): Listener | WrappedOnce {\n\t\tif (!once) {\n\t\t\treturn listener as Listener;\n\t\t}\n\n\t\tconst state = {\n\t\t\tfired: false,\n\t\t\twrapFn: undefined!,\n\t\t\teventEmitter: this,\n\t\t\teventName,\n\t\t\tlistener\n\t\t} as WrappedOnceState;\n\n\t\tconst aliased = onceWrapper;\n\n\t\tconst wrapped = aliased.bind(state) as WrappedOnce<\n\t\t\tK extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]\n\t\t>;\n\t\twrapped.listener = listener;\n\t\tstate.wrapFn = wrapped;\n\n\t\treturn wrapped as WrappedOnce;\n\t}\n\n\tpublic static listenerCount<\n\t\tEmitter extends AsyncEventEmitter,\n\t\tEventNames = Emitter extends AsyncEventEmitter ? Events : never,\n\t\tEventName extends PropertyKey = EventNames extends never ? string | symbol : keyof EventNames\n\t>(emitter: Emitter, eventName: EventName | keyof AsyncEventEmitterPredefinedEvents) {\n\t\treturn emitter.listenerCount(eventName);\n\t}\n\n\tpublic static async once<\n\t\tEmitter extends AsyncEventEmitter,\n\t\tEventNames extends Record = Emitter extends AsyncEventEmitter ? Events : Record,\n\t\tEventName extends PropertyKey = keyof EventNames | keyof AsyncEventEmitterPredefinedEvents,\n\t\tEventResult extends unknown[] = EventName extends keyof AsyncEventEmitterPredefinedEvents\n\t\t\t? AsyncEventEmitterPredefinedEvents[EventName]\n\t\t\t: EventNames[EventName]\n\t>(emitter: Emitter, eventName: EventName, options: AbortableMethods = {}) {\n\t\tconst signal = options?.signal;\n\t\tvalidateAbortSignal(signal);\n\n\t\tif (signal?.aborted) {\n\t\t\tthrow new AbortError(undefined, { cause: getReason(signal) });\n\t\t}\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst errorListener = (err: unknown) => {\n\t\t\t\temitter.removeListener(eventName, resolver);\n\n\t\t\t\tif (signal) {\n\t\t\t\t\teventTargetAgnosticRemoveListener(emitter, eventName, abortListener);\n\t\t\t\t}\n\n\t\t\t\treject(err);\n\t\t\t};\n\n\t\t\tconst resolver = (...args: unknown[]) => {\n\t\t\t\temitter.removeListener('error', errorListener);\n\n\t\t\t\tif (signal) {\n\t\t\t\t\teventTargetAgnosticRemoveListener(signal, 'abort', abortListener);\n\t\t\t\t}\n\n\t\t\t\tresolve(args as EventResult);\n\t\t\t};\n\n\t\t\temitter.once(eventName, resolver);\n\t\t\tif (eventName !== 'error') {\n\t\t\t\temitter.once('error', errorListener);\n\t\t\t}\n\n\t\t\tconst abortListener = () => {\n\t\t\t\teventTargetAgnosticRemoveListener(emitter, eventName, resolver);\n\t\t\t\teventTargetAgnosticRemoveListener(emitter, 'error', errorListener);\n\t\t\t\treject(new AbortError(undefined, { cause: getReason(signal) }));\n\t\t\t};\n\n\t\t\tif (signal) {\n\t\t\t\teventTargetAgnosticAddListener(signal, 'abort', abortListener, { once: true });\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static on<\n\t\tEmitter extends AsyncEventEmitter,\n\t\tEventNames extends Record = Emitter extends AsyncEventEmitter ? Events : Record,\n\t\tEventName extends PropertyKey = keyof EventNames | keyof AsyncEventEmitterPredefinedEvents,\n\t\tEventResult extends unknown[] = EventName extends keyof AsyncEventEmitterPredefinedEvents\n\t\t\t? AsyncEventEmitterPredefinedEvents[EventName]\n\t\t\t: EventNames[EventName]\n\t>(emitter: Emitter, eventName: EventName, options: AbortableMethods = {}): AsyncGenerator {\n\t\tconst signal = options?.signal;\n\t\tvalidateAbortSignal(signal);\n\n\t\tif (signal?.aborted) {\n\t\t\tthrow new AbortError(undefined, { cause: getReason(signal) });\n\t\t}\n\n\t\tconst unconsumedEvents: unknown[][] = [];\n\t\tconst unconsumedPromises: { resolve: (value?: unknown) => void; reject: (reason?: unknown) => void }[] = [];\n\t\tlet error: unknown = null;\n\t\tlet finished = false;\n\n\t\tconst abortListener = () => {\n\t\t\terrorHandler(new AbortError(undefined, { cause: getReason(signal) }));\n\t\t};\n\n\t\tconst eventHandler = (...args: unknown[]) => {\n\t\t\tconst promise = unconsumedPromises.shift();\n\t\t\tif (promise) {\n\t\t\t\tpromise.resolve(createIterResult(args, false));\n\t\t\t} else {\n\t\t\t\tunconsumedEvents.push(args);\n\t\t\t}\n\t\t};\n\n\t\tconst errorHandler = (err: unknown) => {\n\t\t\tfinished = true;\n\n\t\t\tconst toError = unconsumedPromises.shift();\n\n\t\t\tif (toError) {\n\t\t\t\ttoError.reject(err);\n\t\t\t} else {\n\t\t\t\terror = err;\n\t\t\t}\n\n\t\t\tvoid iterator.return();\n\t\t};\n\n\t\tconst iterator: AsyncGenerator = Object.setPrototypeOf(\n\t\t\t{\n\t\t\t\tnext() {\n\t\t\t\t\t// First, we consume all unread events\n\t\t\t\t\tconst value = unconsumedEvents.shift();\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\treturn Promise.resolve(createIterResult(value, false));\n\t\t\t\t\t}\n\n\t\t\t\t\t// Then we error, if an error happened\n\t\t\t\t\t// This happens one time if at all, because after 'error'\n\t\t\t\t\t// we stop listening\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tconst p = Promise.reject(error);\n\t\t\t\t\t\t// Only the first element errors\n\t\t\t\t\t\terror = null;\n\t\t\t\t\t\treturn p;\n\t\t\t\t\t}\n\n\t\t\t\t\t// If the iterator is finished, resolve to done\n\t\t\t\t\tif (finished) {\n\t\t\t\t\t\treturn Promise.resolve(createIterResult(undefined, true));\n\t\t\t\t\t}\n\n\t\t\t\t\t// Wait until an event happens\n\t\t\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\t\t\tunconsumedPromises.push({ resolve, reject });\n\t\t\t\t\t});\n\t\t\t\t},\n\n\t\t\t\treturn() {\n\t\t\t\t\temitter.off(eventName, eventHandler);\n\t\t\t\t\temitter.off('error', errorHandler);\n\n\t\t\t\t\tif (signal) {\n\t\t\t\t\t\teventTargetAgnosticRemoveListener(signal, 'abort', abortListener);\n\t\t\t\t\t}\n\n\t\t\t\t\tfinished = true;\n\n\t\t\t\t\tconst doneResult = createIterResult(undefined, true);\n\t\t\t\t\tfor (const promise of unconsumedPromises) {\n\t\t\t\t\t\tpromise.resolve(doneResult);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Promise.resolve(doneResult);\n\t\t\t\t},\n\n\t\t\t\tthrow(err: unknown) {\n\t\t\t\t\tif (!err || !(err instanceof Error)) {\n\t\t\t\t\t\tthrow new TypeError(`Expected Error instance to be thrown in AsyncEventEmitter.AsyncIterator. Got ${err}`);\n\t\t\t\t\t}\n\n\t\t\t\t\terror = err;\n\t\t\t\t\temitter.off(eventName, eventHandler);\n\t\t\t\t\temitter.off('error', errorHandler);\n\t\t\t\t},\n\n\t\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\t\treturn this;\n\t\t\t\t}\n\t\t\t},\n\t\t\tAsyncIteratorPrototype\n\t\t);\n\n\t\temitter.on(eventName, eventHandler);\n\t\tif (eventName !== 'error') {\n\t\t\temitter.on('error', errorHandler);\n\t\t}\n\n\t\tif (signal) {\n\t\t\teventTargetAgnosticAddListener(signal, 'abort', abortListener);\n\t\t}\n\n\t\treturn iterator;\n\t}\n}\n\nexport interface AsyncEventEmitterPredefinedEvents {\n\tnewListener: [eventName: string | symbol, listener: (...args: any[]) => Awaitable];\n\tremoveListener: [eventName: string | symbol, listener: (...args: any[]) => Awaitable];\n}\n\ninterface WrappedOnceState {\n\tlistener: (...args: Args) => Awaitable;\n\tfired: boolean;\n\teventName: string | symbol;\n\teventEmitter: AsyncEventEmitter;\n\twrapFn: (...args: Args) => Awaitable;\n}\n\nexport interface WrappedOnce {\n\t(...args: Args): Awaitable;\n\tlistener: (...args: Args) => Awaitable;\n\t_hasWarnedAboutMaxListeners?: boolean;\n}\n\nexport interface Listener {\n\t(...args: Args): Awaitable;\n\tlistener: (...args: Args) => Awaitable;\n\t_hasWarnedAboutMaxListeners?: boolean;\n}\n\nexport type Awaitable = T | Promise;\n\nexport interface AbortableMethods {\n\tsignal?: AbortSignal;\n}\n\n// @ts-ignore Not all paths returning is fine just fine:tm:\nfunction onceWrapper(this: WrappedOnceState) {\n\tif (!this.fired) {\n\t\tthis.eventEmitter.removeListener(this.eventName, this.wrapFn);\n\t\tthis.fired = true;\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tif (arguments.length === 0) {\n\t\t\t// @ts-expect-error Types can be hell\n\t\t\treturn this.listener.call(this.eventEmitter);\n\t\t}\n\n\t\t// eslint-disable-next-line prefer-rest-params\n\t\treturn this.listener.apply(this.eventEmitter, arguments as unknown as Args);\n\t}\n}\n\n/**\n * A TypeScript not-compliant way of accessing AbortSignal#reason\n * Because DOM types have it, NodeJS types don't. -w-\n */\nfunction getReason(signal: any) {\n\treturn signal?.reason;\n}\n\nfunction eventTargetAgnosticRemoveListener(emitter: any, name: PropertyKey, listener: (...args: unknown[]) => any, flags?: InternalAgnosticFlags) {\n\tif (typeof emitter.off === 'function') {\n\t\temitter.off(name, listener);\n\t} else if (typeof emitter.removeEventListener === 'function') {\n\t\temitter.removeEventListener(name, listener, flags);\n\t}\n}\n\nfunction eventTargetAgnosticAddListener(emitter: any, name: string | symbol, listener: (...args: unknown[]) => any, flags?: InternalAgnosticFlags) {\n\tif (typeof emitter.on === 'function') {\n\t\tif (flags?.once) {\n\t\t\temitter.once!(name, listener);\n\t\t} else {\n\t\t\temitter.on(name, listener);\n\t\t}\n\t} else if (typeof emitter.addEventListener === 'function') {\n\t\temitter.addEventListener(name, listener, flags);\n\t}\n}\n\ninterface InternalAgnosticFlags {\n\tonce?: boolean;\n}\n\n// eslint-disable-next-line func-names, @typescript-eslint/no-empty-function\nconst AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype);\n\nfunction createIterResult(value: unknown, done: boolean) {\n\treturn { value, done };\n}\n\nexport interface AbortErrorOptions {\n\tcause?: unknown;\n}\n\nexport class AbortError extends Error {\n\tpublic readonly code = 'ABORT_ERR';\n\tpublic override readonly name = 'AbortError';\n\n\tpublic constructor(message = 'The operation was aborted', options: AbortErrorOptions | undefined = undefined) {\n\t\tif (options !== undefined && typeof options !== 'object') {\n\t\t\tthrow new TypeError(`Failed to create AbortError: options is not an object or undefined`);\n\t\t}\n\n\t\tsuper(message, options);\n\t}\n}\n\nfunction handleMaybeAsync(emitter: AsyncEventEmitter, result: any) {\n\ttry {\n\t\tconst fin = result.finally;\n\n\t\tif (typeof fin === 'function') {\n\t\t\tconst promiseId = String(++emitter['_wrapperId']);\n\t\t\temitter['_internalPromiseMap'].set(promiseId, result);\n\t\t\tfin.call(result, function final() {\n\t\t\t\temitter['_internalPromiseMap'].delete(promiseId);\n\t\t\t});\n\t\t}\n\t} catch (err) {\n\t\temitter.emit('error', err);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,WAAS,iBAAiB,OAA0E;AACnG,QAAI,OAAO,UAAU,YAAY;AAChC,YAAM,IAAI,UAAU,sDAAsD,OAAO,OAAO;AAAA,IACzF;AAAA,EACD;AAJS;AAMT,WAAS,oBAAoB,OAA0D;AAEtF,QAAI,SAAS,EAAE,iBAAiB,cAAc;AAC7C,YAAM,IAAI,UAAU,sDAAsD,OAAO;AAAA,IAClF;AAAA,EACD;AALS;AAQT,WAAS,UAAU,MAAiB,OAAe;AAClD,WAAO,QAAQ,IAAI,KAAK,QAAQ,SAAS;AACxC,WAAK,KAAK,IAAI,KAAK,QAAQ,CAAC;AAAA,IAC7B;AAEA,SAAK,IAAI;AAAA,EACV;AANS;AAST,WAAS,WAAgC,KAAW;AAGnD,YAAQ,IAAI,QAAQ;AAAA,MACnB,KAAK;AACJ,eAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AAAA,MACvB,KAAK;AACJ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Ae,mBAAmB;AAAA,EAAC,CAAC,EAAE,SAAS;AAE3G,WAAS,iBAAiB,OAAgB,MAAe;AACxD,WAAO,EAAE,OAAO,KAAK;AAAA,EACtB;AAFS;AAQF,MAAM,aAAN,cAAyB,MAAM;AAAA,IAI9B,YAAY,UAAU,6BAA6B,UAAyC,QAAW;AAC7G,UAAI,YAAY,UAAa,OAAO,YAAY,UAAU;AACzD,cAAM,IAAI,UAAU,oEAAoE;AAAA,MACzF;AAEA,YAAM,SAAS,OAAO;AARvB,WAAgB,OAAO;AACvB,WAAyB,OAAO;AAAA,IAQhC;AAAA,EACD;AAXa;AAab,WAAS,iBAAiB,SAAiC,QAAa;AACvE,QAAI;AACH,YAAM,MAAM,OAAO;AAEnB,UAAI,OAAO,QAAQ,YAAY;AAC9B,cAAM,YAAY,OAAO,EAAE,QAAQ,YAAY,CAAC;AAChD,gBAAQ,qBAAqB,EAAE,IAAI,WAAW,MAAM;AACpD,YAAI,KAAK,QAAQ,gCAAS,QAAQ;AACjC,kBAAQ,qBAAqB,EAAE,OAAO,SAAS;AAAA,QAChD,GAFiB,QAEhB;AAAA,MACF;AAAA,IACD,SAAS,KAAP;AACD,cAAQ,KAAK,SAAS,GAAG;AAAA,IAC1B;AAAA,EACD;AAdS;","names":[]} \ No newline at end of file diff --git a/node_modules/@vladfrangu/async_event_emitter/dist/index.js b/node_modules/@vladfrangu/async_event_emitter/dist/index.js new file mode 100644 index 0000000..c542899 --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/dist/index.js @@ -0,0 +1,571 @@ +"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, { + AbortError: () => AbortError, + AsyncEventEmitter: () => AsyncEventEmitter +}); +module.exports = __toCommonJS(src_exports); +function validateListener(input) { + if (typeof input !== "function") { + throw new TypeError(`The listener argument must be a function. Received ${typeof input}`); + } +} +__name(validateListener, "validateListener"); +function validateAbortSignal(input) { + if (input && !(input instanceof AbortSignal)) { + throw new TypeError(`The signal option must be an AbortSignal. Received ${input}`); + } +} +__name(validateAbortSignal, "validateAbortSignal"); +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) { + list[index] = list[index + 1]; + } + list.pop(); +} +__name(spliceOne, "spliceOne"); +function arrayClone(arr) { + switch (arr.length) { + case 2: + return [arr[0], arr[1]]; + case 3: + return [arr[0], arr[1], arr[2]]; + case 4: + return [arr[0], arr[1], arr[2], arr[3]]; + case 5: + return [arr[0], arr[1], arr[2], arr[3], arr[4]]; + case 6: + return [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]]; + } + return arr.slice(); +} +__name(arrayClone, "arrayClone"); +function identicalSequenceRange(a, b) { + for (let i = 0; i < a.length - 3; i++) { + const pos = b.indexOf(a[i]); + if (pos !== -1) { + const rest = b.length - pos; + if (rest > 3) { + let len = 1; + const maxLen = Math.min(a.length - i, rest); + while (maxLen > len && a[i + len] === b[pos + len]) { + len++; + } + if (len > 3) { + return [len, i]; + } + } + } + } + return [0, 0]; +} +__name(identicalSequenceRange, "identicalSequenceRange"); +function enhanceStackTrace(err, own) { + let ctorInfo = ""; + try { + const { name } = this.constructor; + if (name !== "AsyncEventEmitter") + ctorInfo = ` on ${name} instance`; + } catch { + } + const sep = ` +Emitted 'error' event${ctorInfo} at: +`; + const errStack = err.stack.split("\n").slice(1); + const ownStack = own.stack.split("\n").slice(1); + const { 0: len, 1: off } = identicalSequenceRange(ownStack, errStack); + if (len > 0) { + ownStack.splice(off + 1, len - 2, " [... lines matching original stack trace ...]"); + } + return err.stack + sep + ownStack.join("\n"); +} +__name(enhanceStackTrace, "enhanceStackTrace"); +var AsyncEventEmitter = class { + constructor() { + this._events = { + __proto__: null + }; + this._eventCount = 0; + this._maxListeners = 10; + this._internalPromiseMap = /* @__PURE__ */ new Map(); + this._wrapperId = 0n; + } + addListener(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, false); + this._addListener(eventName, wrapped, false); + return this; + } + on(eventName, listener) { + return this.addListener(eventName, listener); + } + once(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, true); + this._addListener(eventName, wrapped, false); + return this; + } + removeListener(eventName, listener) { + validateListener(listener); + const events = this._events; + const eventList = events[eventName]; + if (eventList === void 0) { + return this; + } + if (eventList === listener || eventList.listener === listener) { + if (--this._eventCount === 0) { + this._events = { __proto__: null }; + } else { + delete events[eventName]; + if (events.removeListener) { + this.emit("removeListener", eventName, eventList.listener ?? eventList); + } + } + } else if (typeof eventList !== "function") { + let position = -1; + for (let i = eventList.length - 1; i >= 0; i--) { + if (eventList[i] === listener || eventList[i].listener === listener) { + position = i; + break; + } + } + if (position < 0) { + return this; + } + if (position === 0) { + eventList.shift(); + } else { + spliceOne(eventList, position); + } + if (eventList.length === 0) { + delete events[eventName]; + --this._eventCount; + } + if (events.removeListener !== void 0) { + this.emit("removeListener", eventName, listener); + } + } + return this; + } + off(eventName, listener) { + return this.removeListener(eventName, listener); + } + removeAllListeners(event) { + const events = this._events; + if (events.removeListener === void 0) { + if (!event) { + this._events = { __proto__: null }; + this._eventCount = 0; + } else if (events[event] !== void 0) { + if (--this._eventCount === 0) { + this._events = { __proto__: null }; + } else { + delete events[event]; + } + } + return this; + } + if (!event) { + for (const key of Reflect.ownKeys(events)) { + if (key === "removeListener") { + continue; + } + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = { __proto__: null }; + this._eventCount = 0; + return this; + } + const listeners = events[event]; + if (typeof listeners === "function") { + this.removeListener(event, listeners); + } else if (listeners !== void 0) { + for (let i = listeners.length - 1; i >= 0; i--) { + this.removeListener(event, listeners[i]); + } + } + return this; + } + setMaxListeners(n) { + if (typeof n !== "number" || n < 0 || Number.isNaN(n)) { + throw new RangeError(`Expected to get a non-negative number for "setMaxListeners", got ${n} instead`); + } + this._maxListeners = n; + return this; + } + getMaxListeners() { + return this._maxListeners; + } + listeners(eventName) { + const eventList = this._events[eventName]; + if (eventList === void 0) { + return []; + } + if (typeof eventList === "function") { + return [eventList.listener ?? eventList]; + } + const ret = arrayClone(eventList); + for (let i = 0; i < ret.length; ++i) { + const orig = ret[i].listener; + if (typeof orig === "function") { + ret[i] = orig; + } + } + return ret; + } + rawListeners(eventName) { + const eventList = this._events[eventName]; + if (eventList === void 0) { + return []; + } + if (typeof eventList === "function") { + return [eventList]; + } + return arrayClone(eventList); + } + emit(eventName, ...args) { + let doError = eventName === "error"; + const events = this._events; + if (events !== void 0) { + doError = doError && events.error === void 0; + } else if (!doError) { + return false; + } + if (doError) { + let er; + if (args.length > 0) { + er = args[0]; + } + if (er instanceof Error) { + try { + const capture = {}; + Error.captureStackTrace(capture, AsyncEventEmitter.prototype.emit); + Object.defineProperty(er, "stack", { + value: enhanceStackTrace.call(this, er, capture), + configurable: true + }); + } catch { + } + throw er; // Unhandled 'error' event + } + const stringifiedError = String(er); + const err = new Error(`Unhandled 'error' event emitted, received ${stringifiedError}`); + err.context = er; + throw err; // Unhandled 'error' event + } + const handlers = events[eventName]; + if (handlers === void 0) { + return false; + } + if (typeof handlers === "function") { + const result = handlers.apply(this, args); + if (result !== void 0 && result !== null) { + handleMaybeAsync(this, result); + } + } else { + const len = handlers.length; + const listeners = arrayClone(handlers); + for (let i = 0; i < len; ++i) { + const result = listeners[i].apply(this, args); + if (result !== void 0 && result !== null) { + handleMaybeAsync(this, result); + } + } + } + return true; + } + listenerCount(eventName) { + const events = this._events; + if (events === void 0) { + return 0; + } + const eventListeners = events[eventName]; + if (typeof eventListeners === "function") { + return 1; + } + return eventListeners?.length ?? 0; + } + prependListener(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, false); + this._addListener(eventName, wrapped, true); + return this; + } + prependOnceListener(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, true); + this._addListener(eventName, wrapped, true); + return this; + } + eventNames() { + return this._eventCount > 0 ? Reflect.ownKeys(this._events) : []; + } + async waitForAllListenersToComplete() { + const promises = [...this._internalPromiseMap.values()]; + if (promises.length === 0) { + return false; + } + await Promise.all(promises); + return true; + } + _addListener(eventName, wrappedListener, prepend) { + if (this._events.newListener !== void 0) { + this.emit("newListener", eventName, wrappedListener.listener ?? wrappedListener); + } + let existing = this._events[eventName]; + if (existing === void 0) { + existing = this._events[eventName] = wrappedListener; + ++this._eventCount; + } else if (typeof existing === "function") { + existing = this._events[eventName] = prepend ? [wrappedListener, existing] : [existing, wrappedListener]; + } else if (prepend) { + existing.unshift(wrappedListener); + } else { + existing.push(wrappedListener); + } + if (this._maxListeners > 0 && existing.length > this._maxListeners && !existing._hasWarnedAboutMaxListeners) { + existing._hasWarnedAboutMaxListeners = true; + const warningMessage = [ + `Possible AsyncEventEmitter memory leak detected. ${existing.length} ${String(eventName)} listeners added to ${this.constructor.name}.`, + `Use emitter.setMaxListeners() to increase the limit.` + ].join(" "); + console.warn(warningMessage); + } + } + _wrapListener(eventName, listener, once) { + if (!once) { + return listener; + } + const state = { + fired: false, + wrapFn: void 0, + eventEmitter: this, + eventName, + listener + }; + const aliased = onceWrapper; + const wrapped = aliased.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; + } + static listenerCount(emitter, eventName) { + return emitter.listenerCount(eventName); + } + static async once(emitter, eventName, options = {}) { + const signal = options?.signal; + validateAbortSignal(signal); + if (signal?.aborted) { + throw new AbortError(void 0, { cause: getReason(signal) }); + } + return new Promise((resolve, reject) => { + const errorListener = /* @__PURE__ */ __name((err) => { + emitter.removeListener(eventName, resolver); + if (signal) { + eventTargetAgnosticRemoveListener(emitter, eventName, abortListener); + } + reject(err); + }, "errorListener"); + const resolver = /* @__PURE__ */ __name((...args) => { + emitter.removeListener("error", errorListener); + if (signal) { + eventTargetAgnosticRemoveListener(signal, "abort", abortListener); + } + resolve(args); + }, "resolver"); + emitter.once(eventName, resolver); + if (eventName !== "error") { + emitter.once("error", errorListener); + } + const abortListener = /* @__PURE__ */ __name(() => { + eventTargetAgnosticRemoveListener(emitter, eventName, resolver); + eventTargetAgnosticRemoveListener(emitter, "error", errorListener); + reject(new AbortError(void 0, { cause: getReason(signal) })); + }, "abortListener"); + if (signal) { + eventTargetAgnosticAddListener(signal, "abort", abortListener, { once: true }); + } + }); + } + static on(emitter, eventName, options = {}) { + const signal = options?.signal; + validateAbortSignal(signal); + if (signal?.aborted) { + throw new AbortError(void 0, { cause: getReason(signal) }); + } + const unconsumedEvents = []; + const unconsumedPromises = []; + let error = null; + let finished = false; + const abortListener = /* @__PURE__ */ __name(() => { + errorHandler(new AbortError(void 0, { cause: getReason(signal) })); + }, "abortListener"); + const eventHandler = /* @__PURE__ */ __name((...args) => { + const promise = unconsumedPromises.shift(); + if (promise) { + promise.resolve(createIterResult(args, false)); + } else { + unconsumedEvents.push(args); + } + }, "eventHandler"); + const errorHandler = /* @__PURE__ */ __name((err) => { + finished = true; + const toError = unconsumedPromises.shift(); + if (toError) { + toError.reject(err); + } else { + error = err; + } + void iterator.return(); + }, "errorHandler"); + const iterator = Object.setPrototypeOf( + { + next() { + const value = unconsumedEvents.shift(); + if (value) { + return Promise.resolve(createIterResult(value, false)); + } + if (error) { + const p = Promise.reject(error); + error = null; + return p; + } + if (finished) { + return Promise.resolve(createIterResult(void 0, true)); + } + return new Promise((resolve, reject) => { + unconsumedPromises.push({ resolve, reject }); + }); + }, + return() { + emitter.off(eventName, eventHandler); + emitter.off("error", errorHandler); + if (signal) { + eventTargetAgnosticRemoveListener(signal, "abort", abortListener); + } + finished = true; + const doneResult = createIterResult(void 0, true); + for (const promise of unconsumedPromises) { + promise.resolve(doneResult); + } + return Promise.resolve(doneResult); + }, + throw(err) { + if (!err || !(err instanceof Error)) { + throw new TypeError(`Expected Error instance to be thrown in AsyncEventEmitter.AsyncIterator. Got ${err}`); + } + error = err; + emitter.off(eventName, eventHandler); + emitter.off("error", errorHandler); + }, + [Symbol.asyncIterator]() { + return this; + } + }, + AsyncIteratorPrototype + ); + emitter.on(eventName, eventHandler); + if (eventName !== "error") { + emitter.on("error", errorHandler); + } + if (signal) { + eventTargetAgnosticAddListener(signal, "abort", abortListener); + } + return iterator; + } +}; +__name(AsyncEventEmitter, "AsyncEventEmitter"); +function onceWrapper() { + if (!this.fired) { + this.eventEmitter.removeListener(this.eventName, this.wrapFn); + this.fired = true; + if (arguments.length === 0) { + return this.listener.call(this.eventEmitter); + } + return this.listener.apply(this.eventEmitter, arguments); + } +} +__name(onceWrapper, "onceWrapper"); +function getReason(signal) { + return signal?.reason; +} +__name(getReason, "getReason"); +function eventTargetAgnosticRemoveListener(emitter, name, listener, flags) { + if (typeof emitter.off === "function") { + emitter.off(name, listener); + } else if (typeof emitter.removeEventListener === "function") { + emitter.removeEventListener(name, listener, flags); + } +} +__name(eventTargetAgnosticRemoveListener, "eventTargetAgnosticRemoveListener"); +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === "function") { + if (flags?.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name, listener, flags); + } +} +__name(eventTargetAgnosticAddListener, "eventTargetAgnosticAddListener"); +var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { +}).prototype); +function createIterResult(value, done) { + return { value, done }; +} +__name(createIterResult, "createIterResult"); +var AbortError = class extends Error { + constructor(message = "The operation was aborted", options = void 0) { + if (options !== void 0 && typeof options !== "object") { + throw new TypeError(`Failed to create AbortError: options is not an object or undefined`); + } + super(message, options); + this.code = "ABORT_ERR"; + this.name = "AbortError"; + } +}; +__name(AbortError, "AbortError"); +function handleMaybeAsync(emitter, result) { + try { + const fin = result.finally; + if (typeof fin === "function") { + const promiseId = String(++emitter["_wrapperId"]); + emitter["_internalPromiseMap"].set(promiseId, result); + fin.call(result, /* @__PURE__ */ __name(function final() { + emitter["_internalPromiseMap"].delete(promiseId); + }, "final")); + } + } catch (err) { + emitter.emit("error", err); + } +} +__name(handleMaybeAsync, "handleMaybeAsync"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + AbortError, + AsyncEventEmitter +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@vladfrangu/async_event_emitter/dist/index.js.map b/node_modules/@vladfrangu/async_event_emitter/dist/index.js.map new file mode 100644 index 0000000..776cb0c --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/dot-notation */\nfunction validateListener(input: unknown): asserts input is (...args: unknown[]) => Awaitable {\n\tif (typeof input !== 'function') {\n\t\tthrow new TypeError(`The listener argument must be a function. Received ${typeof input}`);\n\t}\n}\n\nfunction validateAbortSignal(input: unknown): asserts input is AbortSignal | undefined {\n\t// Only validate that the signal is a signal if its defined\n\tif (input && !(input instanceof AbortSignal)) {\n\t\tthrow new TypeError(`The signal option must be an AbortSignal. Received ${input}`);\n\t}\n}\n\n// Inspired from https://github.com/nodejs/node/blob/42ad967d68137df1a80a877e7b5ad56403fc157f/lib/internal/util.js#L397\nfunction spliceOne(list: unknown[], index: number) {\n\tfor (; index + 1 < list.length; index++) {\n\t\tlist[index] = list[index + 1];\n\t}\n\n\tlist.pop();\n}\n\n// Inspired from https://github.com/nodejs/node/blob/42ad967d68137df1a80a877e7b5ad56403fc157f/lib/events.js#L889\nfunction arrayClone(arr: T): T {\n\t// At least since V8 8.3, this implementation is faster than the previous\n\t// which always used a simple for-loop\n\tswitch (arr.length) {\n\t\tcase 2:\n\t\t\treturn [arr[0], arr[1]] as T;\n\t\tcase 3:\n\t\t\treturn [arr[0], arr[1], arr[2]] as T;\n\t\tcase 4:\n\t\t\treturn [arr[0], arr[1], arr[2], arr[3]] as T;\n\t\tcase 5:\n\t\t\treturn [arr[0], arr[1], arr[2], arr[3], arr[4]] as T;\n\t\tcase 6:\n\t\t\treturn [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]] as T;\n\t}\n\n\treturn arr.slice() as T;\n}\n\n// Inspired from https://github.com/nodejs/node/blob/42ad967d68137df1a80a877e7b5ad56403fc157f/lib/events.js#L427-L475\nfunction identicalSequenceRange(a: unknown[], b: unknown[]): [number, number] {\n\tfor (let i = 0; i < a.length - 3; i++) {\n\t\t// Find the first entry of b that matches the current entry of a.\n\t\tconst pos = b.indexOf(a[i]);\n\t\tif (pos !== -1) {\n\t\t\tconst rest = b.length - pos;\n\t\t\tif (rest > 3) {\n\t\t\t\tlet len = 1;\n\t\t\t\tconst maxLen = Math.min(a.length - i, rest);\n\t\t\t\t// Count the number of consecutive entries.\n\t\t\t\twhile (maxLen > len && a[i + len] === b[pos + len]) {\n\t\t\t\t\tlen++;\n\t\t\t\t}\n\t\t\t\tif (len > 3) {\n\t\t\t\t\treturn [len, i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [0, 0];\n}\n\nfunction enhanceStackTrace(this: AsyncEventEmitter, err: Error, own: Error) {\n\tlet ctorInfo = '';\n\ttry {\n\t\tconst { name } = this.constructor;\n\t\tif (name !== 'AsyncEventEmitter') ctorInfo = ` on ${name} instance`;\n\t} catch {\n\t\t// Continue regardless of error.\n\t}\n\tconst sep = `\\nEmitted 'error' event${ctorInfo} at:\\n`;\n\n\tconst errStack = err.stack!.split('\\n').slice(1);\n\tconst ownStack = own.stack!.split('\\n').slice(1);\n\n\tconst { 0: len, 1: off } = identicalSequenceRange(ownStack, errStack);\n\tif (len > 0) {\n\t\townStack.splice(off + 1, len - 2, ' [... lines matching original stack trace ...]');\n\t}\n\n\treturn err.stack + sep + ownStack.join('\\n');\n}\n\ninterface InternalEventMap extends Array {\n\t_hasWarnedAboutMaxListeners?: boolean;\n}\n\nexport class AsyncEventEmitter = Record & AsyncEventEmitterPredefinedEvents> {\n\tprivate _events: Record = {\n\t\t__proto__: null\n\t} as Record;\n\n\tprivate _eventCount = 0;\n\tprivate _maxListeners = 10;\n\tprivate _internalPromiseMap: Map> = new Map();\n\tprivate _wrapperId = 0n;\n\n\tpublic addListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, false);\n\n\t\tthis._addListener(eventName, wrapped, false);\n\n\t\treturn this;\n\t}\n\n\tpublic on(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\treturn this.addListener(eventName, listener);\n\t}\n\n\tpublic once(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, true);\n\n\t\tthis._addListener(eventName, wrapped, false);\n\n\t\treturn this;\n\t}\n\n\tpublic removeListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst events = this._events;\n\t\tconst eventList = events[eventName];\n\n\t\tif (eventList === undefined) {\n\t\t\treturn this;\n\t\t}\n\n\t\tif (eventList === listener || (eventList as WrappedOnce).listener === listener) {\n\t\t\tif (--this._eventCount === 0) {\n\t\t\t\tthis._events = { __proto__: null } as Record<\n\t\t\t\t\tkeyof Events | keyof AsyncEventEmitterPredefinedEvents,\n\t\t\t\t\tListener | WrappedOnce | InternalEventMap\n\t\t\t\t>;\n\t\t\t} else {\n\t\t\t\tdelete events[eventName];\n\t\t\t\tif (events.removeListener) {\n\t\t\t\t\tthis.emit('removeListener', eventName as string, (eventList as WrappedOnce).listener ?? eventList);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (typeof eventList !== 'function') {\n\t\t\tlet position = -1;\n\n\t\t\tfor (let i = eventList.length - 1; i >= 0; i--) {\n\t\t\t\tif (eventList[i] === listener || (eventList[i] as WrappedOnce).listener === listener) {\n\t\t\t\t\tposition = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (position < 0) {\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tif (position === 0) {\n\t\t\t\teventList.shift();\n\t\t\t} else {\n\t\t\t\tspliceOne(eventList, position);\n\t\t\t}\n\n\t\t\tif (eventList.length === 0) {\n\t\t\t\tdelete events[eventName];\n\t\t\t\t--this._eventCount;\n\t\t\t}\n\n\t\t\tif (events.removeListener !== undefined) {\n\t\t\t\t// Thanks TypeScript for the cast...\n\t\t\t\tthis.emit('removeListener', eventName as string | symbol, listener);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic off(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\treturn this.removeListener(eventName, listener);\n\t}\n\n\tpublic removeAllListeners(event?: K | undefined): this {\n\t\tconst events = this._events;\n\n\t\t// Not listening for removeListener, no need to emit\n\t\tif (events.removeListener === undefined) {\n\t\t\tif (!event) {\n\t\t\t\tthis._events = { __proto__: null } as Record;\n\t\t\t\tthis._eventCount = 0;\n\t\t\t} else if (events[event] !== undefined) {\n\t\t\t\tif (--this._eventCount === 0) {\n\t\t\t\t\tthis._events = { __proto__: null } as Record;\n\t\t\t\t} else {\n\t\t\t\t\tdelete events[event];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this;\n\t\t}\n\n\t\t// Emit removeListener for all listeners on all events\n\t\tif (!event) {\n\t\t\tfor (const key of Reflect.ownKeys(events)) {\n\t\t\t\tif (key === 'removeListener') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis.removeAllListeners(key);\n\t\t\t}\n\n\t\t\tthis.removeAllListeners('removeListener');\n\t\t\tthis._events = { __proto__: null } as Record;\n\t\t\tthis._eventCount = 0;\n\n\t\t\treturn this;\n\t\t}\n\n\t\tconst listeners = events[event];\n\n\t\tif (typeof listeners === 'function') {\n\t\t\tthis.removeListener(event, listeners);\n\t\t} else if (listeners !== undefined) {\n\t\t\t// LIFO order\n\t\t\tfor (let i = listeners.length - 1; i >= 0; i--) {\n\t\t\t\tthis.removeListener(event, listeners[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic setMaxListeners(n: number): this {\n\t\tif (typeof n !== 'number' || n < 0 || Number.isNaN(n)) {\n\t\t\tthrow new RangeError(`Expected to get a non-negative number for \"setMaxListeners\", got ${n} instead`);\n\t\t}\n\n\t\tthis._maxListeners = n;\n\n\t\treturn this;\n\t}\n\n\tpublic getMaxListeners(): number {\n\t\treturn this._maxListeners;\n\t}\n\n\tpublic listeners(eventName: K): Listener['listener'][] {\n\t\tconst eventList = this._events[eventName];\n\n\t\tif (eventList === undefined) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (typeof eventList === 'function') {\n\t\t\treturn [eventList.listener ?? eventList];\n\t\t}\n\n\t\tconst ret = arrayClone(eventList) as Listener['listener'][];\n\n\t\tfor (let i = 0; i < ret.length; ++i) {\n\t\t\tconst orig = (ret[i] as WrappedOnce).listener;\n\t\t\tif (typeof orig === 'function') {\n\t\t\t\tret[i] = orig;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic rawListeners(eventName: K): Listener[] {\n\t\tconst eventList = this._events[eventName];\n\n\t\tif (eventList === undefined) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (typeof eventList === 'function') {\n\t\t\treturn [eventList];\n\t\t}\n\n\t\treturn arrayClone(eventList) as Listener[];\n\t}\n\n\tpublic emit(\n\t\teventName: K,\n\t\t...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]\n\t): boolean {\n\t\tlet doError = eventName === 'error';\n\n\t\tconst events = this._events;\n\t\tif (events !== undefined) {\n\t\t\tdoError = doError && events.error === undefined;\n\t\t} else if (!doError) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (doError) {\n\t\t\tlet er: unknown;\n\n\t\t\tif (args.length > 0) {\n\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\ter = args[0];\n\t\t\t}\n\n\t\t\tif (er instanceof Error) {\n\t\t\t\ttry {\n\t\t\t\t\tconst capture = {};\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\t\t\t\t\tError.captureStackTrace(capture, AsyncEventEmitter.prototype.emit);\n\t\t\t\t\tObject.defineProperty(er, 'stack', {\n\t\t\t\t\t\tvalue: enhanceStackTrace.call(this, er, capture as Error),\n\t\t\t\t\t\tconfigurable: true\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// Continue regardless of error\n\t\t\t\t}\n\n\t\t\t\tthrow er; // Unhandled 'error' event\n\t\t\t}\n\n\t\t\tconst stringifiedError = String(er);\n\n\t\t\t// Give some error to user\n\t\t\tconst err = new Error(`Unhandled 'error' event emitted, received ${stringifiedError}`);\n\t\t\t// @ts-expect-error Add context to error too\n\t\t\terr.context = er;\n\n\t\t\tthrow err; // Unhandled 'error' event\n\t\t}\n\n\t\tconst handlers = events[eventName];\n\n\t\tif (handlers === undefined) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (typeof handlers === 'function') {\n\t\t\tconst result = handlers.apply(this, args);\n\n\t\t\tif (result !== undefined && result !== null) {\n\t\t\t\thandleMaybeAsync(this, result);\n\t\t\t}\n\t\t} else {\n\t\t\tconst len = handlers.length;\n\t\t\tconst listeners = arrayClone(handlers as InternalEventMap);\n\n\t\t\tfor (let i = 0; i < len; ++i) {\n\t\t\t\t// We call all listeners regardless of the result, as we already handle possible error emits in the wrapped func\n\t\t\t\tconst result = listeners[i].apply(this, args);\n\n\t\t\t\tif (result !== undefined && result !== null) {\n\t\t\t\t\thandleMaybeAsync(this, result);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic listenerCount(eventName: K): number {\n\t\tconst events = this._events;\n\n\t\tif (events === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst eventListeners = events[eventName];\n\n\t\tif (typeof eventListeners === 'function') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn eventListeners?.length ?? 0;\n\t}\n\n\tpublic prependListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, false);\n\n\t\tthis._addListener(eventName, wrapped, true);\n\n\t\treturn this;\n\t}\n\n\tpublic prependOnceListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, true);\n\n\t\tthis._addListener(eventName, wrapped, true);\n\n\t\treturn this;\n\t}\n\n\tpublic eventNames(): (keyof Events | keyof AsyncEventEmitterPredefinedEvents)[] {\n\t\treturn this._eventCount > 0 ? Reflect.ownKeys(this._events) : [];\n\t}\n\n\tpublic async waitForAllListenersToComplete() {\n\t\tconst promises = [...this._internalPromiseMap.values()];\n\n\t\tif (promises.length === 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tawait Promise.all(promises);\n\n\t\treturn true;\n\t}\n\n\tprivate _addListener(\n\t\teventName: K,\n\t\twrappedListener: Listener | WrappedOnce,\n\t\tprepend: boolean\n\t) {\n\t\t// Emit newListener first in the event someone is listening for it\n\t\tif (this._events.newListener !== undefined) {\n\t\t\t// Thanks TypeScript for the cast...\n\t\t\tthis.emit('newListener', eventName as string | symbol, (wrappedListener as WrappedOnce).listener ?? wrappedListener);\n\t\t}\n\n\t\tlet existing = this._events[eventName];\n\n\t\tif (existing === undefined) {\n\t\t\t// eslint-disable-next-line no-multi-assign\n\t\t\texisting = this._events[eventName] = wrappedListener;\n\t\t\t++this._eventCount;\n\t\t} else if (typeof existing === 'function') {\n\t\t\t// Adding the second element, need to change to array.\n\t\t\t// eslint-disable-next-line no-multi-assign\n\t\t\texisting = this._events[eventName] = prepend ? [wrappedListener, existing] : [existing, wrappedListener];\n\t\t\t// If we've already got an array, just append.\n\t\t} else if (prepend) {\n\t\t\texisting.unshift(wrappedListener);\n\t\t} else {\n\t\t\texisting.push(wrappedListener);\n\t\t}\n\n\t\tif (this._maxListeners > 0 && existing.length > this._maxListeners && !existing._hasWarnedAboutMaxListeners) {\n\t\t\texisting._hasWarnedAboutMaxListeners = true;\n\t\t\tconst warningMessage = [\n\t\t\t\t`Possible AsyncEventEmitter memory leak detected. ${existing.length} ${String(eventName)} listeners added to ${\n\t\t\t\t\tthis.constructor.name\n\t\t\t\t}.`,\n\t\t\t\t`Use emitter.setMaxListeners() to increase the limit.`\n\t\t\t].join(' ');\n\t\t\tconsole.warn(warningMessage);\n\t\t}\n\t}\n\n\tprivate _wrapListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => Awaitable,\n\t\tonce: boolean\n\t): Listener | WrappedOnce {\n\t\tif (!once) {\n\t\t\treturn listener as Listener;\n\t\t}\n\n\t\tconst state = {\n\t\t\tfired: false,\n\t\t\twrapFn: undefined!,\n\t\t\teventEmitter: this,\n\t\t\teventName,\n\t\t\tlistener\n\t\t} as WrappedOnceState;\n\n\t\tconst aliased = onceWrapper;\n\n\t\tconst wrapped = aliased.bind(state) as WrappedOnce<\n\t\t\tK extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]\n\t\t>;\n\t\twrapped.listener = listener;\n\t\tstate.wrapFn = wrapped;\n\n\t\treturn wrapped as WrappedOnce;\n\t}\n\n\tpublic static listenerCount<\n\t\tEmitter extends AsyncEventEmitter,\n\t\tEventNames = Emitter extends AsyncEventEmitter ? Events : never,\n\t\tEventName extends PropertyKey = EventNames extends never ? string | symbol : keyof EventNames\n\t>(emitter: Emitter, eventName: EventName | keyof AsyncEventEmitterPredefinedEvents) {\n\t\treturn emitter.listenerCount(eventName);\n\t}\n\n\tpublic static async once<\n\t\tEmitter extends AsyncEventEmitter,\n\t\tEventNames extends Record = Emitter extends AsyncEventEmitter ? Events : Record,\n\t\tEventName extends PropertyKey = keyof EventNames | keyof AsyncEventEmitterPredefinedEvents,\n\t\tEventResult extends unknown[] = EventName extends keyof AsyncEventEmitterPredefinedEvents\n\t\t\t? AsyncEventEmitterPredefinedEvents[EventName]\n\t\t\t: EventNames[EventName]\n\t>(emitter: Emitter, eventName: EventName, options: AbortableMethods = {}) {\n\t\tconst signal = options?.signal;\n\t\tvalidateAbortSignal(signal);\n\n\t\tif (signal?.aborted) {\n\t\t\tthrow new AbortError(undefined, { cause: getReason(signal) });\n\t\t}\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst errorListener = (err: unknown) => {\n\t\t\t\temitter.removeListener(eventName, resolver);\n\n\t\t\t\tif (signal) {\n\t\t\t\t\teventTargetAgnosticRemoveListener(emitter, eventName, abortListener);\n\t\t\t\t}\n\n\t\t\t\treject(err);\n\t\t\t};\n\n\t\t\tconst resolver = (...args: unknown[]) => {\n\t\t\t\temitter.removeListener('error', errorListener);\n\n\t\t\t\tif (signal) {\n\t\t\t\t\teventTargetAgnosticRemoveListener(signal, 'abort', abortListener);\n\t\t\t\t}\n\n\t\t\t\tresolve(args as EventResult);\n\t\t\t};\n\n\t\t\temitter.once(eventName, resolver);\n\t\t\tif (eventName !== 'error') {\n\t\t\t\temitter.once('error', errorListener);\n\t\t\t}\n\n\t\t\tconst abortListener = () => {\n\t\t\t\teventTargetAgnosticRemoveListener(emitter, eventName, resolver);\n\t\t\t\teventTargetAgnosticRemoveListener(emitter, 'error', errorListener);\n\t\t\t\treject(new AbortError(undefined, { cause: getReason(signal) }));\n\t\t\t};\n\n\t\t\tif (signal) {\n\t\t\t\teventTargetAgnosticAddListener(signal, 'abort', abortListener, { once: true });\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static on<\n\t\tEmitter extends AsyncEventEmitter,\n\t\tEventNames extends Record = Emitter extends AsyncEventEmitter ? Events : Record,\n\t\tEventName extends PropertyKey = keyof EventNames | keyof AsyncEventEmitterPredefinedEvents,\n\t\tEventResult extends unknown[] = EventName extends keyof AsyncEventEmitterPredefinedEvents\n\t\t\t? AsyncEventEmitterPredefinedEvents[EventName]\n\t\t\t: EventNames[EventName]\n\t>(emitter: Emitter, eventName: EventName, options: AbortableMethods = {}): AsyncGenerator {\n\t\tconst signal = options?.signal;\n\t\tvalidateAbortSignal(signal);\n\n\t\tif (signal?.aborted) {\n\t\t\tthrow new AbortError(undefined, { cause: getReason(signal) });\n\t\t}\n\n\t\tconst unconsumedEvents: unknown[][] = [];\n\t\tconst unconsumedPromises: { resolve: (value?: unknown) => void; reject: (reason?: unknown) => void }[] = [];\n\t\tlet error: unknown = null;\n\t\tlet finished = false;\n\n\t\tconst abortListener = () => {\n\t\t\terrorHandler(new AbortError(undefined, { cause: getReason(signal) }));\n\t\t};\n\n\t\tconst eventHandler = (...args: unknown[]) => {\n\t\t\tconst promise = unconsumedPromises.shift();\n\t\t\tif (promise) {\n\t\t\t\tpromise.resolve(createIterResult(args, false));\n\t\t\t} else {\n\t\t\t\tunconsumedEvents.push(args);\n\t\t\t}\n\t\t};\n\n\t\tconst errorHandler = (err: unknown) => {\n\t\t\tfinished = true;\n\n\t\t\tconst toError = unconsumedPromises.shift();\n\n\t\t\tif (toError) {\n\t\t\t\ttoError.reject(err);\n\t\t\t} else {\n\t\t\t\terror = err;\n\t\t\t}\n\n\t\t\tvoid iterator.return();\n\t\t};\n\n\t\tconst iterator: AsyncGenerator = Object.setPrototypeOf(\n\t\t\t{\n\t\t\t\tnext() {\n\t\t\t\t\t// First, we consume all unread events\n\t\t\t\t\tconst value = unconsumedEvents.shift();\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\treturn Promise.resolve(createIterResult(value, false));\n\t\t\t\t\t}\n\n\t\t\t\t\t// Then we error, if an error happened\n\t\t\t\t\t// This happens one time if at all, because after 'error'\n\t\t\t\t\t// we stop listening\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tconst p = Promise.reject(error);\n\t\t\t\t\t\t// Only the first element errors\n\t\t\t\t\t\terror = null;\n\t\t\t\t\t\treturn p;\n\t\t\t\t\t}\n\n\t\t\t\t\t// If the iterator is finished, resolve to done\n\t\t\t\t\tif (finished) {\n\t\t\t\t\t\treturn Promise.resolve(createIterResult(undefined, true));\n\t\t\t\t\t}\n\n\t\t\t\t\t// Wait until an event happens\n\t\t\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\t\t\tunconsumedPromises.push({ resolve, reject });\n\t\t\t\t\t});\n\t\t\t\t},\n\n\t\t\t\treturn() {\n\t\t\t\t\temitter.off(eventName, eventHandler);\n\t\t\t\t\temitter.off('error', errorHandler);\n\n\t\t\t\t\tif (signal) {\n\t\t\t\t\t\teventTargetAgnosticRemoveListener(signal, 'abort', abortListener);\n\t\t\t\t\t}\n\n\t\t\t\t\tfinished = true;\n\n\t\t\t\t\tconst doneResult = createIterResult(undefined, true);\n\t\t\t\t\tfor (const promise of unconsumedPromises) {\n\t\t\t\t\t\tpromise.resolve(doneResult);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Promise.resolve(doneResult);\n\t\t\t\t},\n\n\t\t\t\tthrow(err: unknown) {\n\t\t\t\t\tif (!err || !(err instanceof Error)) {\n\t\t\t\t\t\tthrow new TypeError(`Expected Error instance to be thrown in AsyncEventEmitter.AsyncIterator. Got ${err}`);\n\t\t\t\t\t}\n\n\t\t\t\t\terror = err;\n\t\t\t\t\temitter.off(eventName, eventHandler);\n\t\t\t\t\temitter.off('error', errorHandler);\n\t\t\t\t},\n\n\t\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\t\treturn this;\n\t\t\t\t}\n\t\t\t},\n\t\t\tAsyncIteratorPrototype\n\t\t);\n\n\t\temitter.on(eventName, eventHandler);\n\t\tif (eventName !== 'error') {\n\t\t\temitter.on('error', errorHandler);\n\t\t}\n\n\t\tif (signal) {\n\t\t\teventTargetAgnosticAddListener(signal, 'abort', abortListener);\n\t\t}\n\n\t\treturn iterator;\n\t}\n}\n\nexport interface AsyncEventEmitterPredefinedEvents {\n\tnewListener: [eventName: string | symbol, listener: (...args: any[]) => Awaitable];\n\tremoveListener: [eventName: string | symbol, listener: (...args: any[]) => Awaitable];\n}\n\ninterface WrappedOnceState {\n\tlistener: (...args: Args) => Awaitable;\n\tfired: boolean;\n\teventName: string | symbol;\n\teventEmitter: AsyncEventEmitter;\n\twrapFn: (...args: Args) => Awaitable;\n}\n\nexport interface WrappedOnce {\n\t(...args: Args): Awaitable;\n\tlistener: (...args: Args) => Awaitable;\n\t_hasWarnedAboutMaxListeners?: boolean;\n}\n\nexport interface Listener {\n\t(...args: Args): Awaitable;\n\tlistener: (...args: Args) => Awaitable;\n\t_hasWarnedAboutMaxListeners?: boolean;\n}\n\nexport type Awaitable = T | Promise;\n\nexport interface AbortableMethods {\n\tsignal?: AbortSignal;\n}\n\n// @ts-ignore Not all paths returning is fine just fine:tm:\nfunction onceWrapper(this: WrappedOnceState) {\n\tif (!this.fired) {\n\t\tthis.eventEmitter.removeListener(this.eventName, this.wrapFn);\n\t\tthis.fired = true;\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tif (arguments.length === 0) {\n\t\t\t// @ts-expect-error Types can be hell\n\t\t\treturn this.listener.call(this.eventEmitter);\n\t\t}\n\n\t\t// eslint-disable-next-line prefer-rest-params\n\t\treturn this.listener.apply(this.eventEmitter, arguments as unknown as Args);\n\t}\n}\n\n/**\n * A TypeScript not-compliant way of accessing AbortSignal#reason\n * Because DOM types have it, NodeJS types don't. -w-\n */\nfunction getReason(signal: any) {\n\treturn signal?.reason;\n}\n\nfunction eventTargetAgnosticRemoveListener(emitter: any, name: PropertyKey, listener: (...args: unknown[]) => any, flags?: InternalAgnosticFlags) {\n\tif (typeof emitter.off === 'function') {\n\t\temitter.off(name, listener);\n\t} else if (typeof emitter.removeEventListener === 'function') {\n\t\temitter.removeEventListener(name, listener, flags);\n\t}\n}\n\nfunction eventTargetAgnosticAddListener(emitter: any, name: string | symbol, listener: (...args: unknown[]) => any, flags?: InternalAgnosticFlags) {\n\tif (typeof emitter.on === 'function') {\n\t\tif (flags?.once) {\n\t\t\temitter.once!(name, listener);\n\t\t} else {\n\t\t\temitter.on(name, listener);\n\t\t}\n\t} else if (typeof emitter.addEventListener === 'function') {\n\t\temitter.addEventListener(name, listener, flags);\n\t}\n}\n\ninterface InternalAgnosticFlags {\n\tonce?: boolean;\n}\n\n// eslint-disable-next-line func-names, @typescript-eslint/no-empty-function\nconst AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype);\n\nfunction createIterResult(value: unknown, done: boolean) {\n\treturn { value, done };\n}\n\nexport interface AbortErrorOptions {\n\tcause?: unknown;\n}\n\nexport class AbortError extends Error {\n\tpublic readonly code = 'ABORT_ERR';\n\tpublic override readonly name = 'AbortError';\n\n\tpublic constructor(message = 'The operation was aborted', options: AbortErrorOptions | undefined = undefined) {\n\t\tif (options !== undefined && typeof options !== 'object') {\n\t\t\tthrow new TypeError(`Failed to create AbortError: options is not an object or undefined`);\n\t\t}\n\n\t\tsuper(message, options);\n\t}\n}\n\nfunction handleMaybeAsync(emitter: AsyncEventEmitter, result: any) {\n\ttry {\n\t\tconst fin = result.finally;\n\n\t\tif (typeof fin === 'function') {\n\t\t\tconst promiseId = String(++emitter['_wrapperId']);\n\t\t\temitter['_internalPromiseMap'].set(promiseId, result);\n\t\t\tfin.call(result, function final() {\n\t\t\t\temitter['_internalPromiseMap'].delete(promiseId);\n\t\t\t});\n\t\t}\n\t} catch (err) {\n\t\temitter.emit('error', err);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,SAAS,iBAAiB,OAA0E;AACnG,MAAI,OAAO,UAAU,YAAY;AAChC,UAAM,IAAI,UAAU,sDAAsD,OAAO,OAAO;AAAA,EACzF;AACD;AAJS;AAMT,SAAS,oBAAoB,OAA0D;AAEtF,MAAI,SAAS,EAAE,iBAAiB,cAAc;AAC7C,UAAM,IAAI,UAAU,sDAAsD,OAAO;AAAA,EAClF;AACD;AALS;AAQT,SAAS,UAAU,MAAiB,OAAe;AAClD,SAAO,QAAQ,IAAI,KAAK,QAAQ,SAAS;AACxC,SAAK,KAAK,IAAI,KAAK,QAAQ,CAAC;AAAA,EAC7B;AAEA,OAAK,IAAI;AACV;AANS;AAST,SAAS,WAAgC,KAAW;AAGnD,UAAQ,IAAI,QAAQ;AAAA,IACnB,KAAK;AACJ,aAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AAAA,IACvB,KAAK;AACJ,aAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AAAA,IAC/B,KAAK;AACJ,aAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,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,YAAY,UAAU;AACzD,YAAM,IAAI,UAAU,oEAAoE;AAAA,IACzF;AAEA,UAAM,SAAS,OAAO;AARvB,SAAgB,OAAO;AACvB,SAAyB,OAAO;AAAA,EAQhC;AACD;AAXa;AAab,SAAS,iBAAiB,SAAiC,QAAa;AACvE,MAAI;AACH,UAAM,MAAM,OAAO;AAEnB,QAAI,OAAO,QAAQ,YAAY;AAC9B,YAAM,YAAY,OAAO,EAAE,QAAQ,YAAY,CAAC;AAChD,cAAQ,qBAAqB,EAAE,IAAI,WAAW,MAAM;AACpD,UAAI,KAAK,QAAQ,gCAAS,QAAQ;AACjC,gBAAQ,qBAAqB,EAAE,OAAO,SAAS;AAAA,MAChD,GAFiB,QAEhB;AAAA,IACF;AAAA,EACD,SAAS,KAAP;AACD,YAAQ,KAAK,SAAS,GAAG;AAAA,EAC1B;AACD;AAdS;","names":[]} \ No newline at end of file diff --git a/node_modules/@vladfrangu/async_event_emitter/dist/index.mjs b/node_modules/@vladfrangu/async_event_emitter/dist/index.mjs new file mode 100644 index 0000000..9987787 --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/dist/index.mjs @@ -0,0 +1,547 @@ +var __defProp = Object.defineProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); + +// src/index.ts +function validateListener(input) { + if (typeof input !== "function") { + throw new TypeError(`The listener argument must be a function. Received ${typeof input}`); + } +} +__name(validateListener, "validateListener"); +function validateAbortSignal(input) { + if (input && !(input instanceof AbortSignal)) { + throw new TypeError(`The signal option must be an AbortSignal. Received ${input}`); + } +} +__name(validateAbortSignal, "validateAbortSignal"); +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) { + list[index] = list[index + 1]; + } + list.pop(); +} +__name(spliceOne, "spliceOne"); +function arrayClone(arr) { + switch (arr.length) { + case 2: + return [arr[0], arr[1]]; + case 3: + return [arr[0], arr[1], arr[2]]; + case 4: + return [arr[0], arr[1], arr[2], arr[3]]; + case 5: + return [arr[0], arr[1], arr[2], arr[3], arr[4]]; + case 6: + return [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]]; + } + return arr.slice(); +} +__name(arrayClone, "arrayClone"); +function identicalSequenceRange(a, b) { + for (let i = 0; i < a.length - 3; i++) { + const pos = b.indexOf(a[i]); + if (pos !== -1) { + const rest = b.length - pos; + if (rest > 3) { + let len = 1; + const maxLen = Math.min(a.length - i, rest); + while (maxLen > len && a[i + len] === b[pos + len]) { + len++; + } + if (len > 3) { + return [len, i]; + } + } + } + } + return [0, 0]; +} +__name(identicalSequenceRange, "identicalSequenceRange"); +function enhanceStackTrace(err, own) { + let ctorInfo = ""; + try { + const { name } = this.constructor; + if (name !== "AsyncEventEmitter") + ctorInfo = ` on ${name} instance`; + } catch { + } + const sep = ` +Emitted 'error' event${ctorInfo} at: +`; + const errStack = err.stack.split("\n").slice(1); + const ownStack = own.stack.split("\n").slice(1); + const { 0: len, 1: off } = identicalSequenceRange(ownStack, errStack); + if (len > 0) { + ownStack.splice(off + 1, len - 2, " [... lines matching original stack trace ...]"); + } + return err.stack + sep + ownStack.join("\n"); +} +__name(enhanceStackTrace, "enhanceStackTrace"); +var AsyncEventEmitter = class { + constructor() { + this._events = { + __proto__: null + }; + this._eventCount = 0; + this._maxListeners = 10; + this._internalPromiseMap = /* @__PURE__ */ new Map(); + this._wrapperId = 0n; + } + addListener(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, false); + this._addListener(eventName, wrapped, false); + return this; + } + on(eventName, listener) { + return this.addListener(eventName, listener); + } + once(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, true); + this._addListener(eventName, wrapped, false); + return this; + } + removeListener(eventName, listener) { + validateListener(listener); + const events = this._events; + const eventList = events[eventName]; + if (eventList === void 0) { + return this; + } + if (eventList === listener || eventList.listener === listener) { + if (--this._eventCount === 0) { + this._events = { __proto__: null }; + } else { + delete events[eventName]; + if (events.removeListener) { + this.emit("removeListener", eventName, eventList.listener ?? eventList); + } + } + } else if (typeof eventList !== "function") { + let position = -1; + for (let i = eventList.length - 1; i >= 0; i--) { + if (eventList[i] === listener || eventList[i].listener === listener) { + position = i; + break; + } + } + if (position < 0) { + return this; + } + if (position === 0) { + eventList.shift(); + } else { + spliceOne(eventList, position); + } + if (eventList.length === 0) { + delete events[eventName]; + --this._eventCount; + } + if (events.removeListener !== void 0) { + this.emit("removeListener", eventName, listener); + } + } + return this; + } + off(eventName, listener) { + return this.removeListener(eventName, listener); + } + removeAllListeners(event) { + const events = this._events; + if (events.removeListener === void 0) { + if (!event) { + this._events = { __proto__: null }; + this._eventCount = 0; + } else if (events[event] !== void 0) { + if (--this._eventCount === 0) { + this._events = { __proto__: null }; + } else { + delete events[event]; + } + } + return this; + } + if (!event) { + for (const key of Reflect.ownKeys(events)) { + if (key === "removeListener") { + continue; + } + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = { __proto__: null }; + this._eventCount = 0; + return this; + } + const listeners = events[event]; + if (typeof listeners === "function") { + this.removeListener(event, listeners); + } else if (listeners !== void 0) { + for (let i = listeners.length - 1; i >= 0; i--) { + this.removeListener(event, listeners[i]); + } + } + return this; + } + setMaxListeners(n) { + if (typeof n !== "number" || n < 0 || Number.isNaN(n)) { + throw new RangeError(`Expected to get a non-negative number for "setMaxListeners", got ${n} instead`); + } + this._maxListeners = n; + return this; + } + getMaxListeners() { + return this._maxListeners; + } + listeners(eventName) { + const eventList = this._events[eventName]; + if (eventList === void 0) { + return []; + } + if (typeof eventList === "function") { + return [eventList.listener ?? eventList]; + } + const ret = arrayClone(eventList); + for (let i = 0; i < ret.length; ++i) { + const orig = ret[i].listener; + if (typeof orig === "function") { + ret[i] = orig; + } + } + return ret; + } + rawListeners(eventName) { + const eventList = this._events[eventName]; + if (eventList === void 0) { + return []; + } + if (typeof eventList === "function") { + return [eventList]; + } + return arrayClone(eventList); + } + emit(eventName, ...args) { + let doError = eventName === "error"; + const events = this._events; + if (events !== void 0) { + doError = doError && events.error === void 0; + } else if (!doError) { + return false; + } + if (doError) { + let er; + if (args.length > 0) { + er = args[0]; + } + if (er instanceof Error) { + try { + const capture = {}; + Error.captureStackTrace(capture, AsyncEventEmitter.prototype.emit); + Object.defineProperty(er, "stack", { + value: enhanceStackTrace.call(this, er, capture), + configurable: true + }); + } catch { + } + throw er; // Unhandled 'error' event + } + const stringifiedError = String(er); + const err = new Error(`Unhandled 'error' event emitted, received ${stringifiedError}`); + err.context = er; + throw err; // Unhandled 'error' event + } + const handlers = events[eventName]; + if (handlers === void 0) { + return false; + } + if (typeof handlers === "function") { + const result = handlers.apply(this, args); + if (result !== void 0 && result !== null) { + handleMaybeAsync(this, result); + } + } else { + const len = handlers.length; + const listeners = arrayClone(handlers); + for (let i = 0; i < len; ++i) { + const result = listeners[i].apply(this, args); + if (result !== void 0 && result !== null) { + handleMaybeAsync(this, result); + } + } + } + return true; + } + listenerCount(eventName) { + const events = this._events; + if (events === void 0) { + return 0; + } + const eventListeners = events[eventName]; + if (typeof eventListeners === "function") { + return 1; + } + return eventListeners?.length ?? 0; + } + prependListener(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, false); + this._addListener(eventName, wrapped, true); + return this; + } + prependOnceListener(eventName, listener) { + validateListener(listener); + const wrapped = this._wrapListener(eventName, listener, true); + this._addListener(eventName, wrapped, true); + return this; + } + eventNames() { + return this._eventCount > 0 ? Reflect.ownKeys(this._events) : []; + } + async waitForAllListenersToComplete() { + const promises = [...this._internalPromiseMap.values()]; + if (promises.length === 0) { + return false; + } + await Promise.all(promises); + return true; + } + _addListener(eventName, wrappedListener, prepend) { + if (this._events.newListener !== void 0) { + this.emit("newListener", eventName, wrappedListener.listener ?? wrappedListener); + } + let existing = this._events[eventName]; + if (existing === void 0) { + existing = this._events[eventName] = wrappedListener; + ++this._eventCount; + } else if (typeof existing === "function") { + existing = this._events[eventName] = prepend ? [wrappedListener, existing] : [existing, wrappedListener]; + } else if (prepend) { + existing.unshift(wrappedListener); + } else { + existing.push(wrappedListener); + } + if (this._maxListeners > 0 && existing.length > this._maxListeners && !existing._hasWarnedAboutMaxListeners) { + existing._hasWarnedAboutMaxListeners = true; + const warningMessage = [ + `Possible AsyncEventEmitter memory leak detected. ${existing.length} ${String(eventName)} listeners added to ${this.constructor.name}.`, + `Use emitter.setMaxListeners() to increase the limit.` + ].join(" "); + console.warn(warningMessage); + } + } + _wrapListener(eventName, listener, once) { + if (!once) { + return listener; + } + const state = { + fired: false, + wrapFn: void 0, + eventEmitter: this, + eventName, + listener + }; + const aliased = onceWrapper; + const wrapped = aliased.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; + } + static listenerCount(emitter, eventName) { + return emitter.listenerCount(eventName); + } + static async once(emitter, eventName, options = {}) { + const signal = options?.signal; + validateAbortSignal(signal); + if (signal?.aborted) { + throw new AbortError(void 0, { cause: getReason(signal) }); + } + return new Promise((resolve, reject) => { + const errorListener = /* @__PURE__ */ __name((err) => { + emitter.removeListener(eventName, resolver); + if (signal) { + eventTargetAgnosticRemoveListener(emitter, eventName, abortListener); + } + reject(err); + }, "errorListener"); + const resolver = /* @__PURE__ */ __name((...args) => { + emitter.removeListener("error", errorListener); + if (signal) { + eventTargetAgnosticRemoveListener(signal, "abort", abortListener); + } + resolve(args); + }, "resolver"); + emitter.once(eventName, resolver); + if (eventName !== "error") { + emitter.once("error", errorListener); + } + const abortListener = /* @__PURE__ */ __name(() => { + eventTargetAgnosticRemoveListener(emitter, eventName, resolver); + eventTargetAgnosticRemoveListener(emitter, "error", errorListener); + reject(new AbortError(void 0, { cause: getReason(signal) })); + }, "abortListener"); + if (signal) { + eventTargetAgnosticAddListener(signal, "abort", abortListener, { once: true }); + } + }); + } + static on(emitter, eventName, options = {}) { + const signal = options?.signal; + validateAbortSignal(signal); + if (signal?.aborted) { + throw new AbortError(void 0, { cause: getReason(signal) }); + } + const unconsumedEvents = []; + const unconsumedPromises = []; + let error = null; + let finished = false; + const abortListener = /* @__PURE__ */ __name(() => { + errorHandler(new AbortError(void 0, { cause: getReason(signal) })); + }, "abortListener"); + const eventHandler = /* @__PURE__ */ __name((...args) => { + const promise = unconsumedPromises.shift(); + if (promise) { + promise.resolve(createIterResult(args, false)); + } else { + unconsumedEvents.push(args); + } + }, "eventHandler"); + const errorHandler = /* @__PURE__ */ __name((err) => { + finished = true; + const toError = unconsumedPromises.shift(); + if (toError) { + toError.reject(err); + } else { + error = err; + } + void iterator.return(); + }, "errorHandler"); + const iterator = Object.setPrototypeOf( + { + next() { + const value = unconsumedEvents.shift(); + if (value) { + return Promise.resolve(createIterResult(value, false)); + } + if (error) { + const p = Promise.reject(error); + error = null; + return p; + } + if (finished) { + return Promise.resolve(createIterResult(void 0, true)); + } + return new Promise((resolve, reject) => { + unconsumedPromises.push({ resolve, reject }); + }); + }, + return() { + emitter.off(eventName, eventHandler); + emitter.off("error", errorHandler); + if (signal) { + eventTargetAgnosticRemoveListener(signal, "abort", abortListener); + } + finished = true; + const doneResult = createIterResult(void 0, true); + for (const promise of unconsumedPromises) { + promise.resolve(doneResult); + } + return Promise.resolve(doneResult); + }, + throw(err) { + if (!err || !(err instanceof Error)) { + throw new TypeError(`Expected Error instance to be thrown in AsyncEventEmitter.AsyncIterator. Got ${err}`); + } + error = err; + emitter.off(eventName, eventHandler); + emitter.off("error", errorHandler); + }, + [Symbol.asyncIterator]() { + return this; + } + }, + AsyncIteratorPrototype + ); + emitter.on(eventName, eventHandler); + if (eventName !== "error") { + emitter.on("error", errorHandler); + } + if (signal) { + eventTargetAgnosticAddListener(signal, "abort", abortListener); + } + return iterator; + } +}; +__name(AsyncEventEmitter, "AsyncEventEmitter"); +function onceWrapper() { + if (!this.fired) { + this.eventEmitter.removeListener(this.eventName, this.wrapFn); + this.fired = true; + if (arguments.length === 0) { + return this.listener.call(this.eventEmitter); + } + return this.listener.apply(this.eventEmitter, arguments); + } +} +__name(onceWrapper, "onceWrapper"); +function getReason(signal) { + return signal?.reason; +} +__name(getReason, "getReason"); +function eventTargetAgnosticRemoveListener(emitter, name, listener, flags) { + if (typeof emitter.off === "function") { + emitter.off(name, listener); + } else if (typeof emitter.removeEventListener === "function") { + emitter.removeEventListener(name, listener, flags); + } +} +__name(eventTargetAgnosticRemoveListener, "eventTargetAgnosticRemoveListener"); +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === "function") { + if (flags?.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name, listener, flags); + } +} +__name(eventTargetAgnosticAddListener, "eventTargetAgnosticAddListener"); +var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { +}).prototype); +function createIterResult(value, done) { + return { value, done }; +} +__name(createIterResult, "createIterResult"); +var AbortError = class extends Error { + constructor(message = "The operation was aborted", options = void 0) { + if (options !== void 0 && typeof options !== "object") { + throw new TypeError(`Failed to create AbortError: options is not an object or undefined`); + } + super(message, options); + this.code = "ABORT_ERR"; + this.name = "AbortError"; + } +}; +__name(AbortError, "AbortError"); +function handleMaybeAsync(emitter, result) { + try { + const fin = result.finally; + if (typeof fin === "function") { + const promiseId = String(++emitter["_wrapperId"]); + emitter["_internalPromiseMap"].set(promiseId, result); + fin.call(result, /* @__PURE__ */ __name(function final() { + emitter["_internalPromiseMap"].delete(promiseId); + }, "final")); + } + } catch (err) { + emitter.emit("error", err); + } +} +__name(handleMaybeAsync, "handleMaybeAsync"); +export { + AbortError, + AsyncEventEmitter +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@vladfrangu/async_event_emitter/dist/index.mjs.map b/node_modules/@vladfrangu/async_event_emitter/dist/index.mjs.map new file mode 100644 index 0000000..3c8b39a --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/dot-notation */\nfunction validateListener(input: unknown): asserts input is (...args: unknown[]) => Awaitable {\n\tif (typeof input !== 'function') {\n\t\tthrow new TypeError(`The listener argument must be a function. Received ${typeof input}`);\n\t}\n}\n\nfunction validateAbortSignal(input: unknown): asserts input is AbortSignal | undefined {\n\t// Only validate that the signal is a signal if its defined\n\tif (input && !(input instanceof AbortSignal)) {\n\t\tthrow new TypeError(`The signal option must be an AbortSignal. Received ${input}`);\n\t}\n}\n\n// Inspired from https://github.com/nodejs/node/blob/42ad967d68137df1a80a877e7b5ad56403fc157f/lib/internal/util.js#L397\nfunction spliceOne(list: unknown[], index: number) {\n\tfor (; index + 1 < list.length; index++) {\n\t\tlist[index] = list[index + 1];\n\t}\n\n\tlist.pop();\n}\n\n// Inspired from https://github.com/nodejs/node/blob/42ad967d68137df1a80a877e7b5ad56403fc157f/lib/events.js#L889\nfunction arrayClone(arr: T): T {\n\t// At least since V8 8.3, this implementation is faster than the previous\n\t// which always used a simple for-loop\n\tswitch (arr.length) {\n\t\tcase 2:\n\t\t\treturn [arr[0], arr[1]] as T;\n\t\tcase 3:\n\t\t\treturn [arr[0], arr[1], arr[2]] as T;\n\t\tcase 4:\n\t\t\treturn [arr[0], arr[1], arr[2], arr[3]] as T;\n\t\tcase 5:\n\t\t\treturn [arr[0], arr[1], arr[2], arr[3], arr[4]] as T;\n\t\tcase 6:\n\t\t\treturn [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]] as T;\n\t}\n\n\treturn arr.slice() as T;\n}\n\n// Inspired from https://github.com/nodejs/node/blob/42ad967d68137df1a80a877e7b5ad56403fc157f/lib/events.js#L427-L475\nfunction identicalSequenceRange(a: unknown[], b: unknown[]): [number, number] {\n\tfor (let i = 0; i < a.length - 3; i++) {\n\t\t// Find the first entry of b that matches the current entry of a.\n\t\tconst pos = b.indexOf(a[i]);\n\t\tif (pos !== -1) {\n\t\t\tconst rest = b.length - pos;\n\t\t\tif (rest > 3) {\n\t\t\t\tlet len = 1;\n\t\t\t\tconst maxLen = Math.min(a.length - i, rest);\n\t\t\t\t// Count the number of consecutive entries.\n\t\t\t\twhile (maxLen > len && a[i + len] === b[pos + len]) {\n\t\t\t\t\tlen++;\n\t\t\t\t}\n\t\t\t\tif (len > 3) {\n\t\t\t\t\treturn [len, i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [0, 0];\n}\n\nfunction enhanceStackTrace(this: AsyncEventEmitter, err: Error, own: Error) {\n\tlet ctorInfo = '';\n\ttry {\n\t\tconst { name } = this.constructor;\n\t\tif (name !== 'AsyncEventEmitter') ctorInfo = ` on ${name} instance`;\n\t} catch {\n\t\t// Continue regardless of error.\n\t}\n\tconst sep = `\\nEmitted 'error' event${ctorInfo} at:\\n`;\n\n\tconst errStack = err.stack!.split('\\n').slice(1);\n\tconst ownStack = own.stack!.split('\\n').slice(1);\n\n\tconst { 0: len, 1: off } = identicalSequenceRange(ownStack, errStack);\n\tif (len > 0) {\n\t\townStack.splice(off + 1, len - 2, ' [... lines matching original stack trace ...]');\n\t}\n\n\treturn err.stack + sep + ownStack.join('\\n');\n}\n\ninterface InternalEventMap extends Array {\n\t_hasWarnedAboutMaxListeners?: boolean;\n}\n\nexport class AsyncEventEmitter = Record & AsyncEventEmitterPredefinedEvents> {\n\tprivate _events: Record = {\n\t\t__proto__: null\n\t} as Record;\n\n\tprivate _eventCount = 0;\n\tprivate _maxListeners = 10;\n\tprivate _internalPromiseMap: Map> = new Map();\n\tprivate _wrapperId = 0n;\n\n\tpublic addListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, false);\n\n\t\tthis._addListener(eventName, wrapped, false);\n\n\t\treturn this;\n\t}\n\n\tpublic on(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\treturn this.addListener(eventName, listener);\n\t}\n\n\tpublic once(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, true);\n\n\t\tthis._addListener(eventName, wrapped, false);\n\n\t\treturn this;\n\t}\n\n\tpublic removeListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst events = this._events;\n\t\tconst eventList = events[eventName];\n\n\t\tif (eventList === undefined) {\n\t\t\treturn this;\n\t\t}\n\n\t\tif (eventList === listener || (eventList as WrappedOnce).listener === listener) {\n\t\t\tif (--this._eventCount === 0) {\n\t\t\t\tthis._events = { __proto__: null } as Record<\n\t\t\t\t\tkeyof Events | keyof AsyncEventEmitterPredefinedEvents,\n\t\t\t\t\tListener | WrappedOnce | InternalEventMap\n\t\t\t\t>;\n\t\t\t} else {\n\t\t\t\tdelete events[eventName];\n\t\t\t\tif (events.removeListener) {\n\t\t\t\t\tthis.emit('removeListener', eventName as string, (eventList as WrappedOnce).listener ?? eventList);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (typeof eventList !== 'function') {\n\t\t\tlet position = -1;\n\n\t\t\tfor (let i = eventList.length - 1; i >= 0; i--) {\n\t\t\t\tif (eventList[i] === listener || (eventList[i] as WrappedOnce).listener === listener) {\n\t\t\t\t\tposition = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (position < 0) {\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tif (position === 0) {\n\t\t\t\teventList.shift();\n\t\t\t} else {\n\t\t\t\tspliceOne(eventList, position);\n\t\t\t}\n\n\t\t\tif (eventList.length === 0) {\n\t\t\t\tdelete events[eventName];\n\t\t\t\t--this._eventCount;\n\t\t\t}\n\n\t\t\tif (events.removeListener !== undefined) {\n\t\t\t\t// Thanks TypeScript for the cast...\n\t\t\t\tthis.emit('removeListener', eventName as string | symbol, listener);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic off(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\treturn this.removeListener(eventName, listener);\n\t}\n\n\tpublic removeAllListeners(event?: K | undefined): this {\n\t\tconst events = this._events;\n\n\t\t// Not listening for removeListener, no need to emit\n\t\tif (events.removeListener === undefined) {\n\t\t\tif (!event) {\n\t\t\t\tthis._events = { __proto__: null } as Record;\n\t\t\t\tthis._eventCount = 0;\n\t\t\t} else if (events[event] !== undefined) {\n\t\t\t\tif (--this._eventCount === 0) {\n\t\t\t\t\tthis._events = { __proto__: null } as Record;\n\t\t\t\t} else {\n\t\t\t\t\tdelete events[event];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this;\n\t\t}\n\n\t\t// Emit removeListener for all listeners on all events\n\t\tif (!event) {\n\t\t\tfor (const key of Reflect.ownKeys(events)) {\n\t\t\t\tif (key === 'removeListener') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis.removeAllListeners(key);\n\t\t\t}\n\n\t\t\tthis.removeAllListeners('removeListener');\n\t\t\tthis._events = { __proto__: null } as Record;\n\t\t\tthis._eventCount = 0;\n\n\t\t\treturn this;\n\t\t}\n\n\t\tconst listeners = events[event];\n\n\t\tif (typeof listeners === 'function') {\n\t\t\tthis.removeListener(event, listeners);\n\t\t} else if (listeners !== undefined) {\n\t\t\t// LIFO order\n\t\t\tfor (let i = listeners.length - 1; i >= 0; i--) {\n\t\t\t\tthis.removeListener(event, listeners[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic setMaxListeners(n: number): this {\n\t\tif (typeof n !== 'number' || n < 0 || Number.isNaN(n)) {\n\t\t\tthrow new RangeError(`Expected to get a non-negative number for \"setMaxListeners\", got ${n} instead`);\n\t\t}\n\n\t\tthis._maxListeners = n;\n\n\t\treturn this;\n\t}\n\n\tpublic getMaxListeners(): number {\n\t\treturn this._maxListeners;\n\t}\n\n\tpublic listeners(eventName: K): Listener['listener'][] {\n\t\tconst eventList = this._events[eventName];\n\n\t\tif (eventList === undefined) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (typeof eventList === 'function') {\n\t\t\treturn [eventList.listener ?? eventList];\n\t\t}\n\n\t\tconst ret = arrayClone(eventList) as Listener['listener'][];\n\n\t\tfor (let i = 0; i < ret.length; ++i) {\n\t\t\tconst orig = (ret[i] as WrappedOnce).listener;\n\t\t\tif (typeof orig === 'function') {\n\t\t\t\tret[i] = orig;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic rawListeners(eventName: K): Listener[] {\n\t\tconst eventList = this._events[eventName];\n\n\t\tif (eventList === undefined) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (typeof eventList === 'function') {\n\t\t\treturn [eventList];\n\t\t}\n\n\t\treturn arrayClone(eventList) as Listener[];\n\t}\n\n\tpublic emit(\n\t\teventName: K,\n\t\t...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]\n\t): boolean {\n\t\tlet doError = eventName === 'error';\n\n\t\tconst events = this._events;\n\t\tif (events !== undefined) {\n\t\t\tdoError = doError && events.error === undefined;\n\t\t} else if (!doError) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (doError) {\n\t\t\tlet er: unknown;\n\n\t\t\tif (args.length > 0) {\n\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\ter = args[0];\n\t\t\t}\n\n\t\t\tif (er instanceof Error) {\n\t\t\t\ttry {\n\t\t\t\t\tconst capture = {};\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\t\t\t\t\tError.captureStackTrace(capture, AsyncEventEmitter.prototype.emit);\n\t\t\t\t\tObject.defineProperty(er, 'stack', {\n\t\t\t\t\t\tvalue: enhanceStackTrace.call(this, er, capture as Error),\n\t\t\t\t\t\tconfigurable: true\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// Continue regardless of error\n\t\t\t\t}\n\n\t\t\t\tthrow er; // Unhandled 'error' event\n\t\t\t}\n\n\t\t\tconst stringifiedError = String(er);\n\n\t\t\t// Give some error to user\n\t\t\tconst err = new Error(`Unhandled 'error' event emitted, received ${stringifiedError}`);\n\t\t\t// @ts-expect-error Add context to error too\n\t\t\terr.context = er;\n\n\t\t\tthrow err; // Unhandled 'error' event\n\t\t}\n\n\t\tconst handlers = events[eventName];\n\n\t\tif (handlers === undefined) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (typeof handlers === 'function') {\n\t\t\tconst result = handlers.apply(this, args);\n\n\t\t\tif (result !== undefined && result !== null) {\n\t\t\t\thandleMaybeAsync(this, result);\n\t\t\t}\n\t\t} else {\n\t\t\tconst len = handlers.length;\n\t\t\tconst listeners = arrayClone(handlers as InternalEventMap);\n\n\t\t\tfor (let i = 0; i < len; ++i) {\n\t\t\t\t// We call all listeners regardless of the result, as we already handle possible error emits in the wrapped func\n\t\t\t\tconst result = listeners[i].apply(this, args);\n\n\t\t\t\tif (result !== undefined && result !== null) {\n\t\t\t\t\thandleMaybeAsync(this, result);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic listenerCount(eventName: K): number {\n\t\tconst events = this._events;\n\n\t\tif (events === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst eventListeners = events[eventName];\n\n\t\tif (typeof eventListeners === 'function') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn eventListeners?.length ?? 0;\n\t}\n\n\tpublic prependListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, false);\n\n\t\tthis._addListener(eventName, wrapped, true);\n\n\t\treturn this;\n\t}\n\n\tpublic prependOnceListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => void\n\t): this {\n\t\tvalidateListener(listener);\n\n\t\tconst wrapped = this._wrapListener(eventName, listener, true);\n\n\t\tthis._addListener(eventName, wrapped, true);\n\n\t\treturn this;\n\t}\n\n\tpublic eventNames(): (keyof Events | keyof AsyncEventEmitterPredefinedEvents)[] {\n\t\treturn this._eventCount > 0 ? Reflect.ownKeys(this._events) : [];\n\t}\n\n\tpublic async waitForAllListenersToComplete() {\n\t\tconst promises = [...this._internalPromiseMap.values()];\n\n\t\tif (promises.length === 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tawait Promise.all(promises);\n\n\t\treturn true;\n\t}\n\n\tprivate _addListener(\n\t\teventName: K,\n\t\twrappedListener: Listener | WrappedOnce,\n\t\tprepend: boolean\n\t) {\n\t\t// Emit newListener first in the event someone is listening for it\n\t\tif (this._events.newListener !== undefined) {\n\t\t\t// Thanks TypeScript for the cast...\n\t\t\tthis.emit('newListener', eventName as string | symbol, (wrappedListener as WrappedOnce).listener ?? wrappedListener);\n\t\t}\n\n\t\tlet existing = this._events[eventName];\n\n\t\tif (existing === undefined) {\n\t\t\t// eslint-disable-next-line no-multi-assign\n\t\t\texisting = this._events[eventName] = wrappedListener;\n\t\t\t++this._eventCount;\n\t\t} else if (typeof existing === 'function') {\n\t\t\t// Adding the second element, need to change to array.\n\t\t\t// eslint-disable-next-line no-multi-assign\n\t\t\texisting = this._events[eventName] = prepend ? [wrappedListener, existing] : [existing, wrappedListener];\n\t\t\t// If we've already got an array, just append.\n\t\t} else if (prepend) {\n\t\t\texisting.unshift(wrappedListener);\n\t\t} else {\n\t\t\texisting.push(wrappedListener);\n\t\t}\n\n\t\tif (this._maxListeners > 0 && existing.length > this._maxListeners && !existing._hasWarnedAboutMaxListeners) {\n\t\t\texisting._hasWarnedAboutMaxListeners = true;\n\t\t\tconst warningMessage = [\n\t\t\t\t`Possible AsyncEventEmitter memory leak detected. ${existing.length} ${String(eventName)} listeners added to ${\n\t\t\t\t\tthis.constructor.name\n\t\t\t\t}.`,\n\t\t\t\t`Use emitter.setMaxListeners() to increase the limit.`\n\t\t\t].join(' ');\n\t\t\tconsole.warn(warningMessage);\n\t\t}\n\t}\n\n\tprivate _wrapListener(\n\t\teventName: K,\n\t\tlistener: (...args: K extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]) => Awaitable,\n\t\tonce: boolean\n\t): Listener | WrappedOnce {\n\t\tif (!once) {\n\t\t\treturn listener as Listener;\n\t\t}\n\n\t\tconst state = {\n\t\t\tfired: false,\n\t\t\twrapFn: undefined!,\n\t\t\teventEmitter: this,\n\t\t\teventName,\n\t\t\tlistener\n\t\t} as WrappedOnceState;\n\n\t\tconst aliased = onceWrapper;\n\n\t\tconst wrapped = aliased.bind(state) as WrappedOnce<\n\t\t\tK extends keyof AsyncEventEmitterPredefinedEvents ? AsyncEventEmitterPredefinedEvents[K] : Events[K]\n\t\t>;\n\t\twrapped.listener = listener;\n\t\tstate.wrapFn = wrapped;\n\n\t\treturn wrapped as WrappedOnce;\n\t}\n\n\tpublic static listenerCount<\n\t\tEmitter extends AsyncEventEmitter,\n\t\tEventNames = Emitter extends AsyncEventEmitter ? Events : never,\n\t\tEventName extends PropertyKey = EventNames extends never ? string | symbol : keyof EventNames\n\t>(emitter: Emitter, eventName: EventName | keyof AsyncEventEmitterPredefinedEvents) {\n\t\treturn emitter.listenerCount(eventName);\n\t}\n\n\tpublic static async once<\n\t\tEmitter extends AsyncEventEmitter,\n\t\tEventNames extends Record = Emitter extends AsyncEventEmitter ? Events : Record,\n\t\tEventName extends PropertyKey = keyof EventNames | keyof AsyncEventEmitterPredefinedEvents,\n\t\tEventResult extends unknown[] = EventName extends keyof AsyncEventEmitterPredefinedEvents\n\t\t\t? AsyncEventEmitterPredefinedEvents[EventName]\n\t\t\t: EventNames[EventName]\n\t>(emitter: Emitter, eventName: EventName, options: AbortableMethods = {}) {\n\t\tconst signal = options?.signal;\n\t\tvalidateAbortSignal(signal);\n\n\t\tif (signal?.aborted) {\n\t\t\tthrow new AbortError(undefined, { cause: getReason(signal) });\n\t\t}\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst errorListener = (err: unknown) => {\n\t\t\t\temitter.removeListener(eventName, resolver);\n\n\t\t\t\tif (signal) {\n\t\t\t\t\teventTargetAgnosticRemoveListener(emitter, eventName, abortListener);\n\t\t\t\t}\n\n\t\t\t\treject(err);\n\t\t\t};\n\n\t\t\tconst resolver = (...args: unknown[]) => {\n\t\t\t\temitter.removeListener('error', errorListener);\n\n\t\t\t\tif (signal) {\n\t\t\t\t\teventTargetAgnosticRemoveListener(signal, 'abort', abortListener);\n\t\t\t\t}\n\n\t\t\t\tresolve(args as EventResult);\n\t\t\t};\n\n\t\t\temitter.once(eventName, resolver);\n\t\t\tif (eventName !== 'error') {\n\t\t\t\temitter.once('error', errorListener);\n\t\t\t}\n\n\t\t\tconst abortListener = () => {\n\t\t\t\teventTargetAgnosticRemoveListener(emitter, eventName, resolver);\n\t\t\t\teventTargetAgnosticRemoveListener(emitter, 'error', errorListener);\n\t\t\t\treject(new AbortError(undefined, { cause: getReason(signal) }));\n\t\t\t};\n\n\t\t\tif (signal) {\n\t\t\t\teventTargetAgnosticAddListener(signal, 'abort', abortListener, { once: true });\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static on<\n\t\tEmitter extends AsyncEventEmitter,\n\t\tEventNames extends Record = Emitter extends AsyncEventEmitter ? Events : Record,\n\t\tEventName extends PropertyKey = keyof EventNames | keyof AsyncEventEmitterPredefinedEvents,\n\t\tEventResult extends unknown[] = EventName extends keyof AsyncEventEmitterPredefinedEvents\n\t\t\t? AsyncEventEmitterPredefinedEvents[EventName]\n\t\t\t: EventNames[EventName]\n\t>(emitter: Emitter, eventName: EventName, options: AbortableMethods = {}): AsyncGenerator {\n\t\tconst signal = options?.signal;\n\t\tvalidateAbortSignal(signal);\n\n\t\tif (signal?.aborted) {\n\t\t\tthrow new AbortError(undefined, { cause: getReason(signal) });\n\t\t}\n\n\t\tconst unconsumedEvents: unknown[][] = [];\n\t\tconst unconsumedPromises: { resolve: (value?: unknown) => void; reject: (reason?: unknown) => void }[] = [];\n\t\tlet error: unknown = null;\n\t\tlet finished = false;\n\n\t\tconst abortListener = () => {\n\t\t\terrorHandler(new AbortError(undefined, { cause: getReason(signal) }));\n\t\t};\n\n\t\tconst eventHandler = (...args: unknown[]) => {\n\t\t\tconst promise = unconsumedPromises.shift();\n\t\t\tif (promise) {\n\t\t\t\tpromise.resolve(createIterResult(args, false));\n\t\t\t} else {\n\t\t\t\tunconsumedEvents.push(args);\n\t\t\t}\n\t\t};\n\n\t\tconst errorHandler = (err: unknown) => {\n\t\t\tfinished = true;\n\n\t\t\tconst toError = unconsumedPromises.shift();\n\n\t\t\tif (toError) {\n\t\t\t\ttoError.reject(err);\n\t\t\t} else {\n\t\t\t\terror = err;\n\t\t\t}\n\n\t\t\tvoid iterator.return();\n\t\t};\n\n\t\tconst iterator: AsyncGenerator = Object.setPrototypeOf(\n\t\t\t{\n\t\t\t\tnext() {\n\t\t\t\t\t// First, we consume all unread events\n\t\t\t\t\tconst value = unconsumedEvents.shift();\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\treturn Promise.resolve(createIterResult(value, false));\n\t\t\t\t\t}\n\n\t\t\t\t\t// Then we error, if an error happened\n\t\t\t\t\t// This happens one time if at all, because after 'error'\n\t\t\t\t\t// we stop listening\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tconst p = Promise.reject(error);\n\t\t\t\t\t\t// Only the first element errors\n\t\t\t\t\t\terror = null;\n\t\t\t\t\t\treturn p;\n\t\t\t\t\t}\n\n\t\t\t\t\t// If the iterator is finished, resolve to done\n\t\t\t\t\tif (finished) {\n\t\t\t\t\t\treturn Promise.resolve(createIterResult(undefined, true));\n\t\t\t\t\t}\n\n\t\t\t\t\t// Wait until an event happens\n\t\t\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\t\t\tunconsumedPromises.push({ resolve, reject });\n\t\t\t\t\t});\n\t\t\t\t},\n\n\t\t\t\treturn() {\n\t\t\t\t\temitter.off(eventName, eventHandler);\n\t\t\t\t\temitter.off('error', errorHandler);\n\n\t\t\t\t\tif (signal) {\n\t\t\t\t\t\teventTargetAgnosticRemoveListener(signal, 'abort', abortListener);\n\t\t\t\t\t}\n\n\t\t\t\t\tfinished = true;\n\n\t\t\t\t\tconst doneResult = createIterResult(undefined, true);\n\t\t\t\t\tfor (const promise of unconsumedPromises) {\n\t\t\t\t\t\tpromise.resolve(doneResult);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Promise.resolve(doneResult);\n\t\t\t\t},\n\n\t\t\t\tthrow(err: unknown) {\n\t\t\t\t\tif (!err || !(err instanceof Error)) {\n\t\t\t\t\t\tthrow new TypeError(`Expected Error instance to be thrown in AsyncEventEmitter.AsyncIterator. Got ${err}`);\n\t\t\t\t\t}\n\n\t\t\t\t\terror = err;\n\t\t\t\t\temitter.off(eventName, eventHandler);\n\t\t\t\t\temitter.off('error', errorHandler);\n\t\t\t\t},\n\n\t\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\t\treturn this;\n\t\t\t\t}\n\t\t\t},\n\t\t\tAsyncIteratorPrototype\n\t\t);\n\n\t\temitter.on(eventName, eventHandler);\n\t\tif (eventName !== 'error') {\n\t\t\temitter.on('error', errorHandler);\n\t\t}\n\n\t\tif (signal) {\n\t\t\teventTargetAgnosticAddListener(signal, 'abort', abortListener);\n\t\t}\n\n\t\treturn iterator;\n\t}\n}\n\nexport interface AsyncEventEmitterPredefinedEvents {\n\tnewListener: [eventName: string | symbol, listener: (...args: any[]) => Awaitable];\n\tremoveListener: [eventName: string | symbol, listener: (...args: any[]) => Awaitable];\n}\n\ninterface WrappedOnceState {\n\tlistener: (...args: Args) => Awaitable;\n\tfired: boolean;\n\teventName: string | symbol;\n\teventEmitter: AsyncEventEmitter;\n\twrapFn: (...args: Args) => Awaitable;\n}\n\nexport interface WrappedOnce {\n\t(...args: Args): Awaitable;\n\tlistener: (...args: Args) => Awaitable;\n\t_hasWarnedAboutMaxListeners?: boolean;\n}\n\nexport interface Listener {\n\t(...args: Args): Awaitable;\n\tlistener: (...args: Args) => Awaitable;\n\t_hasWarnedAboutMaxListeners?: boolean;\n}\n\nexport type Awaitable = T | Promise;\n\nexport interface AbortableMethods {\n\tsignal?: AbortSignal;\n}\n\n// @ts-ignore Not all paths returning is fine just fine:tm:\nfunction onceWrapper(this: WrappedOnceState) {\n\tif (!this.fired) {\n\t\tthis.eventEmitter.removeListener(this.eventName, this.wrapFn);\n\t\tthis.fired = true;\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tif (arguments.length === 0) {\n\t\t\t// @ts-expect-error Types can be hell\n\t\t\treturn this.listener.call(this.eventEmitter);\n\t\t}\n\n\t\t// eslint-disable-next-line prefer-rest-params\n\t\treturn this.listener.apply(this.eventEmitter, arguments as unknown as Args);\n\t}\n}\n\n/**\n * A TypeScript not-compliant way of accessing AbortSignal#reason\n * Because DOM types have it, NodeJS types don't. -w-\n */\nfunction getReason(signal: any) {\n\treturn signal?.reason;\n}\n\nfunction eventTargetAgnosticRemoveListener(emitter: any, name: PropertyKey, listener: (...args: unknown[]) => any, flags?: InternalAgnosticFlags) {\n\tif (typeof emitter.off === 'function') {\n\t\temitter.off(name, listener);\n\t} else if (typeof emitter.removeEventListener === 'function') {\n\t\temitter.removeEventListener(name, listener, flags);\n\t}\n}\n\nfunction eventTargetAgnosticAddListener(emitter: any, name: string | symbol, listener: (...args: unknown[]) => any, flags?: InternalAgnosticFlags) {\n\tif (typeof emitter.on === 'function') {\n\t\tif (flags?.once) {\n\t\t\temitter.once!(name, listener);\n\t\t} else {\n\t\t\temitter.on(name, listener);\n\t\t}\n\t} else if (typeof emitter.addEventListener === 'function') {\n\t\temitter.addEventListener(name, listener, flags);\n\t}\n}\n\ninterface InternalAgnosticFlags {\n\tonce?: boolean;\n}\n\n// eslint-disable-next-line func-names, @typescript-eslint/no-empty-function\nconst AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype);\n\nfunction createIterResult(value: unknown, done: boolean) {\n\treturn { value, done };\n}\n\nexport interface AbortErrorOptions {\n\tcause?: unknown;\n}\n\nexport class AbortError extends Error {\n\tpublic readonly code = 'ABORT_ERR';\n\tpublic override readonly name = 'AbortError';\n\n\tpublic constructor(message = 'The operation was aborted', options: AbortErrorOptions | undefined = undefined) {\n\t\tif (options !== undefined && typeof options !== 'object') {\n\t\t\tthrow new TypeError(`Failed to create AbortError: options is not an object or undefined`);\n\t\t}\n\n\t\tsuper(message, options);\n\t}\n}\n\nfunction handleMaybeAsync(emitter: AsyncEventEmitter, result: any) {\n\ttry {\n\t\tconst fin = result.finally;\n\n\t\tif (typeof fin === 'function') {\n\t\t\tconst promiseId = String(++emitter['_wrapperId']);\n\t\t\temitter['_internalPromiseMap'].set(promiseId, result);\n\t\t\tfin.call(result, function final() {\n\t\t\t\temitter['_internalPromiseMap'].delete(promiseId);\n\t\t\t});\n\t\t}\n\t} catch (err) {\n\t\temitter.emit('error', err);\n\t}\n}\n"],"mappings":";;;;AACA,SAAS,iBAAiB,OAA0E;AACnG,MAAI,OAAO,UAAU,YAAY;AAChC,UAAM,IAAI,UAAU,sDAAsD,OAAO,OAAO;AAAA,EACzF;AACD;AAJS;AAMT,SAAS,oBAAoB,OAA0D;AAEtF,MAAI,SAAS,EAAE,iBAAiB,cAAc;AAC7C,UAAM,IAAI,UAAU,sDAAsD,OAAO;AAAA,EAClF;AACD;AALS;AAQT,SAAS,UAAU,MAAiB,OAAe;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ACN,cAAQ,GAAG,MAAM,QAAQ;AAAA,IAC1B;AAAA,EACD,WAAW,OAAO,QAAQ,qBAAqB,YAAY;AAC1D,YAAQ,iBAAiB,MAAM,UAAU,KAAK;AAAA,EAC/C;AACD;AAVS;AAiBT,IAAM,yBAAyB,OAAO,eAAe,OAAO,eAAe,mBAAmB;AAAC,CAAC,EAAE,SAAS;AAE3G,SAAS,iBAAiB,OAAgB,MAAe;AACxD,SAAO,EAAE,OAAO,KAAK;AACtB;AAFS;AAQF,IAAM,aAAN,cAAyB,MAAM;AAAA,EAI9B,YAAY,UAAU,6BAA6B,UAAyC,QAAW;AAC7G,QAAI,YAAY,UAAa,OAAO,YAAY,UAAU;AACzD,YAAM,IAAI,UAAU,oEAAoE;AAAA,IACzF;AAEA,UAAM,SAAS,OAAO;AARvB,SAAgB,OAAO;AACvB,SAAyB,OAAO;AAAA,EAQhC;AACD;AAXa;AAab,SAAS,iBAAiB,SAAiC,QAAa;AACvE,MAAI;AACH,UAAM,MAAM,OAAO;AAEnB,QAAI,OAAO,QAAQ,YAAY;AAC9B,YAAM,YAAY,OAAO,EAAE,QAAQ,YAAY,CAAC;AAChD,cAAQ,qBAAqB,EAAE,IAAI,WAAW,MAAM;AACpD,UAAI,KAAK,QAAQ,gCAAS,QAAQ;AACjC,gBAAQ,qBAAqB,EAAE,OAAO,SAAS;AAAA,MAChD,GAFiB,QAEhB;AAAA,IACF;AAAA,EACD,SAAS,KAAP;AACD,YAAQ,KAAK,SAAS,GAAG;AAAA,EAC1B;AACD;AAdS;","names":[]} \ No newline at end of file diff --git a/node_modules/@vladfrangu/async_event_emitter/package.json b/node_modules/@vladfrangu/async_event_emitter/package.json new file mode 100644 index 0000000..bb9534f --- /dev/null +++ b/node_modules/@vladfrangu/async_event_emitter/package.json @@ -0,0 +1,107 @@ +{ + "name": "@vladfrangu/async_event_emitter", + "version": "2.2.2", + "description": "An event emitter implementation with async support in mind", + "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, + "author": "Vlad Frangu ", + "license": "MIT", + "scripts": { + "lint": "eslint src tests --ext ts --fix", + "format": "prettier --write \"{src,tests}/**/*.ts\"", + "docs": "typedoc", + "test": "vitest run", + "test:watch": "vitest", + "update": "yarn upgrade-interactive", + "build": "tsup && tsc -b src", + "clean": "node scripts/clean.mjs", + "typecheck": "tsc -p tsconfig.typecheck.json", + "bump": "cliff-jumper", + "check-update": "cliff-jumper --dry-run", + "_postinstall": "husky install .github/husky", + "prepack": "rollup-type-bundler && pinst --disable", + "postpack": "pinst --enable" + }, + "devDependencies": { + "@commitlint/cli": "^17.4.4", + "@commitlint/config-conventional": "^17.4.4", + "@favware/cliff-jumper": "^1.10.0", + "@favware/npm-deprecate": "^1.0.7", + "@favware/rollup-type-bundler": "^2.0.0", + "@sapphire/eslint-config": "^4.3.8", + "@sapphire/prettier-config": "^1.4.5", + "@sapphire/ts-config": "^3.3.4", + "@typescript-eslint/eslint-plugin": "^5.52.0", + "@typescript-eslint/parser": "^5.52.0", + "@vitest/coverage-c8": "^0.28.5", + "cz-conventional-changelog": "^3.3.0", + "eslint": "^8.34.0", + "eslint-config-prettier": "^8.6.0", + "eslint-plugin-prettier": "^4.2.1", + "husky": "^8.0.3", + "lint-staged": "^13.1.2", + "pinst": "^3.0.0", + "prettier": "^2.8.4", + "pretty-quick": "^3.1.3", + "tsup": "^6.6.3", + "typedoc": "^0.23.25", + "typedoc-plugin-mdn-links": "^2.0.2", + "typescript": "^4.9.5", + "vitest": "^0.28.5" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/vladfrangu/async_event_emitter.git" + }, + "files": [ + "dist", + "!dist/*.tsbuildinfo", + "THIRD_PARTY_LICENSE.md" + ], + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + }, + "keywords": [ + "event emitter", + "async", + "event", + "emitter" + ], + "bugs": { + "url": "https://github.com/vladfrangu/async_event_emitter/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" + }, + "prettier": "@sapphire/prettier-config", + "resolutions": { + "ansi-regex": "^5.0.1", + "minimist": "^1.2.6" + }, + "packageManager": "yarn@3.2.1" +} \ No newline at end of file diff --git a/node_modules/openai/node_modules/axios/CHANGELOG.md b/node_modules/axios/CHANGELOG.md similarity index 100% rename from node_modules/openai/node_modules/axios/CHANGELOG.md rename to node_modules/axios/CHANGELOG.md diff --git a/node_modules/openai/node_modules/axios/LICENSE b/node_modules/axios/LICENSE similarity index 100% rename from node_modules/openai/node_modules/axios/LICENSE rename to node_modules/axios/LICENSE diff --git a/node_modules/openai/node_modules/axios/README.md b/node_modules/axios/README.md similarity index 100% rename from node_modules/openai/node_modules/axios/README.md rename to node_modules/axios/README.md diff --git a/node_modules/openai/node_modules/axios/SECURITY.md b/node_modules/axios/SECURITY.md similarity index 100% rename from node_modules/openai/node_modules/axios/SECURITY.md rename to node_modules/axios/SECURITY.md diff --git a/node_modules/openai/node_modules/axios/UPGRADE_GUIDE.md b/node_modules/axios/UPGRADE_GUIDE.md similarity index 100% rename from node_modules/openai/node_modules/axios/UPGRADE_GUIDE.md rename to node_modules/axios/UPGRADE_GUIDE.md diff --git a/node_modules/openai/node_modules/axios/dist/axios.js b/node_modules/axios/dist/axios.js similarity index 100% rename from node_modules/openai/node_modules/axios/dist/axios.js rename to node_modules/axios/dist/axios.js diff --git a/node_modules/openai/node_modules/axios/dist/axios.map b/node_modules/axios/dist/axios.map similarity index 100% rename from node_modules/openai/node_modules/axios/dist/axios.map rename to node_modules/axios/dist/axios.map diff --git a/node_modules/openai/node_modules/axios/dist/axios.min.js b/node_modules/axios/dist/axios.min.js similarity index 100% rename from node_modules/openai/node_modules/axios/dist/axios.min.js rename to node_modules/axios/dist/axios.min.js diff --git a/node_modules/openai/node_modules/axios/dist/axios.min.map b/node_modules/axios/dist/axios.min.map similarity index 100% rename from node_modules/openai/node_modules/axios/dist/axios.min.map rename to node_modules/axios/dist/axios.min.map diff --git a/node_modules/openai/node_modules/axios/index.d.ts b/node_modules/axios/index.d.ts similarity index 100% rename from node_modules/openai/node_modules/axios/index.d.ts rename to node_modules/axios/index.d.ts diff --git a/node_modules/openai/node_modules/axios/index.js b/node_modules/axios/index.js similarity index 100% rename from node_modules/openai/node_modules/axios/index.js rename to node_modules/axios/index.js diff --git a/node_modules/openai/node_modules/axios/lib/adapters/README.md b/node_modules/axios/lib/adapters/README.md similarity index 100% rename from node_modules/openai/node_modules/axios/lib/adapters/README.md rename to node_modules/axios/lib/adapters/README.md diff --git a/node_modules/openai/node_modules/axios/lib/adapters/http.js b/node_modules/axios/lib/adapters/http.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/adapters/http.js rename to node_modules/axios/lib/adapters/http.js diff --git a/node_modules/openai/node_modules/axios/lib/adapters/xhr.js b/node_modules/axios/lib/adapters/xhr.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/adapters/xhr.js rename to node_modules/axios/lib/adapters/xhr.js diff --git a/node_modules/openai/node_modules/axios/lib/axios.js b/node_modules/axios/lib/axios.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/axios.js rename to node_modules/axios/lib/axios.js diff --git a/node_modules/openai/node_modules/axios/lib/cancel/Cancel.js b/node_modules/axios/lib/cancel/Cancel.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/cancel/Cancel.js rename to node_modules/axios/lib/cancel/Cancel.js diff --git a/node_modules/openai/node_modules/axios/lib/cancel/CancelToken.js b/node_modules/axios/lib/cancel/CancelToken.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/cancel/CancelToken.js rename to node_modules/axios/lib/cancel/CancelToken.js diff --git a/node_modules/openai/node_modules/axios/lib/cancel/isCancel.js b/node_modules/axios/lib/cancel/isCancel.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/cancel/isCancel.js rename to node_modules/axios/lib/cancel/isCancel.js diff --git a/node_modules/openai/node_modules/axios/lib/core/Axios.js b/node_modules/axios/lib/core/Axios.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/Axios.js rename to node_modules/axios/lib/core/Axios.js diff --git a/node_modules/openai/node_modules/axios/lib/core/InterceptorManager.js b/node_modules/axios/lib/core/InterceptorManager.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/InterceptorManager.js rename to node_modules/axios/lib/core/InterceptorManager.js diff --git a/node_modules/openai/node_modules/axios/lib/core/README.md b/node_modules/axios/lib/core/README.md similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/README.md rename to node_modules/axios/lib/core/README.md diff --git a/node_modules/openai/node_modules/axios/lib/core/buildFullPath.js b/node_modules/axios/lib/core/buildFullPath.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/buildFullPath.js rename to node_modules/axios/lib/core/buildFullPath.js diff --git a/node_modules/openai/node_modules/axios/lib/core/createError.js b/node_modules/axios/lib/core/createError.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/createError.js rename to node_modules/axios/lib/core/createError.js diff --git a/node_modules/openai/node_modules/axios/lib/core/dispatchRequest.js b/node_modules/axios/lib/core/dispatchRequest.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/dispatchRequest.js rename to node_modules/axios/lib/core/dispatchRequest.js diff --git a/node_modules/openai/node_modules/axios/lib/core/enhanceError.js b/node_modules/axios/lib/core/enhanceError.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/enhanceError.js rename to node_modules/axios/lib/core/enhanceError.js diff --git a/node_modules/openai/node_modules/axios/lib/core/mergeConfig.js b/node_modules/axios/lib/core/mergeConfig.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/mergeConfig.js rename to node_modules/axios/lib/core/mergeConfig.js diff --git a/node_modules/openai/node_modules/axios/lib/core/settle.js b/node_modules/axios/lib/core/settle.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/settle.js rename to node_modules/axios/lib/core/settle.js diff --git a/node_modules/openai/node_modules/axios/lib/core/transformData.js b/node_modules/axios/lib/core/transformData.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/core/transformData.js rename to node_modules/axios/lib/core/transformData.js diff --git a/node_modules/openai/node_modules/axios/lib/defaults/index.js b/node_modules/axios/lib/defaults/index.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/defaults/index.js rename to node_modules/axios/lib/defaults/index.js diff --git a/node_modules/openai/node_modules/axios/lib/defaults/transitional.js b/node_modules/axios/lib/defaults/transitional.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/defaults/transitional.js rename to node_modules/axios/lib/defaults/transitional.js diff --git a/node_modules/openai/node_modules/axios/lib/env/README.md b/node_modules/axios/lib/env/README.md similarity index 100% rename from node_modules/openai/node_modules/axios/lib/env/README.md rename to node_modules/axios/lib/env/README.md diff --git a/node_modules/openai/node_modules/axios/lib/env/data.js b/node_modules/axios/lib/env/data.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/env/data.js rename to node_modules/axios/lib/env/data.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/README.md b/node_modules/axios/lib/helpers/README.md similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/README.md rename to node_modules/axios/lib/helpers/README.md diff --git a/node_modules/openai/node_modules/axios/lib/helpers/bind.js b/node_modules/axios/lib/helpers/bind.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/bind.js rename to node_modules/axios/lib/helpers/bind.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/buildURL.js b/node_modules/axios/lib/helpers/buildURL.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/buildURL.js rename to node_modules/axios/lib/helpers/buildURL.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/combineURLs.js b/node_modules/axios/lib/helpers/combineURLs.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/combineURLs.js rename to node_modules/axios/lib/helpers/combineURLs.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/cookies.js b/node_modules/axios/lib/helpers/cookies.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/cookies.js rename to node_modules/axios/lib/helpers/cookies.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/deprecatedMethod.js b/node_modules/axios/lib/helpers/deprecatedMethod.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/deprecatedMethod.js rename to node_modules/axios/lib/helpers/deprecatedMethod.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/isAbsoluteURL.js b/node_modules/axios/lib/helpers/isAbsoluteURL.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/isAbsoluteURL.js rename to node_modules/axios/lib/helpers/isAbsoluteURL.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/isAxiosError.js b/node_modules/axios/lib/helpers/isAxiosError.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/isAxiosError.js rename to node_modules/axios/lib/helpers/isAxiosError.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/isURLSameOrigin.js b/node_modules/axios/lib/helpers/isURLSameOrigin.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/isURLSameOrigin.js rename to node_modules/axios/lib/helpers/isURLSameOrigin.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/normalizeHeaderName.js b/node_modules/axios/lib/helpers/normalizeHeaderName.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/normalizeHeaderName.js rename to node_modules/axios/lib/helpers/normalizeHeaderName.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/parseHeaders.js b/node_modules/axios/lib/helpers/parseHeaders.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/parseHeaders.js rename to node_modules/axios/lib/helpers/parseHeaders.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/spread.js b/node_modules/axios/lib/helpers/spread.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/spread.js rename to node_modules/axios/lib/helpers/spread.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/toFormData.js b/node_modules/axios/lib/helpers/toFormData.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/toFormData.js rename to node_modules/axios/lib/helpers/toFormData.js diff --git a/node_modules/openai/node_modules/axios/lib/helpers/validator.js b/node_modules/axios/lib/helpers/validator.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/helpers/validator.js rename to node_modules/axios/lib/helpers/validator.js diff --git a/node_modules/openai/node_modules/axios/lib/utils.js b/node_modules/axios/lib/utils.js similarity index 100% rename from node_modules/openai/node_modules/axios/lib/utils.js rename to node_modules/axios/lib/utils.js diff --git a/node_modules/openai/node_modules/axios/package.json b/node_modules/axios/package.json similarity index 100% rename from node_modules/openai/node_modules/axios/package.json rename to node_modules/axios/package.json diff --git a/node_modules/openai/node_modules/axios/tsconfig.json b/node_modules/axios/tsconfig.json similarity index 100% rename from node_modules/openai/node_modules/axios/tsconfig.json rename to node_modules/axios/tsconfig.json diff --git a/node_modules/openai/node_modules/axios/tslint.json b/node_modules/axios/tslint.json similarity index 100% rename from node_modules/openai/node_modules/axios/tslint.json rename to node_modules/axios/tslint.json diff --git a/node_modules/core-util-is/float.patch b/node_modules/core-util-is/float.patch deleted file mode 100644 index a06d5c0..0000000 --- a/node_modules/core-util-is/float.patch +++ /dev/null @@ -1,604 +0,0 @@ -diff --git a/lib/util.js b/lib/util.js -index a03e874..9074e8e 100644 ---- a/lib/util.js -+++ b/lib/util.js -@@ -19,430 +19,6 @@ - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - --var formatRegExp = /%[sdj%]/g; --exports.format = function(f) { -- if (!isString(f)) { -- var objects = []; -- for (var i = 0; i < arguments.length; i++) { -- objects.push(inspect(arguments[i])); -- } -- return objects.join(' '); -- } -- -- var i = 1; -- var args = arguments; -- var len = args.length; -- var str = String(f).replace(formatRegExp, function(x) { -- if (x === '%%') return '%'; -- if (i >= len) return x; -- switch (x) { -- case '%s': return String(args[i++]); -- case '%d': return Number(args[i++]); -- case '%j': -- try { -- return JSON.stringify(args[i++]); -- } catch (_) { -- return '[Circular]'; -- } -- default: -- return x; -- } -- }); -- for (var x = args[i]; i < len; x = args[++i]) { -- if (isNull(x) || !isObject(x)) { -- str += ' ' + x; -- } else { -- str += ' ' + inspect(x); -- } -- } -- return str; --}; -- -- --// Mark that a method should not be used. --// Returns a modified function which warns once by default. --// If --no-deprecation is set, then it is a no-op. --exports.deprecate = function(fn, msg) { -- // Allow for deprecating things in the process of starting up. -- if (isUndefined(global.process)) { -- return function() { -- return exports.deprecate(fn, msg).apply(this, arguments); -- }; -- } -- -- if (process.noDeprecation === true) { -- return fn; -- } -- -- var warned = false; -- function deprecated() { -- if (!warned) { -- if (process.throwDeprecation) { -- throw new Error(msg); -- } else if (process.traceDeprecation) { -- console.trace(msg); -- } else { -- console.error(msg); -- } -- warned = true; -- } -- return fn.apply(this, arguments); -- } -- -- return deprecated; --}; -- -- --var debugs = {}; --var debugEnviron; --exports.debuglog = function(set) { -- if (isUndefined(debugEnviron)) -- debugEnviron = process.env.NODE_DEBUG || ''; -- set = set.toUpperCase(); -- if (!debugs[set]) { -- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { -- var pid = process.pid; -- debugs[set] = function() { -- var msg = exports.format.apply(exports, arguments); -- console.error('%s %d: %s', set, pid, msg); -- }; -- } else { -- debugs[set] = function() {}; -- } -- } -- return debugs[set]; --}; -- -- --/** -- * Echos the value of a value. Trys to print the value out -- * in the best way possible given the different types. -- * -- * @param {Object} obj The object to print out. -- * @param {Object} opts Optional options object that alters the output. -- */ --/* legacy: obj, showHidden, depth, colors*/ --function inspect(obj, opts) { -- // default options -- var ctx = { -- seen: [], -- stylize: stylizeNoColor -- }; -- // legacy... -- if (arguments.length >= 3) ctx.depth = arguments[2]; -- if (arguments.length >= 4) ctx.colors = arguments[3]; -- if (isBoolean(opts)) { -- // legacy... -- ctx.showHidden = opts; -- } else if (opts) { -- // got an "options" object -- exports._extend(ctx, opts); -- } -- // set default options -- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; -- if (isUndefined(ctx.depth)) ctx.depth = 2; -- if (isUndefined(ctx.colors)) ctx.colors = false; -- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; -- if (ctx.colors) ctx.stylize = stylizeWithColor; -- return formatValue(ctx, obj, ctx.depth); --} --exports.inspect = inspect; -- -- --// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics --inspect.colors = { -- 'bold' : [1, 22], -- 'italic' : [3, 23], -- 'underline' : [4, 24], -- 'inverse' : [7, 27], -- 'white' : [37, 39], -- 'grey' : [90, 39], -- 'black' : [30, 39], -- 'blue' : [34, 39], -- 'cyan' : [36, 39], -- 'green' : [32, 39], -- 'magenta' : [35, 39], -- 'red' : [31, 39], -- 'yellow' : [33, 39] --}; -- --// Don't use 'blue' not visible on cmd.exe --inspect.styles = { -- 'special': 'cyan', -- 'number': 'yellow', -- 'boolean': 'yellow', -- 'undefined': 'grey', -- 'null': 'bold', -- 'string': 'green', -- 'date': 'magenta', -- // "name": intentionally not styling -- 'regexp': 'red' --}; -- -- --function stylizeWithColor(str, styleType) { -- var style = inspect.styles[styleType]; -- -- if (style) { -- return '\u001b[' + inspect.colors[style][0] + 'm' + str + -- '\u001b[' + inspect.colors[style][1] + 'm'; -- } else { -- return str; -- } --} -- -- --function stylizeNoColor(str, styleType) { -- return str; --} -- -- --function arrayToHash(array) { -- var hash = {}; -- -- array.forEach(function(val, idx) { -- hash[val] = true; -- }); -- -- return hash; --} -- -- --function formatValue(ctx, value, recurseTimes) { -- // Provide a hook for user-specified inspect functions. -- // Check that value is an object with an inspect function on it -- if (ctx.customInspect && -- value && -- isFunction(value.inspect) && -- // Filter out the util module, it's inspect function is special -- value.inspect !== exports.inspect && -- // Also filter out any prototype objects using the circular check. -- !(value.constructor && value.constructor.prototype === value)) { -- var ret = value.inspect(recurseTimes, ctx); -- if (!isString(ret)) { -- ret = formatValue(ctx, ret, recurseTimes); -- } -- return ret; -- } -- -- // Primitive types cannot have properties -- var primitive = formatPrimitive(ctx, value); -- if (primitive) { -- return primitive; -- } -- -- // Look up the keys of the object. -- var keys = Object.keys(value); -- var visibleKeys = arrayToHash(keys); -- -- if (ctx.showHidden) { -- keys = Object.getOwnPropertyNames(value); -- } -- -- // Some type of object without properties can be shortcutted. -- if (keys.length === 0) { -- if (isFunction(value)) { -- var name = value.name ? ': ' + value.name : ''; -- return ctx.stylize('[Function' + name + ']', 'special'); -- } -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } -- if (isDate(value)) { -- return ctx.stylize(Date.prototype.toString.call(value), 'date'); -- } -- if (isError(value)) { -- return formatError(value); -- } -- } -- -- var base = '', array = false, braces = ['{', '}']; -- -- // Make Array say that they are Array -- if (isArray(value)) { -- array = true; -- braces = ['[', ']']; -- } -- -- // Make functions say that they are functions -- if (isFunction(value)) { -- var n = value.name ? ': ' + value.name : ''; -- base = ' [Function' + n + ']'; -- } -- -- // Make RegExps say that they are RegExps -- if (isRegExp(value)) { -- base = ' ' + RegExp.prototype.toString.call(value); -- } -- -- // Make dates with properties first say the date -- if (isDate(value)) { -- base = ' ' + Date.prototype.toUTCString.call(value); -- } -- -- // Make error with message first say the error -- if (isError(value)) { -- base = ' ' + formatError(value); -- } -- -- if (keys.length === 0 && (!array || value.length == 0)) { -- return braces[0] + base + braces[1]; -- } -- -- if (recurseTimes < 0) { -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } else { -- return ctx.stylize('[Object]', 'special'); -- } -- } -- -- ctx.seen.push(value); -- -- var output; -- if (array) { -- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); -- } else { -- output = keys.map(function(key) { -- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); -- }); -- } -- -- ctx.seen.pop(); -- -- return reduceToSingleString(output, base, braces); --} -- -- --function formatPrimitive(ctx, value) { -- if (isUndefined(value)) -- return ctx.stylize('undefined', 'undefined'); -- if (isString(value)) { -- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') -- .replace(/'/g, "\\'") -- .replace(/\\"/g, '"') + '\''; -- return ctx.stylize(simple, 'string'); -- } -- if (isNumber(value)) { -- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, -- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . -- if (value === 0 && 1 / value < 0) -- return ctx.stylize('-0', 'number'); -- return ctx.stylize('' + value, 'number'); -- } -- if (isBoolean(value)) -- return ctx.stylize('' + value, 'boolean'); -- // For some reason typeof null is "object", so special case here. -- if (isNull(value)) -- return ctx.stylize('null', 'null'); --} -- -- --function formatError(value) { -- return '[' + Error.prototype.toString.call(value) + ']'; --} -- -- --function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { -- var output = []; -- for (var i = 0, l = value.length; i < l; ++i) { -- if (hasOwnProperty(value, String(i))) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- String(i), true)); -- } else { -- output.push(''); -- } -- } -- keys.forEach(function(key) { -- if (!key.match(/^\d+$/)) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- key, true)); -- } -- }); -- return output; --} -- -- --function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { -- var name, str, desc; -- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; -- if (desc.get) { -- if (desc.set) { -- str = ctx.stylize('[Getter/Setter]', 'special'); -- } else { -- str = ctx.stylize('[Getter]', 'special'); -- } -- } else { -- if (desc.set) { -- str = ctx.stylize('[Setter]', 'special'); -- } -- } -- if (!hasOwnProperty(visibleKeys, key)) { -- name = '[' + key + ']'; -- } -- if (!str) { -- if (ctx.seen.indexOf(desc.value) < 0) { -- if (isNull(recurseTimes)) { -- str = formatValue(ctx, desc.value, null); -- } else { -- str = formatValue(ctx, desc.value, recurseTimes - 1); -- } -- if (str.indexOf('\n') > -1) { -- if (array) { -- str = str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n').substr(2); -- } else { -- str = '\n' + str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n'); -- } -- } -- } else { -- str = ctx.stylize('[Circular]', 'special'); -- } -- } -- if (isUndefined(name)) { -- if (array && key.match(/^\d+$/)) { -- return str; -- } -- name = JSON.stringify('' + key); -- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { -- name = name.substr(1, name.length - 2); -- name = ctx.stylize(name, 'name'); -- } else { -- name = name.replace(/'/g, "\\'") -- .replace(/\\"/g, '"') -- .replace(/(^"|"$)/g, "'"); -- name = ctx.stylize(name, 'string'); -- } -- } -- -- return name + ': ' + str; --} -- -- --function reduceToSingleString(output, base, braces) { -- var numLinesEst = 0; -- var length = output.reduce(function(prev, cur) { -- numLinesEst++; -- if (cur.indexOf('\n') >= 0) numLinesEst++; -- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; -- }, 0); -- -- if (length > 60) { -- return braces[0] + -- (base === '' ? '' : base + '\n ') + -- ' ' + -- output.join(',\n ') + -- ' ' + -- braces[1]; -- } -- -- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; --} -- -- - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { -@@ -522,166 +98,10 @@ function isPrimitive(arg) { - exports.isPrimitive = isPrimitive; - - function isBuffer(arg) { -- return arg instanceof Buffer; -+ return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); --} -- -- --function pad(n) { -- return n < 10 ? '0' + n.toString(10) : n.toString(10); --} -- -- --var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', -- 'Oct', 'Nov', 'Dec']; -- --// 26 Feb 16:19:34 --function timestamp() { -- var d = new Date(); -- var time = [pad(d.getHours()), -- pad(d.getMinutes()), -- pad(d.getSeconds())].join(':'); -- return [d.getDate(), months[d.getMonth()], time].join(' '); --} -- -- --// log is just a thin wrapper to console.log that prepends a timestamp --exports.log = function() { -- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); --}; -- -- --/** -- * Inherit the prototype methods from one constructor into another. -- * -- * The Function.prototype.inherits from lang.js rewritten as a standalone -- * function (not on Function.prototype). NOTE: If this file is to be loaded -- * during bootstrapping this function needs to be rewritten using some native -- * functions as prototype setup using normal JavaScript does not work as -- * expected during bootstrapping (see mirror.js in r114903). -- * -- * @param {function} ctor Constructor function which needs to inherit the -- * prototype. -- * @param {function} superCtor Constructor function to inherit prototype from. -- */ --exports.inherits = function(ctor, superCtor) { -- ctor.super_ = superCtor; -- ctor.prototype = Object.create(superCtor.prototype, { -- constructor: { -- value: ctor, -- enumerable: false, -- writable: true, -- configurable: true -- } -- }); --}; -- --exports._extend = function(origin, add) { -- // Don't do anything if add isn't an object -- if (!add || !isObject(add)) return origin; -- -- var keys = Object.keys(add); -- var i = keys.length; -- while (i--) { -- origin[keys[i]] = add[keys[i]]; -- } -- return origin; --}; -- --function hasOwnProperty(obj, prop) { -- return Object.prototype.hasOwnProperty.call(obj, prop); --} -- -- --// Deprecated old stuff. -- --exports.p = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- console.error(exports.inspect(arguments[i])); -- } --}, 'util.p: Use console.error() instead'); -- -- --exports.exec = exports.deprecate(function() { -- return require('child_process').exec.apply(this, arguments); --}, 'util.exec is now called `child_process.exec`.'); -- -- --exports.print = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(String(arguments[i])); -- } --}, 'util.print: Use console.log instead'); -- -- --exports.puts = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(arguments[i] + '\n'); -- } --}, 'util.puts: Use console.log instead'); -- -- --exports.debug = exports.deprecate(function(x) { -- process.stderr.write('DEBUG: ' + x + '\n'); --}, 'util.debug: Use console.error instead'); -- -- --exports.error = exports.deprecate(function(x) { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stderr.write(arguments[i] + '\n'); -- } --}, 'util.error: Use console.error instead'); -- -- --exports.pump = exports.deprecate(function(readStream, writeStream, callback) { -- var callbackCalled = false; -- -- function call(a, b, c) { -- if (callback && !callbackCalled) { -- callback(a, b, c); -- callbackCalled = true; -- } -- } -- -- readStream.addListener('data', function(chunk) { -- if (writeStream.write(chunk) === false) readStream.pause(); -- }); -- -- writeStream.addListener('drain', function() { -- readStream.resume(); -- }); -- -- readStream.addListener('end', function() { -- writeStream.end(); -- }); -- -- readStream.addListener('close', function() { -- call(); -- }); -- -- readStream.addListener('error', function(err) { -- writeStream.end(); -- call(err); -- }); -- -- writeStream.addListener('error', function(err) { -- readStream.destroy(); -- call(err); -- }); --}, 'util.pump(): Use readableStream.pipe() instead'); -- -- --var uv; --exports._errnoException = function(err, syscall) { -- if (isUndefined(uv)) uv = process.binding('uv'); -- var errname = uv.errname(err); -- var e = new Error(syscall + ' ' + errname); -- e.code = errname; -- e.errno = errname; -- e.syscall = syscall; -- return e; --}; -+} \ No newline at end of file diff --git a/node_modules/core-util-is/lib/util.js b/node_modules/core-util-is/lib/util.js index ff4c851..6e5a20d 100644 --- a/node_modules/core-util-is/lib/util.js +++ b/node_modules/core-util-is/lib/util.js @@ -100,7 +100,7 @@ function isPrimitive(arg) { } exports.isPrimitive = isPrimitive; -exports.isBuffer = Buffer.isBuffer; +exports.isBuffer = require('buffer').Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); diff --git a/node_modules/core-util-is/package.json b/node_modules/core-util-is/package.json index 3368e95..b0c51f5 100644 --- a/node_modules/core-util-is/package.json +++ b/node_modules/core-util-is/package.json @@ -1,8 +1,11 @@ { "name": "core-util-is", - "version": "1.0.2", + "version": "1.0.3", "description": "The `util.is*` functions introduced in Node v0.12.", "main": "lib/util.js", + "files": [ + "lib" + ], "repository": { "type": "git", "url": "git://github.com/isaacs/core-util-is" @@ -24,9 +27,12 @@ "url": "https://github.com/isaacs/core-util-is/issues" }, "scripts": { - "test": "tap test.js" + "test": "tap test.js", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" }, "devDependencies": { - "tap": "^2.3.0" + "tap": "^15.0.9" } } diff --git a/node_modules/core-util-is/test.js b/node_modules/core-util-is/test.js deleted file mode 100644 index 1a490c6..0000000 --- a/node_modules/core-util-is/test.js +++ /dev/null @@ -1,68 +0,0 @@ -var assert = require('tap'); - -var t = require('./lib/util'); - -assert.equal(t.isArray([]), true); -assert.equal(t.isArray({}), false); - -assert.equal(t.isBoolean(null), false); -assert.equal(t.isBoolean(true), true); -assert.equal(t.isBoolean(false), true); - -assert.equal(t.isNull(null), true); -assert.equal(t.isNull(undefined), false); -assert.equal(t.isNull(false), false); -assert.equal(t.isNull(), false); - -assert.equal(t.isNullOrUndefined(null), true); -assert.equal(t.isNullOrUndefined(undefined), true); -assert.equal(t.isNullOrUndefined(false), false); -assert.equal(t.isNullOrUndefined(), true); - -assert.equal(t.isNumber(null), false); -assert.equal(t.isNumber('1'), false); -assert.equal(t.isNumber(1), true); - -assert.equal(t.isString(null), false); -assert.equal(t.isString('1'), true); -assert.equal(t.isString(1), false); - -assert.equal(t.isSymbol(null), false); -assert.equal(t.isSymbol('1'), false); -assert.equal(t.isSymbol(1), false); -assert.equal(t.isSymbol(Symbol()), true); - -assert.equal(t.isUndefined(null), false); -assert.equal(t.isUndefined(undefined), true); -assert.equal(t.isUndefined(false), false); -assert.equal(t.isUndefined(), true); - -assert.equal(t.isRegExp(null), false); -assert.equal(t.isRegExp('1'), false); -assert.equal(t.isRegExp(new RegExp()), true); - -assert.equal(t.isObject({}), true); -assert.equal(t.isObject([]), true); -assert.equal(t.isObject(new RegExp()), true); -assert.equal(t.isObject(new Date()), true); - -assert.equal(t.isDate(null), false); -assert.equal(t.isDate('1'), false); -assert.equal(t.isDate(new Date()), true); - -assert.equal(t.isError(null), false); -assert.equal(t.isError({ err: true }), false); -assert.equal(t.isError(new Error()), true); - -assert.equal(t.isFunction(null), false); -assert.equal(t.isFunction({ }), false); -assert.equal(t.isFunction(function() {}), true); - -assert.equal(t.isPrimitive(null), true); -assert.equal(t.isPrimitive(''), true); -assert.equal(t.isPrimitive(0), true); -assert.equal(t.isPrimitive(new Date()), false); - -assert.equal(t.isBuffer(null), false); -assert.equal(t.isBuffer({}), false); -assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/node_modules/discord-api-types/gateway/v10.d.ts b/node_modules/discord-api-types/gateway/v10.d.ts index a75722f..587bbca 100644 --- a/node_modules/discord-api-types/gateway/v10.d.ts +++ b/node_modules/discord-api-types/gateway/v10.d.ts @@ -233,9 +233,9 @@ export declare enum GatewayDispatchEvents { AutoModerationActionExecution = "AUTO_MODERATION_ACTION_EXECUTION", GuildAuditLogEntryCreate = "GUILD_AUDIT_LOG_ENTRY_CREATE" } -export declare type GatewaySendPayload = GatewayHeartbeat | GatewayIdentify | GatewayUpdatePresence | GatewayVoiceStateUpdate | GatewayResume | GatewayRequestGuildMembers; -export declare type GatewayReceivePayload = GatewayHello | GatewayHeartbeatRequest | GatewayHeartbeatAck | GatewayInvalidSession | GatewayReconnect | GatewayDispatchPayload; -export declare type GatewayDispatchPayload = GatewayAutoModerationRuleModifyDispatch | GatewayAutoModerationRuleCreateDispatch | GatewayAutoModerationRuleDeleteDispatch | GatewayAutoModerationActionExecutionDispatch | GatewayApplicationCommandPermissionsUpdateDispatch | GatewayChannelModifyDispatch | GatewayChannelPinsUpdateDispatch | GatewayGuildBanModifyDispatch | GatewayGuildCreateDispatch | GatewayGuildDeleteDispatch | GatewayGuildEmojisUpdateDispatch | GatewayGuildIntegrationsUpdateDispatch | GatewayGuildMemberAddDispatch | GatewayGuildMemberRemoveDispatch | GatewayGuildMembersChunkDispatch | GatewayGuildMemberUpdateDispatch | GatewayGuildModifyDispatch | GatewayGuildRoleDeleteDispatch | GatewayGuildRoleModifyDispatch | GatewayGuildScheduledEventCreateDispatch | GatewayGuildScheduledEventUpdateDispatch | GatewayGuildScheduledEventDeleteDispatch | GatewayGuildScheduledEventUserAddDispatch | GatewayGuildScheduledEventUserRemoveDispatch | GatewayGuildStickersUpdateDispatch | GatewayIntegrationCreateDispatch | GatewayIntegrationDeleteDispatch | GatewayIntegrationUpdateDispatch | GatewayInteractionCreateDispatch | GatewayInviteCreateDispatch | GatewayInviteDeleteDispatch | GatewayMessageCreateDispatch | GatewayMessageDeleteBulkDispatch | GatewayMessageDeleteDispatch | GatewayMessageReactionAddDispatch | GatewayMessageReactionRemoveAllDispatch | GatewayMessageReactionRemoveDispatch | GatewayMessageReactionRemoveEmojiDispatch | GatewayMessageUpdateDispatch | GatewayPresenceUpdateDispatch | GatewayStageInstanceCreateDispatch | GatewayStageInstanceDeleteDispatch | GatewayStageInstanceUpdateDispatch | GatewayReadyDispatch | GatewayResumedDispatch | GatewayThreadListSyncDispatch | GatewayThreadMembersUpdateDispatch | GatewayThreadMemberUpdateDispatch | GatewayThreadModifyDispatch | GatewayTypingStartDispatch | GatewayUserUpdateDispatch | GatewayVoiceServerUpdateDispatch | GatewayVoiceStateUpdateDispatch | GatewayWebhooksUpdateDispatch; +export type GatewaySendPayload = GatewayHeartbeat | GatewayIdentify | GatewayUpdatePresence | GatewayVoiceStateUpdate | GatewayResume | GatewayRequestGuildMembers; +export type GatewayReceivePayload = GatewayHello | GatewayHeartbeatRequest | GatewayHeartbeatAck | GatewayInvalidSession | GatewayReconnect | GatewayDispatchPayload; +export type GatewayDispatchPayload = GatewayAutoModerationRuleModifyDispatch | GatewayAutoModerationRuleCreateDispatch | GatewayAutoModerationRuleDeleteDispatch | GatewayAutoModerationActionExecutionDispatch | GatewayApplicationCommandPermissionsUpdateDispatch | GatewayChannelModifyDispatch | GatewayChannelPinsUpdateDispatch | GatewayGuildBanModifyDispatch | GatewayGuildCreateDispatch | GatewayGuildDeleteDispatch | GatewayGuildEmojisUpdateDispatch | GatewayGuildIntegrationsUpdateDispatch | GatewayGuildMemberAddDispatch | GatewayGuildMemberRemoveDispatch | GatewayGuildMembersChunkDispatch | GatewayGuildMemberUpdateDispatch | GatewayGuildModifyDispatch | GatewayGuildRoleDeleteDispatch | GatewayGuildRoleModifyDispatch | GatewayGuildScheduledEventCreateDispatch | GatewayGuildScheduledEventUpdateDispatch | GatewayGuildScheduledEventDeleteDispatch | GatewayGuildScheduledEventUserAddDispatch | GatewayGuildScheduledEventUserRemoveDispatch | GatewayGuildStickersUpdateDispatch | GatewayIntegrationCreateDispatch | GatewayIntegrationDeleteDispatch | GatewayIntegrationUpdateDispatch | GatewayInteractionCreateDispatch | GatewayInviteCreateDispatch | GatewayInviteDeleteDispatch | GatewayMessageCreateDispatch | GatewayMessageDeleteBulkDispatch | GatewayMessageDeleteDispatch | GatewayMessageReactionAddDispatch | GatewayMessageReactionRemoveAllDispatch | GatewayMessageReactionRemoveDispatch | GatewayMessageReactionRemoveEmojiDispatch | GatewayMessageUpdateDispatch | GatewayPresenceUpdateDispatch | GatewayStageInstanceCreateDispatch | GatewayStageInstanceDeleteDispatch | GatewayStageInstanceUpdateDispatch | GatewayReadyDispatch | GatewayResumedDispatch | GatewayThreadListSyncDispatch | GatewayThreadMembersUpdateDispatch | GatewayThreadMemberUpdateDispatch | GatewayThreadModifyDispatch | GatewayTypingStartDispatch | GatewayUserUpdateDispatch | GatewayVoiceServerUpdateDispatch | GatewayVoiceStateUpdateDispatch | GatewayWebhooksUpdateDispatch | GatewayGuildAuditLogEntryCreateDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#hello */ @@ -276,7 +276,7 @@ export interface GatewayInvalidSession extends NonDispatchPayload { /** * https://discord.com/developers/docs/topics/gateway-events#invalid-session */ -export declare type GatewayInvalidSessionData = boolean; +export type GatewayInvalidSessionData = boolean; /** * https://discord.com/developers/docs/topics/gateway-events#reconnect */ @@ -287,7 +287,7 @@ export interface GatewayReconnect extends NonDispatchPayload { /** * https://discord.com/developers/docs/topics/gateway-events#ready */ -export declare type GatewayReadyDispatch = DataPayload; +export type GatewayReadyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#ready */ @@ -334,47 +334,47 @@ export interface GatewayReadyDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#resumed */ -export declare type GatewayResumedDispatch = DataPayload; +export type GatewayResumedDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete */ -export declare type GatewayAutoModerationRuleModifyDispatch = DataPayload; +export type GatewayAutoModerationRuleModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete */ -export declare type GatewayAutoModerationRuleModifyDispatchData = APIAutoModerationRule; +export type GatewayAutoModerationRuleModifyDispatchData = APIAutoModerationRule; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create */ -export declare type GatewayAutoModerationRuleCreateDispatch = GatewayAutoModerationRuleModifyDispatch; +export type GatewayAutoModerationRuleCreateDispatch = GatewayAutoModerationRuleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create */ -export declare type GatewayAutoModerationRuleCreateDispatchData = GatewayAutoModerationRuleModifyDispatchData; +export type GatewayAutoModerationRuleCreateDispatchData = GatewayAutoModerationRuleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update */ -export declare type GatewayAutoModerationRuleUpdateDispatch = GatewayAutoModerationRuleModifyDispatch; +export type GatewayAutoModerationRuleUpdateDispatch = GatewayAutoModerationRuleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update */ -export declare type GatewayAutoModerationRuleUpdateDispatchData = GatewayAutoModerationRuleModifyDispatchData; +export type GatewayAutoModerationRuleUpdateDispatchData = GatewayAutoModerationRuleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete */ -export declare type GatewayAutoModerationRuleDeleteDispatch = GatewayAutoModerationRuleModifyDispatch; +export type GatewayAutoModerationRuleDeleteDispatch = GatewayAutoModerationRuleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete */ -export declare type GatewayAutoModerationRuleDeleteDispatchData = GatewayAutoModerationRuleModifyDispatchData; +export type GatewayAutoModerationRuleDeleteDispatchData = GatewayAutoModerationRuleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-action-execution */ -export declare type GatewayAutoModerationActionExecutionDispatch = DataPayload; +export type GatewayAutoModerationActionExecutionDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-action-execution */ @@ -435,7 +435,7 @@ export interface GatewayAutoModerationActionExecutionDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#application-command-permissions-update */ -export declare type GatewayApplicationCommandPermissionsUpdateDispatch = DataPayload; +export type GatewayApplicationCommandPermissionsUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#application-command-permissions-update */ @@ -462,41 +462,41 @@ export interface GatewayApplicationCommandPermissionsUpdateDispatchData { * https://discord.com/developers/docs/topics/gateway-events#channel-update * https://discord.com/developers/docs/topics/gateway-events#channel-delete */ -export declare type GatewayChannelModifyDispatch = DataPayload; +export type GatewayChannelModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#channel-create * https://discord.com/developers/docs/topics/gateway-events#channel-update * https://discord.com/developers/docs/topics/gateway-events#channel-delete */ -export declare type GatewayChannelModifyDispatchData = APIChannel; +export type GatewayChannelModifyDispatchData = APIChannel; /** * https://discord.com/developers/docs/topics/gateway-events#channel-create */ -export declare type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#channel-create */ -export declare type GatewayChannelCreateDispatchData = GatewayChannelModifyDispatchData; +export type GatewayChannelCreateDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#channel-update */ -export declare type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#channel-update */ -export declare type GatewayChannelUpdateDispatchData = GatewayChannelModifyDispatchData; +export type GatewayChannelUpdateDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#channel-delete */ -export declare type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#channel-delete */ -export declare type GatewayChannelDeleteDispatchData = GatewayChannelModifyDispatchData; +export type GatewayChannelDeleteDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#channel-pins-update */ -export declare type GatewayChannelPinsUpdateDispatch = DataPayload; +export type GatewayChannelPinsUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#channel-pins-update */ @@ -517,15 +517,15 @@ export interface GatewayChannelPinsUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-create */ -export declare type GatewayGuildModifyDispatch = DataPayload; +export type GatewayGuildModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-update */ -export declare type GatewayGuildModifyDispatchData = APIGuild; +export type GatewayGuildModifyDispatchData = APIGuild; /** * https://discord.com/developers/docs/topics/gateway-events#guild-create */ -export declare type GatewayGuildCreateDispatch = DataPayload; +export type GatewayGuildCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-create * https://discord.com/developers/docs/topics/gateway-events#guild-create-guild-create-extra-fields @@ -613,24 +613,24 @@ export interface GatewayGuildCreateDispatchData extends APIGuild { /** * https://discord.com/developers/docs/topics/gateway-events#guild-update */ -export declare type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; +export type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-update */ -export declare type GatewayGuildUpdateDispatchData = GatewayGuildModifyDispatchData; +export type GatewayGuildUpdateDispatchData = GatewayGuildModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-delete */ -export declare type GatewayGuildDeleteDispatch = DataPayload; +export type GatewayGuildDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-delete */ -export declare type GatewayGuildDeleteDispatchData = APIUnavailableGuild; +export type GatewayGuildDeleteDispatchData = APIUnavailableGuild; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-add * https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove */ -export declare type GatewayGuildBanModifyDispatch = DataPayload; +export type GatewayGuildBanModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-add * https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove @@ -650,23 +650,23 @@ export interface GatewayGuildBanModifyDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-add */ -export declare type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; +export type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-add */ -export declare type GatewayGuildBanAddDispatchData = GatewayGuildBanModifyDispatchData; +export type GatewayGuildBanAddDispatchData = GatewayGuildBanModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove */ -export declare type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; +export type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove */ -export declare type GatewayGuildBanRemoveDispatchData = GatewayGuildBanModifyDispatchData; +export type GatewayGuildBanRemoveDispatchData = GatewayGuildBanModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-emojis-update */ -export declare type GatewayGuildEmojisUpdateDispatch = DataPayload; +export type GatewayGuildEmojisUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-emojis-update */ @@ -685,7 +685,7 @@ export interface GatewayGuildEmojisUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-stickers-update */ -export declare type GatewayGuildStickersUpdateDispatch = DataPayload; +export type GatewayGuildStickersUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-stickers-update */ @@ -704,7 +704,7 @@ export interface GatewayGuildStickersUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-integrations-update */ -export declare type GatewayGuildIntegrationsUpdateDispatch = DataPayload; +export type GatewayGuildIntegrationsUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-integrations-update */ @@ -717,7 +717,7 @@ export interface GatewayGuildIntegrationsUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-add */ -export declare type GatewayGuildMemberAddDispatch = DataPayload; +export type GatewayGuildMemberAddDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-add */ @@ -730,7 +730,7 @@ export interface GatewayGuildMemberAddDispatchData extends APIGuildMember { /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-remove */ -export declare type GatewayGuildMemberRemoveDispatch = DataPayload; +export type GatewayGuildMemberRemoveDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-remove */ @@ -749,11 +749,11 @@ export interface GatewayGuildMemberRemoveDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-update */ -export declare type GatewayGuildMemberUpdateDispatch = DataPayload; +export type GatewayGuildMemberUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-update */ -export declare type GatewayGuildMemberUpdateDispatchData = Omit & Partial> & Required> & Nullable> & { +export type GatewayGuildMemberUpdateDispatchData = Omit & Partial> & Required> & Nullable> & { /** * The id of the guild */ @@ -762,7 +762,11 @@ export declare type GatewayGuildMemberUpdateDispatchData = Omit; +export type GatewayGuildMembersChunkDispatch = DataPayload; +/** + * https://discord.com/developers/docs/topics/gateway-events#update-presence + */ +export type GatewayGuildMembersChunkPresence = Omit; /** * https://discord.com/developers/docs/topics/gateway-events#guild-members-chunk */ @@ -794,7 +798,7 @@ export interface GatewayGuildMembersChunkDispatchData { * * See https://discord.com/developers/docs/topics/gateway-events#update-presence */ - presences?: RawGatewayPresenceUpdate[]; + presences?: GatewayGuildMembersChunkPresence[]; /** * The nonce used in the Guild Members Request * @@ -806,7 +810,7 @@ export interface GatewayGuildMembersChunkDispatchData { * https://discord.com/developers/docs/topics/gateway-events#guild-role-create * https://discord.com/developers/docs/topics/gateway-events#guild-role-update */ -export declare type GatewayGuildRoleModifyDispatch = DataPayload; +export type GatewayGuildRoleModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-create * https://discord.com/developers/docs/topics/gateway-events#guild-role-update @@ -826,23 +830,23 @@ export interface GatewayGuildRoleModifyDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-create */ -export declare type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; +export type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-create */ -export declare type GatewayGuildRoleCreateDispatchData = GatewayGuildRoleModifyDispatchData; +export type GatewayGuildRoleCreateDispatchData = GatewayGuildRoleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-update */ -export declare type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; +export type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-update */ -export declare type GatewayGuildRoleUpdateDispatchData = GatewayGuildRoleModifyDispatchData; +export type GatewayGuildRoleUpdateDispatchData = GatewayGuildRoleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-delete */ -export declare type GatewayGuildRoleDeleteDispatch = DataPayload; +export type GatewayGuildRoleDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-delete */ @@ -856,19 +860,19 @@ export interface GatewayGuildRoleDeleteDispatchData { */ role_id: Snowflake; } -export declare type GatewayGuildScheduledEventCreateDispatch = DataPayload; -export declare type GatewayGuildScheduledEventCreateDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventUpdateDispatch = DataPayload; -export declare type GatewayGuildScheduledEventUpdateDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventDeleteDispatch = DataPayload; -export declare type GatewayGuildScheduledEventDeleteDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventUserAddDispatch = DataPayload; +export type GatewayGuildScheduledEventCreateDispatch = DataPayload; +export type GatewayGuildScheduledEventCreateDispatchData = APIGuildScheduledEvent; +export type GatewayGuildScheduledEventUpdateDispatch = DataPayload; +export type GatewayGuildScheduledEventUpdateDispatchData = APIGuildScheduledEvent; +export type GatewayGuildScheduledEventDeleteDispatch = DataPayload; +export type GatewayGuildScheduledEventDeleteDispatchData = APIGuildScheduledEvent; +export type GatewayGuildScheduledEventUserAddDispatch = DataPayload; export interface GatewayGuildScheduledEventUserAddDispatchData { guild_scheduled_event_id: Snowflake; user_id: Snowflake; guild_id: Snowflake; } -export declare type GatewayGuildScheduledEventUserRemoveDispatch = DataPayload; +export type GatewayGuildScheduledEventUserRemoveDispatch = DataPayload; export interface GatewayGuildScheduledEventUserRemoveDispatchData { guild_scheduled_event_id: Snowflake; user_id: Snowflake; @@ -877,27 +881,27 @@ export interface GatewayGuildScheduledEventUserRemoveDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#integration-create */ -export declare type GatewayIntegrationCreateDispatch = DataPayload; +export type GatewayIntegrationCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#integration-create */ -export declare type GatewayIntegrationCreateDispatchData = APIGuildIntegration & { +export type GatewayIntegrationCreateDispatchData = APIGuildIntegration & { guild_id: Snowflake; }; /** * https://discord.com/developers/docs/topics/gateway-events#integration-update */ -export declare type GatewayIntegrationUpdateDispatch = DataPayload; +export type GatewayIntegrationUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#integration-update */ -export declare type GatewayIntegrationUpdateDispatchData = APIGuildIntegration & { +export type GatewayIntegrationUpdateDispatchData = APIGuildIntegration & { guild_id: Snowflake; }; /** * https://discord.com/developers/docs/topics/gateway-events#integration-update */ -export declare type GatewayIntegrationDeleteDispatch = DataPayload; +export type GatewayIntegrationDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#integration-delete */ @@ -918,15 +922,15 @@ export interface GatewayIntegrationDeleteDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#interaction-create */ -export declare type GatewayInteractionCreateDispatch = DataPayload; +export type GatewayInteractionCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#interaction-create */ -export declare type GatewayInteractionCreateDispatchData = APIInteraction; +export type GatewayInteractionCreateDispatchData = APIInteraction; /** * https://discord.com/developers/docs/topics/gateway-events#invite-create */ -export declare type GatewayInviteCreateDispatch = DataPayload; +export type GatewayInviteCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#invite-create */ @@ -991,7 +995,7 @@ export interface GatewayInviteCreateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#invite-delete */ -export declare type GatewayInviteDeleteDispatch = DataPayload; +export type GatewayInviteDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#invite-delete */ @@ -1014,19 +1018,19 @@ export interface GatewayInviteDeleteDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#message-create */ -export declare type GatewayMessageCreateDispatch = DataPayload; +export type GatewayMessageCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-create */ -export declare type GatewayMessageCreateDispatchData = Omit & GatewayMessageEventExtraFields; +export type GatewayMessageCreateDispatchData = Omit & GatewayMessageEventExtraFields; /** * https://discord.com/developers/docs/topics/gateway-events#message-update */ -export declare type GatewayMessageUpdateDispatch = DataPayload; +export type GatewayMessageUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-update */ -export declare type GatewayMessageUpdateDispatchData = Omit, 'mentions'> & GatewayMessageEventExtraFields & { +export type GatewayMessageUpdateDispatchData = Omit, 'mentions'> & GatewayMessageEventExtraFields & { /** * ID of the message */ @@ -1066,7 +1070,7 @@ export interface GatewayMessageEventExtraFields { /** * https://discord.com/developers/docs/topics/gateway-events#message-delete */ -export declare type GatewayMessageDeleteDispatch = DataPayload; +export type GatewayMessageDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-delete */ @@ -1087,7 +1091,7 @@ export interface GatewayMessageDeleteDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#message-delete-bulk */ -export declare type GatewayMessageDeleteBulkDispatch = DataPayload; +export type GatewayMessageDeleteBulkDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-delete-bulk */ @@ -1108,31 +1112,31 @@ export interface GatewayMessageDeleteBulkDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-add */ -export declare type GatewayMessageReactionAddDispatch = ReactionData; +export type GatewayMessageReactionAddDispatch = ReactionData; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-add */ -export declare type GatewayMessageReactionAddDispatchData = GatewayMessageReactionAddDispatch['d']; +export type GatewayMessageReactionAddDispatchData = GatewayMessageReactionAddDispatch['d']; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove */ -export declare type GatewayMessageReactionRemoveDispatch = ReactionData; +export type GatewayMessageReactionRemoveDispatch = ReactionData; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove */ -export declare type GatewayMessageReactionRemoveDispatchData = GatewayMessageReactionRemoveDispatch['d']; +export type GatewayMessageReactionRemoveDispatchData = GatewayMessageReactionRemoveDispatch['d']; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove-all */ -export declare type GatewayMessageReactionRemoveAllDispatch = DataPayload; +export type GatewayMessageReactionRemoveAllDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove-all */ -export declare type GatewayMessageReactionRemoveAllDispatchData = MessageReactionRemoveData; +export type GatewayMessageReactionRemoveAllDispatchData = MessageReactionRemoveData; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove-emoji */ -export declare type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; +export type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove-emoji */ @@ -1145,59 +1149,59 @@ export interface GatewayMessageReactionRemoveEmojiDispatchData extends MessageRe /** * https://discord.com/developers/docs/topics/gateway-events#presence-update */ -export declare type GatewayPresenceUpdateDispatch = DataPayload; +export type GatewayPresenceUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#presence-update */ -export declare type GatewayPresenceUpdateDispatchData = RawGatewayPresenceUpdate; +export type GatewayPresenceUpdateDispatchData = RawGatewayPresenceUpdate; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-create */ -export declare type GatewayStageInstanceCreateDispatch = DataPayload; +export type GatewayStageInstanceCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-create */ -export declare type GatewayStageInstanceCreateDispatchData = APIStageInstance; +export type GatewayStageInstanceCreateDispatchData = APIStageInstance; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-delete */ -export declare type GatewayStageInstanceDeleteDispatch = DataPayload; +export type GatewayStageInstanceDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-delete */ -export declare type GatewayStageInstanceDeleteDispatchData = APIStageInstance; +export type GatewayStageInstanceDeleteDispatchData = APIStageInstance; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-update */ -export declare type GatewayStageInstanceUpdateDispatch = DataPayload; +export type GatewayStageInstanceUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-update */ -export declare type GatewayStageInstanceUpdateDispatchData = APIStageInstance; +export type GatewayStageInstanceUpdateDispatchData = APIStageInstance; /** * https://discord.com/developers/docs/topics/gateway-events#thread-list-sync */ -export declare type GatewayThreadListSyncDispatch = DataPayload; +export type GatewayThreadListSyncDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#thread-list-sync */ -export declare type GatewayThreadListSyncDispatchData = RawGatewayThreadListSync; +export type GatewayThreadListSyncDispatchData = RawGatewayThreadListSync; /** * https://discord.com/developers/docs/topics/gateway-events#thread-members-update */ -export declare type GatewayThreadMembersUpdateDispatch = DataPayload; +export type GatewayThreadMembersUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#thread-members-update */ -export declare type GatewayThreadMembersUpdateDispatchData = RawGatewayThreadMembersUpdate; +export type GatewayThreadMembersUpdateDispatchData = RawGatewayThreadMembersUpdate; /** * https://discord.com/developers/docs/topics/gateway-events#thread-member-update */ -export declare type GatewayThreadMemberUpdateDispatch = DataPayload; +export type GatewayThreadMemberUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#thread-member-update */ -export declare type GatewayThreadMemberUpdateDispatchData = APIThreadMember & { +export type GatewayThreadMemberUpdateDispatchData = APIThreadMember & { guild_id: Snowflake; }; /** @@ -1205,11 +1209,11 @@ export declare type GatewayThreadMemberUpdateDispatchData = APIThreadMember & { * https://discord.com/developers/docs/topics/gateway-events#thread-update * https://discord.com/developers/docs/topics/gateway-events#thread-delete */ -export declare type GatewayThreadModifyDispatch = DataPayload; +export type GatewayThreadModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#thread-create */ -export declare type GatewayThreadCreateDispatch = GatewayChannelModifyDispatch; +export type GatewayThreadCreateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#thread-create */ @@ -1222,23 +1226,23 @@ export interface GatewayThreadCreateDispatchData extends APIThreadChannel { /** * https://discord.com/developers/docs/topics/gateway-events#thread-update */ -export declare type GatewayThreadUpdateDispatch = GatewayChannelModifyDispatch; +export type GatewayThreadUpdateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#thread-update */ -export declare type GatewayThreadUpdateDispatchData = GatewayChannelModifyDispatchData; +export type GatewayThreadUpdateDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#thread-delete */ -export declare type GatewayThreadDeleteDispatch = GatewayChannelModifyDispatch; +export type GatewayThreadDeleteDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#thread-delete */ -export declare type GatewayThreadDeleteDispatchData = GatewayChannelModifyDispatchData; +export type GatewayThreadDeleteDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#typing-start */ -export declare type GatewayTypingStartDispatch = DataPayload; +export type GatewayTypingStartDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#typing-start */ @@ -1269,23 +1273,23 @@ export interface GatewayTypingStartDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#user-update */ -export declare type GatewayUserUpdateDispatch = DataPayload; +export type GatewayUserUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#user-update */ -export declare type GatewayUserUpdateDispatchData = APIUser; +export type GatewayUserUpdateDispatchData = APIUser; /** * https://discord.com/developers/docs/topics/gateway-events#voice-state-update */ -export declare type GatewayVoiceStateUpdateDispatch = DataPayload; +export type GatewayVoiceStateUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#voice-state-update */ -export declare type GatewayVoiceStateUpdateDispatchData = GatewayVoiceState; +export type GatewayVoiceStateUpdateDispatchData = GatewayVoiceState; /** * https://discord.com/developers/docs/topics/gateway-events#voice-server-update */ -export declare type GatewayVoiceServerUpdateDispatch = DataPayload; +export type GatewayVoiceServerUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#voice-server-update */ @@ -1310,7 +1314,7 @@ export interface GatewayVoiceServerUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#webhooks-update */ -export declare type GatewayWebhooksUpdateDispatch = DataPayload; +export type GatewayWebhooksUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#webhooks-update */ @@ -1327,7 +1331,7 @@ export interface GatewayWebhooksUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-audit-log-entry-create */ -export declare type GatewayGuildAuditLogEntryCreateDispatch = DataPayload; +export type GatewayGuildAuditLogEntryCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-audit-log-entry-create */ @@ -1347,7 +1351,7 @@ export interface GatewayHeartbeat { /** * https://discord.com/developers/docs/topics/gateway#sending-heartbeats */ -export declare type GatewayHeartbeatData = number | null; +export type GatewayHeartbeatData = number | null; /** * https://discord.com/developers/docs/topics/gateway-events#identify */ @@ -1487,7 +1491,7 @@ export interface GatewayRequestGuildMembersDataWithQuery extends GatewayRequestG /** * https://discord.com/developers/docs/topics/gateway-events#request-guild-members */ -export declare type GatewayRequestGuildMembersData = GatewayRequestGuildMembersDataWithUserIds | GatewayRequestGuildMembersDataWithQuery; +export type GatewayRequestGuildMembersData = GatewayRequestGuildMembersDataWithUserIds | GatewayRequestGuildMembersDataWithQuery; /** * https://discord.com/developers/docs/topics/gateway-events#update-voice-state */ @@ -1551,7 +1555,7 @@ export interface GatewayPresenceUpdateData { /** * https://discord.com/developers/docs/topics/gateway-events#activity-object-activity-structure */ -export declare type GatewayActivityUpdateData = Pick; +export type GatewayActivityUpdateData = Pick; interface BasePayload { /** * Opcode for the payload @@ -1570,7 +1574,7 @@ interface BasePayload { */ t?: string; } -declare type NonDispatchPayload = Omit & { +type NonDispatchPayload = Omit & { t: null; s: null; }; @@ -1579,7 +1583,7 @@ interface DataPayload extends t: Event; d: D; } -declare type ReactionData = DataPayload = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#resumed + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayResumedDispatch = DataPayload; +export type GatewayResumedDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#channel-create * https://discord.com/developers/docs/topics/gateway#channel-update * https://discord.com/developers/docs/topics/gateway#channel-delete + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayChannelModifyDispatch = DataPayload; +export type GatewayChannelModifyDispatch = DataPayload; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#channel-pins-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayChannelPinsUpdateDispatch = DataPayload; +export type GatewayGuildModifyDispatch = DataPayload; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildCreateDispatch = GatewayGuildModifyDispatch; +export type GatewayGuildCreateDispatch = GatewayGuildModifyDispatch; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; +export type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#guild-delete + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildDeleteDispatch = DataPayload; +export type GatewayGuildDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-ban-add * https://discord.com/developers/docs/topics/gateway#guild-ban-remove + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildBanModifyDispatch = DataPayload; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; +export type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; +export type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#guild-emojis-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildEmojisUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-integrations-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildIntegrationsUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-member-add + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildMemberAddDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-member-remove + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildMemberRemoveDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-member-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildMemberUpdateDispatch = DataPayload & { +export type GatewayGuildMemberUpdateDispatch = DataPayload & { guild_id: string; }>; /** * https://discord.com/developers/docs/topics/gateway#guild-members-chunk + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildMembersChunkDispatch = DataPayload; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; +export type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; +export type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#guild-role-delete + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayGuildRoleDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#invite-create + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayInviteCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#invite-delete + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayInviteDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-create + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayMessageCreateDispatch = DataPayload; +export type GatewayMessageCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayMessageUpdateDispatch = DataPayload>; /** * https://discord.com/developers/docs/topics/gateway#message-delete + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayMessageDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-delete-bulk + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayMessageDeleteBulkDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-add + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayMessageReactionAddDispatch = ReactionData; +export type GatewayMessageReactionAddDispatch = ReactionData; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-remove + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayMessageReactionRemoveDispatch = ReactionData; +export type GatewayMessageReactionRemoveDispatch = ReactionData; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayMessageReactionRemoveAllDispatch = DataPayload; +export type GatewayMessageReactionRemoveAllDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#presence-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayPresenceUpdateDispatch = DataPayload; +export type GatewayPresenceUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#typing-start + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayTypingStartDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#user-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayUserUpdateDispatch = DataPayload; +export type GatewayUserUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#voice-state-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayVoiceStateUpdateDispatch = DataPayload; +export type GatewayVoiceStateUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#voice-server-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayVoiceServerUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#webhooks-update + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -export declare type GatewayWebhooksUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#heartbeating + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ export interface GatewayHeartbeat { @@ -483,6 +526,7 @@ export interface GatewayHeartbeat { } /** * https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ export interface GatewayIdentifyProperties { @@ -492,6 +536,7 @@ export interface GatewayIdentifyProperties { } /** * https://discord.com/developers/docs/topics/gateway#identify + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ export interface GatewayIdentify { @@ -509,6 +554,7 @@ export interface GatewayIdentify { } /** * https://discord.com/developers/docs/topics/gateway#resume + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ export interface GatewayResume { @@ -521,6 +567,7 @@ export interface GatewayResume { } /** * https://discord.com/developers/docs/topics/gateway#request-guild-members + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ export interface GatewayRequestGuildMembers { @@ -536,6 +583,7 @@ export interface GatewayRequestGuildMembers { } /** * https://discord.com/developers/docs/topics/gateway#update-voice-state + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ export interface GatewayVoiceStateUpdate { @@ -549,6 +597,7 @@ export interface GatewayVoiceStateUpdate { } /** * https://discord.com/developers/docs/topics/gateway#update-status + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ export interface GatewayUpdatePresence { @@ -557,6 +606,7 @@ export interface GatewayUpdatePresence { } /** * https://discord.com/developers/docs/topics/gateway#update-status-gateway-status-update-structure + * * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ export interface GatewayPresenceUpdateData { @@ -577,7 +627,7 @@ interface BasePayload { /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -declare type NonDispatchPayload = Omit; +type NonDispatchPayload = Omit; /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ @@ -589,7 +639,7 @@ interface DataPayload extends /** * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. */ -declare type ReactionData = DataPayload = DataPayload; +export type GatewayReadyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#ready + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayReadyDispatchData { @@ -334,60 +347,71 @@ export interface GatewayReadyDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#resumed + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayResumedDispatch = DataPayload; +export type GatewayResumedDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#channel-create * https://discord.com/developers/docs/topics/gateway#channel-update * https://discord.com/developers/docs/topics/gateway#channel-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayChannelModifyDispatch = DataPayload; +export type GatewayChannelModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#channel-create * https://discord.com/developers/docs/topics/gateway#channel-update * https://discord.com/developers/docs/topics/gateway#channel-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayChannelModifyDispatchData = APIChannel; +export type GatewayChannelModifyDispatchData = APIChannel; /** * https://discord.com/developers/docs/topics/gateway#channel-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#channel-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayChannelCreateDispatchData = GatewayChannelModifyDispatchData; +export type GatewayChannelCreateDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway#channel-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#channel-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayChannelUpdateDispatchData = GatewayChannelModifyDispatchData; +export type GatewayChannelUpdateDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway#channel-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#channel-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayChannelDeleteDispatchData = GatewayChannelModifyDispatchData; +export type GatewayChannelDeleteDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway#channel-pins-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayChannelPinsUpdateDispatch = DataPayload; +export type GatewayChannelPinsUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#channel-pins-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayChannelPinsUpdateDispatchData { @@ -407,54 +431,64 @@ export interface GatewayChannelPinsUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway#guild-create * https://discord.com/developers/docs/topics/gateway#guild-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildModifyDispatch = DataPayload; +export type GatewayGuildModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-create * https://discord.com/developers/docs/topics/gateway#guild-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildModifyDispatchData = APIGuild; +export type GatewayGuildModifyDispatchData = APIGuild; /** * https://discord.com/developers/docs/topics/gateway#guild-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildCreateDispatch = GatewayGuildModifyDispatch; +export type GatewayGuildCreateDispatch = GatewayGuildModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#guild-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildCreateDispatchData = GatewayGuildModifyDispatchData; +export type GatewayGuildCreateDispatchData = GatewayGuildModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway#guild-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; +export type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#guild-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildUpdateDispatchData = GatewayGuildModifyDispatchData; +export type GatewayGuildUpdateDispatchData = GatewayGuildModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway#guild-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildDeleteDispatch = DataPayload; +export type GatewayGuildDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildDeleteDispatchData = APIUnavailableGuild; +export type GatewayGuildDeleteDispatchData = APIUnavailableGuild; /** * https://discord.com/developers/docs/topics/gateway#guild-ban-add * https://discord.com/developers/docs/topics/gateway#guild-ban-remove + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildBanModifyDispatch = DataPayload; +export type GatewayGuildBanModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-ban-add * https://discord.com/developers/docs/topics/gateway#guild-ban-remove + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayGuildBanModifyDispatchData { @@ -471,31 +505,37 @@ export interface GatewayGuildBanModifyDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#guild-ban-add + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; +export type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#guild-ban-add + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildBanAddDispatchData = GatewayGuildBanModifyDispatchData; +export type GatewayGuildBanAddDispatchData = GatewayGuildBanModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway#guild-ban-remove + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; +export type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#guild-ban-remove + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildBanRemoveDispatchData = GatewayGuildBanModifyDispatchData; +export type GatewayGuildBanRemoveDispatchData = GatewayGuildBanModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway#guild-emojis-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildEmojisUpdateDispatch = DataPayload; +export type GatewayGuildEmojisUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-emojis-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayGuildEmojisUpdateDispatchData { @@ -512,11 +552,13 @@ export interface GatewayGuildEmojisUpdateDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#guild-stickers-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildStickersUpdateDispatch = DataPayload; +export type GatewayGuildStickersUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-stickers-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayGuildStickersUpdateDispatchData { @@ -533,11 +575,13 @@ export interface GatewayGuildStickersUpdateDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#guild-integrations-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildIntegrationsUpdateDispatch = DataPayload; +export type GatewayGuildIntegrationsUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-integrations-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayGuildIntegrationsUpdateDispatchData { @@ -548,11 +592,13 @@ export interface GatewayGuildIntegrationsUpdateDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#guild-member-add + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildMemberAddDispatch = DataPayload; +export type GatewayGuildMemberAddDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-member-add + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayGuildMemberAddDispatchData extends APIGuildMember { @@ -563,11 +609,13 @@ export interface GatewayGuildMemberAddDispatchData extends APIGuildMember { } /** * https://discord.com/developers/docs/topics/gateway#guild-member-remove + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildMemberRemoveDispatch = DataPayload; +export type GatewayGuildMemberRemoveDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-member-remove + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayGuildMemberRemoveDispatchData { @@ -584,14 +632,16 @@ export interface GatewayGuildMemberRemoveDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#guild-member-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildMemberUpdateDispatch = DataPayload; +export type GatewayGuildMemberUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-member-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildMemberUpdateDispatchData = Omit & Partial> & Required> & Nullable> & { +export type GatewayGuildMemberUpdateDispatchData = Omit & Partial> & Required> & Nullable> & { /** * The id of the guild */ @@ -599,11 +649,13 @@ export declare type GatewayGuildMemberUpdateDispatchData = Omit; +export type GatewayGuildMembersChunkDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-members-chunk + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayGuildMembersChunkDispatchData { @@ -645,12 +697,14 @@ export interface GatewayGuildMembersChunkDispatchData { /** * https://discord.com/developers/docs/topics/gateway#guild-role-create * https://discord.com/developers/docs/topics/gateway#guild-role-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildRoleModifyDispatch = DataPayload; +export type GatewayGuildRoleModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-role-create * https://discord.com/developers/docs/topics/gateway#guild-role-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayGuildRoleModifyDispatchData { @@ -667,31 +721,37 @@ export interface GatewayGuildRoleModifyDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#guild-role-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; +export type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#guild-role-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildRoleCreateDispatchData = GatewayGuildRoleModifyDispatchData; +export type GatewayGuildRoleCreateDispatchData = GatewayGuildRoleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway#guild-role-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; +export type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway#guild-role-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildRoleUpdateDispatchData = GatewayGuildRoleModifyDispatchData; +export type GatewayGuildRoleUpdateDispatchData = GatewayGuildRoleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway#guild-role-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildRoleDeleteDispatch = DataPayload; +export type GatewayGuildRoleDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#guild-role-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayGuildRoleDeleteDispatchData { @@ -707,31 +767,31 @@ export interface GatewayGuildRoleDeleteDispatchData { /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildScheduledEventCreateDispatch = DataPayload; +export type GatewayGuildScheduledEventCreateDispatch = DataPayload; /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildScheduledEventCreateDispatchData = APIGuildScheduledEvent; +export type GatewayGuildScheduledEventCreateDispatchData = APIGuildScheduledEvent; /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildScheduledEventUpdateDispatch = DataPayload; +export type GatewayGuildScheduledEventUpdateDispatch = DataPayload; /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildScheduledEventUpdateDispatchData = APIGuildScheduledEvent; +export type GatewayGuildScheduledEventUpdateDispatchData = APIGuildScheduledEvent; /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildScheduledEventDeleteDispatch = DataPayload; +export type GatewayGuildScheduledEventDeleteDispatch = DataPayload; /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildScheduledEventDeleteDispatchData = APIGuildScheduledEvent; +export type GatewayGuildScheduledEventDeleteDispatchData = APIGuildScheduledEvent; /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildScheduledEventUserAddDispatch = DataPayload; +export type GatewayGuildScheduledEventUserAddDispatch = DataPayload; /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ @@ -743,7 +803,7 @@ export interface GatewayGuildScheduledEventUserAddDispatchData { /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayGuildScheduledEventUserRemoveDispatch = DataPayload; +export type GatewayGuildScheduledEventUserRemoveDispatch = DataPayload; /** * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ @@ -754,35 +814,41 @@ export interface GatewayGuildScheduledEventUserRemoveDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#integration-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayIntegrationCreateDispatch = DataPayload; +export type GatewayIntegrationCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#integration-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayIntegrationCreateDispatchData = APIGuildIntegration & { +export type GatewayIntegrationCreateDispatchData = APIGuildIntegration & { guild_id: Snowflake; }; /** * https://discord.com/developers/docs/topics/gateway#integration-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayIntegrationUpdateDispatch = DataPayload; +export type GatewayIntegrationUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#integration-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayIntegrationUpdateDispatchData = APIGuildIntegration & { +export type GatewayIntegrationUpdateDispatchData = APIGuildIntegration & { guild_id: Snowflake; }; /** * https://discord.com/developers/docs/topics/gateway#integration-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayIntegrationDeleteDispatch = DataPayload; +export type GatewayIntegrationDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#integration-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayIntegrationDeleteDispatchData { @@ -801,21 +867,25 @@ export interface GatewayIntegrationDeleteDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#interaction-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayInteractionCreateDispatch = DataPayload; +export type GatewayInteractionCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#interaction-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayInteractionCreateDispatchData = APIInteraction; +export type GatewayInteractionCreateDispatchData = APIInteraction; /** * https://discord.com/developers/docs/topics/gateway#invite-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayInviteCreateDispatch = DataPayload; +export type GatewayInviteCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#invite-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayInviteCreateDispatchData { @@ -878,11 +948,13 @@ export interface GatewayInviteCreateDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#invite-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayInviteDeleteDispatch = DataPayload; +export type GatewayInviteDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#invite-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayInviteDeleteDispatchData { @@ -903,34 +975,40 @@ export interface GatewayInviteDeleteDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#message-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageCreateDispatch = DataPayload; +export type GatewayMessageCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageCreateDispatchData = APIMessage; +export type GatewayMessageCreateDispatchData = APIMessage; /** * https://discord.com/developers/docs/topics/gateway#message-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageUpdateDispatch = DataPayload; +export type GatewayMessageUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageUpdateDispatchData = { +export type GatewayMessageUpdateDispatchData = { id: Snowflake; channel_id: Snowflake; } & Partial; /** * https://discord.com/developers/docs/topics/gateway#message-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageDeleteDispatch = DataPayload; +export type GatewayMessageDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayMessageDeleteDispatchData { @@ -949,11 +1027,13 @@ export interface GatewayMessageDeleteDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#message-delete-bulk + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageDeleteBulkDispatch = DataPayload; +export type GatewayMessageDeleteBulkDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-delete-bulk + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayMessageDeleteBulkDispatchData { @@ -972,41 +1052,49 @@ export interface GatewayMessageDeleteBulkDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#message-reaction-add + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageReactionAddDispatch = ReactionData; +export type GatewayMessageReactionAddDispatch = ReactionData; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-add + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageReactionAddDispatchData = GatewayMessageReactionAddDispatch['d']; +export type GatewayMessageReactionAddDispatchData = GatewayMessageReactionAddDispatch['d']; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-remove + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageReactionRemoveDispatch = ReactionData; +export type GatewayMessageReactionRemoveDispatch = ReactionData; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-remove + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageReactionRemoveDispatchData = GatewayMessageReactionRemoveDispatch['d']; +export type GatewayMessageReactionRemoveDispatchData = GatewayMessageReactionRemoveDispatch['d']; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageReactionRemoveAllDispatch = DataPayload; +export type GatewayMessageReactionRemoveAllDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageReactionRemoveAllDispatchData = MessageReactionRemoveData; +export type GatewayMessageReactionRemoveAllDispatchData = MessageReactionRemoveData; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; +export type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayMessageReactionRemoveEmojiDispatchData extends MessageReactionRemoveData { @@ -1017,51 +1105,61 @@ export interface GatewayMessageReactionRemoveEmojiDispatchData extends MessageRe } /** * https://discord.com/developers/docs/topics/gateway#presence-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayPresenceUpdateDispatch = DataPayload; +export type GatewayPresenceUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#presence-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayPresenceUpdateDispatchData = RawGatewayPresenceUpdate; +export type GatewayPresenceUpdateDispatchData = RawGatewayPresenceUpdate; /** * https://discord.com/developers/docs/topics/gateway#stage-instance-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayStageInstanceCreateDispatch = DataPayload; +export type GatewayStageInstanceCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#stage-instance-create + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayStageInstanceCreateDispatchData = APIStageInstance; +export type GatewayStageInstanceCreateDispatchData = APIStageInstance; /** * https://discord.com/developers/docs/topics/gateway#stage-instance-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayStageInstanceDeleteDispatch = DataPayload; +export type GatewayStageInstanceDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#stage-instance-delete + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayStageInstanceDeleteDispatchData = APIStageInstance; +export type GatewayStageInstanceDeleteDispatchData = APIStageInstance; /** * https://discord.com/developers/docs/topics/gateway#stage-instance-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayStageInstanceUpdateDispatch = DataPayload; +export type GatewayStageInstanceUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#stage-instance-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayStageInstanceUpdateDispatchData = APIStageInstance; +export type GatewayStageInstanceUpdateDispatchData = APIStageInstance; /** * https://discord.com/developers/docs/topics/gateway#typing-start + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayTypingStartDispatch = DataPayload; +export type GatewayTypingStartDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#typing-start + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayTypingStartDispatchData { @@ -1090,31 +1188,37 @@ export interface GatewayTypingStartDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#user-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayUserUpdateDispatch = DataPayload; +export type GatewayUserUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#user-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayUserUpdateDispatchData = APIUser; +export type GatewayUserUpdateDispatchData = APIUser; /** * https://discord.com/developers/docs/topics/gateway#voice-state-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayVoiceStateUpdateDispatch = DataPayload; +export type GatewayVoiceStateUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#voice-state-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayVoiceStateUpdateDispatchData = GatewayVoiceState; +export type GatewayVoiceStateUpdateDispatchData = GatewayVoiceState; /** * https://discord.com/developers/docs/topics/gateway#voice-server-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayVoiceServerUpdateDispatch = DataPayload; +export type GatewayVoiceServerUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#voice-server-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayVoiceServerUpdateDispatchData { @@ -1137,11 +1241,13 @@ export interface GatewayVoiceServerUpdateDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#webhooks-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayWebhooksUpdateDispatch = DataPayload; +export type GatewayWebhooksUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway#webhooks-update + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayWebhooksUpdateDispatchData { @@ -1156,6 +1262,7 @@ export interface GatewayWebhooksUpdateDispatchData { } /** * https://discord.com/developers/docs/topics/gateway#heartbeating + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayHeartbeat { @@ -1164,11 +1271,13 @@ export interface GatewayHeartbeat { } /** * https://discord.com/developers/docs/topics/gateway#heartbeating + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayHeartbeatData = number | null; +export type GatewayHeartbeatData = number | null; /** * https://discord.com/developers/docs/topics/gateway#identify + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayIdentify { @@ -1177,6 +1286,7 @@ export interface GatewayIdentify { } /** * https://discord.com/developers/docs/topics/gateway#identify + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayIdentifyData { @@ -1224,6 +1334,7 @@ export interface GatewayIdentifyData { } /** * https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayIdentifyProperties { @@ -1242,6 +1353,7 @@ export interface GatewayIdentifyProperties { } /** * https://discord.com/developers/docs/topics/gateway#resume + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayResume { @@ -1250,6 +1362,7 @@ export interface GatewayResume { } /** * https://discord.com/developers/docs/topics/gateway#resume + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayResumeData { @@ -1268,6 +1381,7 @@ export interface GatewayResumeData { } /** * https://discord.com/developers/docs/topics/gateway#request-guild-members + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayRequestGuildMembers { @@ -1276,6 +1390,7 @@ export interface GatewayRequestGuildMembers { } /** * https://discord.com/developers/docs/topics/gateway#request-guild-members + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayRequestGuildMembersData { @@ -1311,6 +1426,7 @@ export interface GatewayRequestGuildMembersData { } /** * https://discord.com/developers/docs/topics/gateway#update-voice-state + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayVoiceStateUpdate { @@ -1319,6 +1435,7 @@ export interface GatewayVoiceStateUpdate { } /** * https://discord.com/developers/docs/topics/gateway#update-voice-state + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayVoiceStateUpdateData { @@ -1341,6 +1458,7 @@ export interface GatewayVoiceStateUpdateData { } /** * https://discord.com/developers/docs/topics/gateway#update-presence + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayUpdatePresence { @@ -1349,6 +1467,7 @@ export interface GatewayUpdatePresence { } /** * https://discord.com/developers/docs/topics/gateway#update-presence-gateway-presence-update-structure + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ export interface GatewayPresenceUpdateData { @@ -1375,9 +1494,10 @@ export interface GatewayPresenceUpdateData { } /** * https://discord.com/developers/docs/topics/gateway-events#activity-object-activity-structure + * * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. */ -export declare type GatewayActivityUpdateData = Pick; +export type GatewayActivityUpdateData = Pick; interface BasePayload { /** * Opcode for the payload @@ -1396,7 +1516,7 @@ interface BasePayload { */ t?: string; } -declare type NonDispatchPayload = Omit & { +type NonDispatchPayload = Omit & { t: null; s: null; }; @@ -1405,7 +1525,7 @@ interface DataPayload extends t: Event; d: D; } -declare type ReactionData = DataPayload = DataPayload; +export type GatewayReadyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#ready */ @@ -333,47 +333,47 @@ export interface GatewayReadyDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#resumed */ -export declare type GatewayResumedDispatch = DataPayload; +export type GatewayResumedDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete */ -export declare type GatewayAutoModerationRuleModifyDispatch = DataPayload; +export type GatewayAutoModerationRuleModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete */ -export declare type GatewayAutoModerationRuleModifyDispatchData = APIAutoModerationRule; +export type GatewayAutoModerationRuleModifyDispatchData = APIAutoModerationRule; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create */ -export declare type GatewayAutoModerationRuleCreateDispatch = GatewayAutoModerationRuleModifyDispatch; +export type GatewayAutoModerationRuleCreateDispatch = GatewayAutoModerationRuleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-create */ -export declare type GatewayAutoModerationRuleCreateDispatchData = GatewayAutoModerationRuleModifyDispatchData; +export type GatewayAutoModerationRuleCreateDispatchData = GatewayAutoModerationRuleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update */ -export declare type GatewayAutoModerationRuleUpdateDispatch = GatewayAutoModerationRuleModifyDispatch; +export type GatewayAutoModerationRuleUpdateDispatch = GatewayAutoModerationRuleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-update */ -export declare type GatewayAutoModerationRuleUpdateDispatchData = GatewayAutoModerationRuleModifyDispatchData; +export type GatewayAutoModerationRuleUpdateDispatchData = GatewayAutoModerationRuleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete */ -export declare type GatewayAutoModerationRuleDeleteDispatch = GatewayAutoModerationRuleModifyDispatch; +export type GatewayAutoModerationRuleDeleteDispatch = GatewayAutoModerationRuleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-rule-delete */ -export declare type GatewayAutoModerationRuleDeleteDispatchData = GatewayAutoModerationRuleModifyDispatchData; +export type GatewayAutoModerationRuleDeleteDispatchData = GatewayAutoModerationRuleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-action-execution */ -export declare type GatewayAutoModerationActionExecutionDispatch = DataPayload; +export type GatewayAutoModerationActionExecutionDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#auto-moderation-action-execution */ @@ -434,7 +434,7 @@ export interface GatewayAutoModerationActionExecutionDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#application-command-permissions-update */ -export declare type GatewayApplicationCommandPermissionsUpdateDispatch = DataPayload; +export type GatewayApplicationCommandPermissionsUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#application-command-permissions-update */ @@ -461,41 +461,41 @@ export interface GatewayApplicationCommandPermissionsUpdateDispatchData { * https://discord.com/developers/docs/topics/gateway-events#channel-update * https://discord.com/developers/docs/topics/gateway-events#channel-delete */ -export declare type GatewayChannelModifyDispatch = DataPayload; +export type GatewayChannelModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#channel-create * https://discord.com/developers/docs/topics/gateway-events#channel-update * https://discord.com/developers/docs/topics/gateway-events#channel-delete */ -export declare type GatewayChannelModifyDispatchData = APIChannel; +export type GatewayChannelModifyDispatchData = APIChannel; /** * https://discord.com/developers/docs/topics/gateway-events#channel-create */ -export declare type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#channel-create */ -export declare type GatewayChannelCreateDispatchData = GatewayChannelModifyDispatchData; +export type GatewayChannelCreateDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#channel-update */ -export declare type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#channel-update */ -export declare type GatewayChannelUpdateDispatchData = GatewayChannelModifyDispatchData; +export type GatewayChannelUpdateDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#channel-delete */ -export declare type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; +export type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#channel-delete */ -export declare type GatewayChannelDeleteDispatchData = GatewayChannelModifyDispatchData; +export type GatewayChannelDeleteDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#channel-pins-update */ -export declare type GatewayChannelPinsUpdateDispatch = DataPayload; +export type GatewayChannelPinsUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#channel-pins-update */ @@ -516,15 +516,15 @@ export interface GatewayChannelPinsUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-update */ -export declare type GatewayGuildModifyDispatch = DataPayload; +export type GatewayGuildModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-update */ -export declare type GatewayGuildModifyDispatchData = APIGuild; +export type GatewayGuildModifyDispatchData = APIGuild; /** * https://discord.com/developers/docs/topics/gateway-events#guild-create */ -export declare type GatewayGuildCreateDispatch = DataPayload; +export type GatewayGuildCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-create * https://discord.com/developers/docs/topics/gateway-events#guild-create-guild-create-extra-fields @@ -612,24 +612,24 @@ export interface GatewayGuildCreateDispatchData extends APIGuild { /** * https://discord.com/developers/docs/topics/gateway-events#guild-update */ -export declare type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; +export type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-update */ -export declare type GatewayGuildUpdateDispatchData = GatewayGuildModifyDispatchData; +export type GatewayGuildUpdateDispatchData = GatewayGuildModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-delete */ -export declare type GatewayGuildDeleteDispatch = DataPayload; +export type GatewayGuildDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-delete */ -export declare type GatewayGuildDeleteDispatchData = APIUnavailableGuild; +export type GatewayGuildDeleteDispatchData = APIUnavailableGuild; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-add * https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove */ -export declare type GatewayGuildBanModifyDispatch = DataPayload; +export type GatewayGuildBanModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-add * https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove @@ -649,23 +649,23 @@ export interface GatewayGuildBanModifyDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-add */ -export declare type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; +export type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-add */ -export declare type GatewayGuildBanAddDispatchData = GatewayGuildBanModifyDispatchData; +export type GatewayGuildBanAddDispatchData = GatewayGuildBanModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove */ -export declare type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; +export type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-ban-remove */ -export declare type GatewayGuildBanRemoveDispatchData = GatewayGuildBanModifyDispatchData; +export type GatewayGuildBanRemoveDispatchData = GatewayGuildBanModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-emojis-update */ -export declare type GatewayGuildEmojisUpdateDispatch = DataPayload; +export type GatewayGuildEmojisUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-emojis-update */ @@ -684,7 +684,7 @@ export interface GatewayGuildEmojisUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-stickers-update */ -export declare type GatewayGuildStickersUpdateDispatch = DataPayload; +export type GatewayGuildStickersUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-stickers-update */ @@ -703,7 +703,7 @@ export interface GatewayGuildStickersUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-integrations-update */ -export declare type GatewayGuildIntegrationsUpdateDispatch = DataPayload; +export type GatewayGuildIntegrationsUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-integrations-update */ @@ -716,7 +716,7 @@ export interface GatewayGuildIntegrationsUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-add */ -export declare type GatewayGuildMemberAddDispatch = DataPayload; +export type GatewayGuildMemberAddDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-add */ @@ -729,7 +729,7 @@ export interface GatewayGuildMemberAddDispatchData extends APIGuildMember { /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-remove */ -export declare type GatewayGuildMemberRemoveDispatch = DataPayload; +export type GatewayGuildMemberRemoveDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-remove */ @@ -748,11 +748,11 @@ export interface GatewayGuildMemberRemoveDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-update */ -export declare type GatewayGuildMemberUpdateDispatch = DataPayload; +export type GatewayGuildMemberUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-member-update */ -export declare type GatewayGuildMemberUpdateDispatchData = Omit & Partial> & Required> & Nullable> & { +export type GatewayGuildMemberUpdateDispatchData = Omit & Partial> & Required> & Nullable> & { /** * The id of the guild */ @@ -761,7 +761,11 @@ export declare type GatewayGuildMemberUpdateDispatchData = Omit; +export type GatewayGuildMembersChunkDispatch = DataPayload; +/** + * https://discord.com/developers/docs/topics/gateway-events#update-presence + */ +export type GatewayGuildMembersChunkPresence = Omit; /** * https://discord.com/developers/docs/topics/gateway-events#guild-members-chunk */ @@ -793,7 +797,7 @@ export interface GatewayGuildMembersChunkDispatchData { * * See https://discord.com/developers/docs/topics/gateway-events#update-presence */ - presences?: RawGatewayPresenceUpdate[]; + presences?: GatewayGuildMembersChunkPresence[]; /** * The nonce used in the Guild Members Request * @@ -805,7 +809,7 @@ export interface GatewayGuildMembersChunkDispatchData { * https://discord.com/developers/docs/topics/gateway-events#guild-role-create * https://discord.com/developers/docs/topics/gateway-events#guild-role-update */ -export declare type GatewayGuildRoleModifyDispatch = DataPayload; +export type GatewayGuildRoleModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-create * https://discord.com/developers/docs/topics/gateway-events#guild-role-update @@ -825,23 +829,23 @@ export interface GatewayGuildRoleModifyDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-create */ -export declare type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; +export type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-create */ -export declare type GatewayGuildRoleCreateDispatchData = GatewayGuildRoleModifyDispatchData; +export type GatewayGuildRoleCreateDispatchData = GatewayGuildRoleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-update */ -export declare type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; +export type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-update */ -export declare type GatewayGuildRoleUpdateDispatchData = GatewayGuildRoleModifyDispatchData; +export type GatewayGuildRoleUpdateDispatchData = GatewayGuildRoleModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-delete */ -export declare type GatewayGuildRoleDeleteDispatch = DataPayload; +export type GatewayGuildRoleDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-role-delete */ @@ -855,19 +859,19 @@ export interface GatewayGuildRoleDeleteDispatchData { */ role_id: Snowflake; } -export declare type GatewayGuildScheduledEventCreateDispatch = DataPayload; -export declare type GatewayGuildScheduledEventCreateDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventUpdateDispatch = DataPayload; -export declare type GatewayGuildScheduledEventUpdateDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventDeleteDispatch = DataPayload; -export declare type GatewayGuildScheduledEventDeleteDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventUserAddDispatch = DataPayload; +export type GatewayGuildScheduledEventCreateDispatch = DataPayload; +export type GatewayGuildScheduledEventCreateDispatchData = APIGuildScheduledEvent; +export type GatewayGuildScheduledEventUpdateDispatch = DataPayload; +export type GatewayGuildScheduledEventUpdateDispatchData = APIGuildScheduledEvent; +export type GatewayGuildScheduledEventDeleteDispatch = DataPayload; +export type GatewayGuildScheduledEventDeleteDispatchData = APIGuildScheduledEvent; +export type GatewayGuildScheduledEventUserAddDispatch = DataPayload; export interface GatewayGuildScheduledEventUserAddDispatchData { guild_scheduled_event_id: Snowflake; user_id: Snowflake; guild_id: Snowflake; } -export declare type GatewayGuildScheduledEventUserRemoveDispatch = DataPayload; +export type GatewayGuildScheduledEventUserRemoveDispatch = DataPayload; export interface GatewayGuildScheduledEventUserRemoveDispatchData { guild_scheduled_event_id: Snowflake; user_id: Snowflake; @@ -876,27 +880,27 @@ export interface GatewayGuildScheduledEventUserRemoveDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#integration-create */ -export declare type GatewayIntegrationCreateDispatch = DataPayload; +export type GatewayIntegrationCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#integration-create */ -export declare type GatewayIntegrationCreateDispatchData = APIGuildIntegration & { +export type GatewayIntegrationCreateDispatchData = APIGuildIntegration & { guild_id: Snowflake; }; /** * https://discord.com/developers/docs/topics/gateway-events#integration-update */ -export declare type GatewayIntegrationUpdateDispatch = DataPayload; +export type GatewayIntegrationUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#integration-update */ -export declare type GatewayIntegrationUpdateDispatchData = APIGuildIntegration & { +export type GatewayIntegrationUpdateDispatchData = APIGuildIntegration & { guild_id: Snowflake; }; /** * https://discord.com/developers/docs/topics/gateway-events#integration-update */ -export declare type GatewayIntegrationDeleteDispatch = DataPayload; +export type GatewayIntegrationDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#integration-delete */ @@ -917,15 +921,15 @@ export interface GatewayIntegrationDeleteDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#interaction-create */ -export declare type GatewayInteractionCreateDispatch = DataPayload; +export type GatewayInteractionCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#interaction-create */ -export declare type GatewayInteractionCreateDispatchData = APIInteraction; +export type GatewayInteractionCreateDispatchData = APIInteraction; /** * https://discord.com/developers/docs/topics/gateway-events#invite-create */ -export declare type GatewayInviteCreateDispatch = DataPayload; +export type GatewayInviteCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#invite-create */ @@ -990,7 +994,7 @@ export interface GatewayInviteCreateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#invite-delete */ -export declare type GatewayInviteDeleteDispatch = DataPayload; +export type GatewayInviteDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#invite-delete */ @@ -1013,19 +1017,19 @@ export interface GatewayInviteDeleteDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#message-create */ -export declare type GatewayMessageCreateDispatch = DataPayload; +export type GatewayMessageCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-create */ -export declare type GatewayMessageCreateDispatchData = Omit & GatewayMessageEventExtraFields; +export type GatewayMessageCreateDispatchData = Omit & GatewayMessageEventExtraFields; /** * https://discord.com/developers/docs/topics/gateway-events#message-update */ -export declare type GatewayMessageUpdateDispatch = DataPayload; +export type GatewayMessageUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-update */ -export declare type GatewayMessageUpdateDispatchData = Omit, 'mentions'> & GatewayMessageEventExtraFields & { +export type GatewayMessageUpdateDispatchData = Omit, 'mentions'> & GatewayMessageEventExtraFields & { /** * ID of the message */ @@ -1065,7 +1069,7 @@ export interface GatewayMessageEventExtraFields { /** * https://discord.com/developers/docs/topics/gateway-events#message-delete */ -export declare type GatewayMessageDeleteDispatch = DataPayload; +export type GatewayMessageDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-delete */ @@ -1086,7 +1090,7 @@ export interface GatewayMessageDeleteDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#message-delete-bulk */ -export declare type GatewayMessageDeleteBulkDispatch = DataPayload; +export type GatewayMessageDeleteBulkDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-delete-bulk */ @@ -1107,31 +1111,31 @@ export interface GatewayMessageDeleteBulkDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-add */ -export declare type GatewayMessageReactionAddDispatch = ReactionData; +export type GatewayMessageReactionAddDispatch = ReactionData; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-add */ -export declare type GatewayMessageReactionAddDispatchData = GatewayMessageReactionAddDispatch['d']; +export type GatewayMessageReactionAddDispatchData = GatewayMessageReactionAddDispatch['d']; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove */ -export declare type GatewayMessageReactionRemoveDispatch = ReactionData; +export type GatewayMessageReactionRemoveDispatch = ReactionData; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove */ -export declare type GatewayMessageReactionRemoveDispatchData = GatewayMessageReactionRemoveDispatch['d']; +export type GatewayMessageReactionRemoveDispatchData = GatewayMessageReactionRemoveDispatch['d']; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove-all */ -export declare type GatewayMessageReactionRemoveAllDispatch = DataPayload; +export type GatewayMessageReactionRemoveAllDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove-all */ -export declare type GatewayMessageReactionRemoveAllDispatchData = MessageReactionRemoveData; +export type GatewayMessageReactionRemoveAllDispatchData = MessageReactionRemoveData; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove-emoji */ -export declare type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; +export type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#message-reaction-remove-emoji */ @@ -1144,59 +1148,59 @@ export interface GatewayMessageReactionRemoveEmojiDispatchData extends MessageRe /** * https://discord.com/developers/docs/topics/gateway-events#presence-update */ -export declare type GatewayPresenceUpdateDispatch = DataPayload; +export type GatewayPresenceUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#presence-update */ -export declare type GatewayPresenceUpdateDispatchData = RawGatewayPresenceUpdate; +export type GatewayPresenceUpdateDispatchData = RawGatewayPresenceUpdate; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-create */ -export declare type GatewayStageInstanceCreateDispatch = DataPayload; +export type GatewayStageInstanceCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-create */ -export declare type GatewayStageInstanceCreateDispatchData = APIStageInstance; +export type GatewayStageInstanceCreateDispatchData = APIStageInstance; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-delete */ -export declare type GatewayStageInstanceDeleteDispatch = DataPayload; +export type GatewayStageInstanceDeleteDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-delete */ -export declare type GatewayStageInstanceDeleteDispatchData = APIStageInstance; +export type GatewayStageInstanceDeleteDispatchData = APIStageInstance; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-update */ -export declare type GatewayStageInstanceUpdateDispatch = DataPayload; +export type GatewayStageInstanceUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#stage-instance-update */ -export declare type GatewayStageInstanceUpdateDispatchData = APIStageInstance; +export type GatewayStageInstanceUpdateDispatchData = APIStageInstance; /** * https://discord.com/developers/docs/topics/gateway-events#thread-list-sync */ -export declare type GatewayThreadListSyncDispatch = DataPayload; +export type GatewayThreadListSyncDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#thread-list-sync */ -export declare type GatewayThreadListSyncDispatchData = RawGatewayThreadListSync; +export type GatewayThreadListSyncDispatchData = RawGatewayThreadListSync; /** * https://discord.com/developers/docs/topics/gateway-events#thread-members-update */ -export declare type GatewayThreadMembersUpdateDispatch = DataPayload; +export type GatewayThreadMembersUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#thread-members-update */ -export declare type GatewayThreadMembersUpdateDispatchData = RawGatewayThreadMembersUpdate; +export type GatewayThreadMembersUpdateDispatchData = RawGatewayThreadMembersUpdate; /** * https://discord.com/developers/docs/topics/gateway-events#thread-member-update */ -export declare type GatewayThreadMemberUpdateDispatch = DataPayload; +export type GatewayThreadMemberUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#thread-member-update */ -export declare type GatewayThreadMemberUpdateDispatchData = APIThreadMember & { +export type GatewayThreadMemberUpdateDispatchData = APIThreadMember & { guild_id: Snowflake; }; /** @@ -1204,11 +1208,11 @@ export declare type GatewayThreadMemberUpdateDispatchData = APIThreadMember & { * https://discord.com/developers/docs/topics/gateway-events#thread-update * https://discord.com/developers/docs/topics/gateway-events#thread-delete */ -export declare type GatewayThreadModifyDispatch = DataPayload; +export type GatewayThreadModifyDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#thread-create */ -export declare type GatewayThreadCreateDispatch = GatewayChannelModifyDispatch; +export type GatewayThreadCreateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#thread-create */ @@ -1221,23 +1225,23 @@ export interface GatewayThreadCreateDispatchData extends APIThreadChannel { /** * https://discord.com/developers/docs/topics/gateway-events#thread-update */ -export declare type GatewayThreadUpdateDispatch = GatewayChannelModifyDispatch; +export type GatewayThreadUpdateDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#thread-update */ -export declare type GatewayThreadUpdateDispatchData = GatewayChannelModifyDispatchData; +export type GatewayThreadUpdateDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#thread-delete */ -export declare type GatewayThreadDeleteDispatch = GatewayChannelModifyDispatch; +export type GatewayThreadDeleteDispatch = GatewayChannelModifyDispatch; /** * https://discord.com/developers/docs/topics/gateway-events#thread-delete */ -export declare type GatewayThreadDeleteDispatchData = GatewayChannelModifyDispatchData; +export type GatewayThreadDeleteDispatchData = GatewayChannelModifyDispatchData; /** * https://discord.com/developers/docs/topics/gateway-events#typing-start */ -export declare type GatewayTypingStartDispatch = DataPayload; +export type GatewayTypingStartDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#typing-start */ @@ -1268,23 +1272,23 @@ export interface GatewayTypingStartDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#user-update */ -export declare type GatewayUserUpdateDispatch = DataPayload; +export type GatewayUserUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#user-update */ -export declare type GatewayUserUpdateDispatchData = APIUser; +export type GatewayUserUpdateDispatchData = APIUser; /** * https://discord.com/developers/docs/topics/gateway-events#voice-state-update */ -export declare type GatewayVoiceStateUpdateDispatch = DataPayload; +export type GatewayVoiceStateUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#voice-state-update */ -export declare type GatewayVoiceStateUpdateDispatchData = GatewayVoiceState; +export type GatewayVoiceStateUpdateDispatchData = GatewayVoiceState; /** * https://discord.com/developers/docs/topics/gateway-events#voice-server-update */ -export declare type GatewayVoiceServerUpdateDispatch = DataPayload; +export type GatewayVoiceServerUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#voice-server-update */ @@ -1309,7 +1313,7 @@ export interface GatewayVoiceServerUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#webhooks-update */ -export declare type GatewayWebhooksUpdateDispatch = DataPayload; +export type GatewayWebhooksUpdateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#webhooks-update */ @@ -1326,7 +1330,7 @@ export interface GatewayWebhooksUpdateDispatchData { /** * https://discord.com/developers/docs/topics/gateway-events#guild-audit-log-entry-create */ -export declare type GatewayGuildAuditLogEntryCreateDispatch = DataPayload; +export type GatewayGuildAuditLogEntryCreateDispatch = DataPayload; /** * https://discord.com/developers/docs/topics/gateway-events#guild-audit-log-entry-create */ @@ -1346,7 +1350,7 @@ export interface GatewayHeartbeat { /** * https://discord.com/developers/docs/topics/gateway#sending-heartbeats */ -export declare type GatewayHeartbeatData = number | null; +export type GatewayHeartbeatData = number | null; /** * https://discord.com/developers/docs/topics/gateway-events#identify */ @@ -1486,7 +1490,7 @@ export interface GatewayRequestGuildMembersDataWithQuery extends GatewayRequestG /** * https://discord.com/developers/docs/topics/gateway-events#request-guild-members */ -export declare type GatewayRequestGuildMembersData = GatewayRequestGuildMembersDataWithUserIds | GatewayRequestGuildMembersDataWithQuery; +export type GatewayRequestGuildMembersData = GatewayRequestGuildMembersDataWithUserIds | GatewayRequestGuildMembersDataWithQuery; /** * https://discord.com/developers/docs/topics/gateway-events#update-voice-state */ @@ -1550,7 +1554,7 @@ export interface GatewayPresenceUpdateData { /** * https://discord.com/developers/docs/topics/gateway-events#activity-object-activity-structure */ -export declare type GatewayActivityUpdateData = Pick; +export type GatewayActivityUpdateData = Pick; interface BasePayload { /** * Opcode for the payload @@ -1569,7 +1573,7 @@ interface BasePayload { */ t?: string; } -declare type NonDispatchPayload = Omit & { +type NonDispatchPayload = Omit & { t: null; s: null; }; @@ -1578,7 +1582,7 @@ interface DataPayload extends t: Event; d: D; } -declare type ReactionData = DataPayload = DataPayload\d{17,20})>/, @@ -22,6 +23,7 @@ exports.FormattingPatterns = { * Regular expression for matching a user mention, with or without a nickname * * The `id` group property is present on the `exec` result of this expression + * * @deprecated Passing `!` in user mentions is no longer necessary / supported, and future message contents won't have it */ UserWithOptionalNickname: /<@!?(?\d{17,20})>/, @@ -42,7 +44,9 @@ exports.FormattingPatterns = { * * The `fullName` (possibly including `name`, `subcommandOrGroup` and `subcommand`) and `id` group properties are present on the `exec` result of this expression */ - SlashCommand: /<\/(?(?[-_\p{Letter}\p{Number}\p{sc=Deva}\p{sc=Thai}]{1,32})(?: (?[-_\p{Letter}\p{Number}\p{sc=Deva}\p{sc=Thai}]{1,32}))?(?: (?[-_\p{Letter}\p{Number}\p{sc=Deva}\p{sc=Thai}]{1,32}))?):(?\d{17,20})>/u, + SlashCommand: + // eslint-disable-next-line unicorn/no-unsafe-regex + /<\/(?(?[-_\p{Letter}\p{Number}\p{sc=Deva}\p{sc=Thai}]{1,32})(?: (?[-_\p{Letter}\p{Number}\p{sc=Deva}\p{sc=Thai}]{1,32}))?(?: (?[-_\p{Letter}\p{Number}\p{sc=Deva}\p{sc=Thai}]{1,32}))?):(?\d{17,20})>/u, /** * Regular expression for matching a custom emoji, either static or animated * @@ -66,7 +70,8 @@ exports.FormattingPatterns = { * * The `timestamp` and `style` group properties are present on the `exec` result of this expression */ - Timestamp: /-?\d{1,13})(:(?