feat: init

This commit is contained in:
Nick 2024-08-10 02:59:22 -05:00
parent 8379d09058
commit 2cfa016090
2929 changed files with 299087 additions and 3 deletions

191
node_modules/@discordjs/ws/LICENSE generated vendored Normal file
View file

@ -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 Denis 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.

204
node_modules/@discordjs/ws/README.md generated vendored Normal file
View file

@ -0,0 +1,204 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://www.npmjs.com/package/@discordjs/ws"><img src="https://img.shields.io/npm/v/@discordjs/ws.svg?maxAge=3600" alt="npm version" /></a>
<a href="https://www.npmjs.com/package/@discordjs/ws"><img src="https://img.shields.io/npm/dt/@discordjs/ws.svg?maxAge=3600" alt="npm downloads" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=ws" alt="Code coverage" /></a>
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
<a href="https://www.cloudflare.com"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-workers.png" alt="Cloudflare Workers" height="44" /></a>
</p>
</div>
## About
`@discordjs/ws` is a powerful wrapper around Discord's gateway.
## Installation
**Node.js 16.11.0 or newer is required.**
```sh
npm install @discordjs/ws
yarn add @discordjs/ws
pnpm add @discordjs/ws
bun 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`)
## 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',
// Optionally, if you have custom messaging, like for analytic collection, you can use this:
async unknownPayloadHandler(data: any) {
// handle data here :3
},
}),
});
```
And your `worker.ts` file:
```ts
import { WorkerBootstrapper, WebSocketShardEvents } from '@discordjs/ws';
import { parentPort } from 'node:worker_threads';
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
});
},
});
// This will go to `unknownPayloadHandler` in the main thread, or be ignored if not provided
parentPort!.postMessage({ custom: 'data' });
```
## 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

2
node_modules/@discordjs/ws/dist/defaultWorker.d.mts generated vendored Normal file
View file

@ -0,0 +1,2 @@
export { }

2
node_modules/@discordjs/ws/dist/defaultWorker.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
export { }

1058
node_modules/@discordjs/ws/dist/defaultWorker.js generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@discordjs/ws/dist/defaultWorker.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

1040
node_modules/@discordjs/ws/dist/defaultWorker.mjs generated vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

704
node_modules/@discordjs/ws/dist/index.d.mts generated vendored Normal file
View file

@ -0,0 +1,704 @@
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
}
interface 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 {
resetAt: number;
sent: number;
}
declare class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
#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<void>;
private internalConnect;
destroy(options?: WebSocketShardDestroyOptions): Promise<void>;
private waitForEvent;
send(payload: GatewaySendPayload): Promise<void>;
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<void>;
/**
* Destroys all the shards
*/
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Awaitable<void>;
/**
* Fetches the status of all the shards
*/
fetchStatus(): Awaitable<Collection<number, WebSocketShardStatus>>;
/**
* Sends a payload to a shard
*/
send(shardId: number, payload: GatewaySendPayload): Awaitable<void>;
/**
* Spawns all the shards
*/
spawn(shardIds: number[]): Awaitable<void>;
}
/**
* 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<void>;
}
/**
* 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<void>;
/**
* {@inheritDoc IShardingStrategy.connect}
*/
connect(): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.destroy}
*/
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.send}
*/
send(shardId: number, payload: GatewaySendPayload): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.fetchStatus}
*/
fetchStatus(): Promise<Collection<number, WebSocketShardStatus>>;
}
/**
* 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<void>;
}
/**
* 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<SimpleIdentifyThrottler>;
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<GatewayOpcodes>;
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<IIdentifyThrottler>;
/**
* 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<SessionInfo | null> {
* // Fetch this info from redis or similar
* return { sessionId: string, sequence: number };
* // Return null if no information is found
* },
* });
* ```
*/
retrieveSessionInfo(shardId: number): Awaitable<SessionInfo | null>;
/**
* 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<void>;
/**
* The gateway version to use
*
* @defaultValue `'10'`
*/
version: string;
}
interface WebSocketManagerOptions extends OptionalWebSocketManagerOptions, RequiredWebSocketManagerOptions {
}
interface CreateWebSocketManagerOptions extends Partial<OptionalWebSocketManagerOptions>, RequiredWebSocketManagerOptions {
}
interface ManagerShardEventsMap {
[WebSocketShardEvents.Closed]: [{
code: number;
shardId: number;
}];
[WebSocketShardEvents.Debug]: [payload: {
message: string;
shardId: number;
}];
[WebSocketShardEvents.Dispatch]: [payload: {
data: GatewayDispatchPayload;
shardId: number;
}];
[WebSocketShardEvents.Error]: [payload: {
error: Error;
shardId: number;
}];
[WebSocketShardEvents.Hello]: [{
shardId: number;
}];
[WebSocketShardEvents.Ready]: [payload: {
data: GatewayReadyDispatchData;
shardId: number;
}];
[WebSocketShardEvents.Resumed]: [{
shardId: number;
}];
[WebSocketShardEvents.HeartbeatComplete]: [
payload: {
ackAt: number;
heartbeatAt: number;
latency: number;
shardId: number;
}
];
}
declare class WebSocketManager extends AsyncEventEmitter<ManagerShardEventsMap> implements AsyncDisposable {
/**
* 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: CreateWebSocketManagerOptions);
/**
* 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<APIGatewayBotInfo>;
/**
* 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<this>;
/**
* Yields the total number of shards across for your bot, accounting for Discord recommendations
*/
getShardCount(): Promise<number>;
/**
* Yields the ids of the shards this manager should manage
*/
getShardIds(force?: boolean): Promise<number[]>;
connect(): Promise<void>;
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Awaitable<void>;
send(shardId: number, payload: GatewaySendPayload): Awaitable<void>;
fetchStatus(): Awaitable<_discordjs_collection.Collection<number, WebSocketShardStatus>>;
[Symbol.asyncDispose](): Promise<void>;
}
interface FetchingStrategyOptions extends Omit<WebSocketManagerOptions, 'buildIdentifyThrottler' | 'buildStrategy' | 'rest' | 'retrieveSessionInfo' | 'shardCount' | 'shardIds' | 'updateSessionInfo'> {
readonly gatewayInformation: APIGatewayBotInfo;
readonly shardCount: number;
}
/**
* Strategies responsible solely for making manager information accessible
*/
interface IContextFetchingStrategy {
readonly options: FetchingStrategyOptions;
retrieveSessionInfo(shardId: number): Awaitable<SessionInfo | null>;
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable<void>;
/**
* Resolves once the given shard should be allowed to identify
* This should correctly handle the signal and reject with an abort error if the operation is aborted.
* Other errors will cause the shard to reconnect.
*/
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
declare function managerToFetchingStrategyOptions(manager: WebSocketManager): Promise<FetchingStrategyOptions>;
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<SessionInfo | null>;
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): _discordjs_util.Awaitable<void>;
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
declare class WorkerContextFetchingStrategy implements IContextFetchingStrategy {
readonly options: FetchingStrategyOptions;
private readonly sessionPromises;
private readonly waitForIdentifyPromises;
constructor(options: FetchingStrategyOptions);
retrieveSessionInfo(shardId: number): Promise<SessionInfo | null>;
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): void;
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
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';
/**
* Handles a payload not recognized by the handler.
*/
unknownPayloadHandler?(payload: any): unknown;
/**
* 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<void>;
/**
* {@inheritDoc IShardingStrategy.connect}
*/
connect(): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.destroy}
*/
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.send}
*/
send(shardId: number, data: GatewaySendPayload): void;
/**
* {@inheritDoc IShardingStrategy.fetchStatus}
*/
fetchStatus(): Promise<Collection<number, WebSocketShardStatus>>;
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<void>;
}
/**
* 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<number, WebSocketShard>;
constructor();
/**
* Helper method to initiate a shard's connection process
*/
protected connect(shardId: number): Promise<void>;
/**
* Helper method to destroy a shard
*/
protected destroy(shardId: number, options?: WebSocketShardDestroyOptions): Promise<void>;
/**
* Helper method to attach event listeners to the parentPort
*/
protected setupThreadEvents(): void;
/**
* Bootstraps the worker thread with the provided options
*/
bootstrap(options?: Readonly<BootstrapOptions>): Promise<void>;
}
/**
* 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 { type BootstrapOptions, CloseCodes, CompressionMethod, type CreateWebSocketManagerOptions, DefaultDeviceProperty, DefaultWebSocketManagerOptions, Encoding, type FetchingStrategyOptions, type IContextFetchingStrategy, type IIdentifyThrottler, type IShardingStrategy, type IdentifyState, ImportantGatewayOpcodes, type ManagerShardEventsMap, type OptionalWebSocketManagerOptions, type RequiredWebSocketManagerOptions, type SendRateLimitState, type SessionInfo, type ShardRange, SimpleContextFetchingStrategy, SimpleIdentifyThrottler, SimpleShardingStrategy, WebSocketManager, type WebSocketManagerOptions, WebSocketShard, type WebSocketShardDestroyOptions, WebSocketShardDestroyRecovery, WebSocketShardEvents, type WebSocketShardEventsMap, WebSocketShardStatus, WorkerBootstrapper, WorkerContextFetchingStrategy, type WorkerData, type WorkerReceivePayload, WorkerReceivePayloadOp, type WorkerSendPayload, WorkerSendPayloadOp, WorkerShardingStrategy, type WorkerShardingStrategyOptions, getInitialSendRateLimitState, managerToFetchingStrategyOptions, version };

704
node_modules/@discordjs/ws/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,704 @@
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
}
interface 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 {
resetAt: number;
sent: number;
}
declare class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
#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<void>;
private internalConnect;
destroy(options?: WebSocketShardDestroyOptions): Promise<void>;
private waitForEvent;
send(payload: GatewaySendPayload): Promise<void>;
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<void>;
/**
* Destroys all the shards
*/
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Awaitable<void>;
/**
* Fetches the status of all the shards
*/
fetchStatus(): Awaitable<Collection<number, WebSocketShardStatus>>;
/**
* Sends a payload to a shard
*/
send(shardId: number, payload: GatewaySendPayload): Awaitable<void>;
/**
* Spawns all the shards
*/
spawn(shardIds: number[]): Awaitable<void>;
}
/**
* 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<void>;
}
/**
* 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<void>;
/**
* {@inheritDoc IShardingStrategy.connect}
*/
connect(): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.destroy}
*/
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.send}
*/
send(shardId: number, payload: GatewaySendPayload): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.fetchStatus}
*/
fetchStatus(): Promise<Collection<number, WebSocketShardStatus>>;
}
/**
* 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<void>;
}
/**
* 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<SimpleIdentifyThrottler>;
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<GatewayOpcodes>;
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<IIdentifyThrottler>;
/**
* 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<SessionInfo | null> {
* // Fetch this info from redis or similar
* return { sessionId: string, sequence: number };
* // Return null if no information is found
* },
* });
* ```
*/
retrieveSessionInfo(shardId: number): Awaitable<SessionInfo | null>;
/**
* 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<void>;
/**
* The gateway version to use
*
* @defaultValue `'10'`
*/
version: string;
}
interface WebSocketManagerOptions extends OptionalWebSocketManagerOptions, RequiredWebSocketManagerOptions {
}
interface CreateWebSocketManagerOptions extends Partial<OptionalWebSocketManagerOptions>, RequiredWebSocketManagerOptions {
}
interface ManagerShardEventsMap {
[WebSocketShardEvents.Closed]: [{
code: number;
shardId: number;
}];
[WebSocketShardEvents.Debug]: [payload: {
message: string;
shardId: number;
}];
[WebSocketShardEvents.Dispatch]: [payload: {
data: GatewayDispatchPayload;
shardId: number;
}];
[WebSocketShardEvents.Error]: [payload: {
error: Error;
shardId: number;
}];
[WebSocketShardEvents.Hello]: [{
shardId: number;
}];
[WebSocketShardEvents.Ready]: [payload: {
data: GatewayReadyDispatchData;
shardId: number;
}];
[WebSocketShardEvents.Resumed]: [{
shardId: number;
}];
[WebSocketShardEvents.HeartbeatComplete]: [
payload: {
ackAt: number;
heartbeatAt: number;
latency: number;
shardId: number;
}
];
}
declare class WebSocketManager extends AsyncEventEmitter<ManagerShardEventsMap> implements AsyncDisposable {
/**
* 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: CreateWebSocketManagerOptions);
/**
* 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<APIGatewayBotInfo>;
/**
* 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<this>;
/**
* Yields the total number of shards across for your bot, accounting for Discord recommendations
*/
getShardCount(): Promise<number>;
/**
* Yields the ids of the shards this manager should manage
*/
getShardIds(force?: boolean): Promise<number[]>;
connect(): Promise<void>;
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Awaitable<void>;
send(shardId: number, payload: GatewaySendPayload): Awaitable<void>;
fetchStatus(): Awaitable<_discordjs_collection.Collection<number, WebSocketShardStatus>>;
[Symbol.asyncDispose](): Promise<void>;
}
interface FetchingStrategyOptions extends Omit<WebSocketManagerOptions, 'buildIdentifyThrottler' | 'buildStrategy' | 'rest' | 'retrieveSessionInfo' | 'shardCount' | 'shardIds' | 'updateSessionInfo'> {
readonly gatewayInformation: APIGatewayBotInfo;
readonly shardCount: number;
}
/**
* Strategies responsible solely for making manager information accessible
*/
interface IContextFetchingStrategy {
readonly options: FetchingStrategyOptions;
retrieveSessionInfo(shardId: number): Awaitable<SessionInfo | null>;
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable<void>;
/**
* Resolves once the given shard should be allowed to identify
* This should correctly handle the signal and reject with an abort error if the operation is aborted.
* Other errors will cause the shard to reconnect.
*/
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
declare function managerToFetchingStrategyOptions(manager: WebSocketManager): Promise<FetchingStrategyOptions>;
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<SessionInfo | null>;
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): _discordjs_util.Awaitable<void>;
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
declare class WorkerContextFetchingStrategy implements IContextFetchingStrategy {
readonly options: FetchingStrategyOptions;
private readonly sessionPromises;
private readonly waitForIdentifyPromises;
constructor(options: FetchingStrategyOptions);
retrieveSessionInfo(shardId: number): Promise<SessionInfo | null>;
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): void;
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
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';
/**
* Handles a payload not recognized by the handler.
*/
unknownPayloadHandler?(payload: any): unknown;
/**
* 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<void>;
/**
* {@inheritDoc IShardingStrategy.connect}
*/
connect(): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.destroy}
*/
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.send}
*/
send(shardId: number, data: GatewaySendPayload): void;
/**
* {@inheritDoc IShardingStrategy.fetchStatus}
*/
fetchStatus(): Promise<Collection<number, WebSocketShardStatus>>;
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<void>;
}
/**
* 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<number, WebSocketShard>;
constructor();
/**
* Helper method to initiate a shard's connection process
*/
protected connect(shardId: number): Promise<void>;
/**
* Helper method to destroy a shard
*/
protected destroy(shardId: number, options?: WebSocketShardDestroyOptions): Promise<void>;
/**
* Helper method to attach event listeners to the parentPort
*/
protected setupThreadEvents(): void;
/**
* Bootstraps the worker thread with the provided options
*/
bootstrap(options?: Readonly<BootstrapOptions>): Promise<void>;
}
/**
* 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 { type BootstrapOptions, CloseCodes, CompressionMethod, type CreateWebSocketManagerOptions, DefaultDeviceProperty, DefaultWebSocketManagerOptions, Encoding, type FetchingStrategyOptions, type IContextFetchingStrategy, type IIdentifyThrottler, type IShardingStrategy, type IdentifyState, ImportantGatewayOpcodes, type ManagerShardEventsMap, type OptionalWebSocketManagerOptions, type RequiredWebSocketManagerOptions, type SendRateLimitState, type SessionInfo, type ShardRange, SimpleContextFetchingStrategy, SimpleIdentifyThrottler, SimpleShardingStrategy, WebSocketManager, type WebSocketManagerOptions, WebSocketShard, type WebSocketShardDestroyOptions, WebSocketShardDestroyRecovery, WebSocketShardEvents, type WebSocketShardEventsMap, WebSocketShardStatus, WorkerBootstrapper, WorkerContextFetchingStrategy, type WorkerData, type WorkerReceivePayload, WorkerReceivePayloadOp, type WorkerSendPayload, WorkerSendPayloadOp, WorkerShardingStrategy, type WorkerShardingStrategyOptions, getInitialSendRateLimitState, managerToFetchingStrategyOptions, version };

1505
node_modules/@discordjs/ws/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@discordjs/ws/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

1469
node_modules/@discordjs/ws/dist/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@discordjs/ws/dist/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2021 Noel Buechler
Copyright 2015 Amish Shah
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,67 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://www.npmjs.com/package/@discordjs/collection"><img src="https://img.shields.io/npm/v/@discordjs/collection.svg?maxAge=3600" alt="npm version" /></a>
<a href="https://www.npmjs.com/package/@discordjs/collection"><img src="https://img.shields.io/npm/dt/@discordjs/collection.svg?maxAge=3600" alt="npm downloads" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=collection" alt="Code coverage" /></a>
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
<a href="https://www.cloudflare.com"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-workers.png" alt="Cloudflare Workers" height="44" /></a>
</p>
</div>
## About
`@discordjs/collection` is a powerful utility data structure used in discord.js.
## Installation
**Node.js 18 or newer is required.**
```sh
npm install @discordjs/collection
yarn add @discordjs/collection
pnpm add @discordjs/collection
```
## Links
- [Website][website] ([source][website-source])
- [Documentation][documentation]
- [Guide][guide] ([source][guide-source])
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/collection/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/collection
[npm]: https://www.npmjs.com/package/@discordjs/collection
[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries
[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md

View file

@ -0,0 +1,535 @@
/**
* @internal
*/
interface CollectionConstructor {
new (): Collection<unknown, unknown>;
new <Key, Value>(entries?: readonly (readonly [Key, Value])[] | null): Collection<Key, Value>;
new <Key, Value>(iterable: Iterable<readonly [Key, Value]>): Collection<Key, Value>;
readonly prototype: Collection<unknown, unknown>;
readonly [Symbol.species]: CollectionConstructor;
}
/**
* Represents an immutable version of a collection
*/
type ReadonlyCollection<Key, Value> = Omit<Collection<Key, Value>, 'clear' | 'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'> & ReadonlyMap<Key, Value>;
/**
* Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself
*
* @internal
*/
interface Collection<Key, Value> extends Map<Key, Value> {
constructor: CollectionConstructor;
}
/**
* A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has
* an ID, for significantly improved performance and ease-of-use.
*
* @typeParam Key - The key type this collection holds
* @typeParam Value - The value type this collection holds
*/
declare class Collection<Key, Value> extends Map<Key, Value> {
/**
* 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: Key, defaultValueGenerator: (key: Key, collection: this) => Value): Value;
/**
* 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: Key[]): boolean;
/**
* Checks if any of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if any of the elements exist, `false` if none exist.
*/
hasAny(...keys: Key[]): boolean;
/**
* Obtains the first value(s) in this collection.
*
* @param amount - Amount of values to obtain from the beginning
* @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative
*/
first(): Value | undefined;
first(amount: number): Value[];
/**
* Obtains the first key(s) in this collection.
*
* @param amount - Amount of keys to obtain from the beginning
* @returns A single key if no amount is provided or an array of keys, starting from the end if
* amount is negative
*/
firstKey(): Key | undefined;
firstKey(amount: number): Key[];
/**
* Obtains the last value(s) in this collection.
*
* @param amount - Amount of values to obtain from the end
* @returns A single value if no amount is provided or an array of values, starting from the start if
* amount is negative
*/
last(): Value | undefined;
last(amount: number): Value[];
/**
* Obtains the last key(s) in this collection.
*
* @param amount - Amount of keys to obtain from the end
* @returns A single key if no amount is provided or an array of keys, starting from the start if
* amount is negative
*/
lastKey(): Key | undefined;
lastKey(amount: number): Key[];
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the item at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the element to obtain
*/
at(index: number): Value | undefined;
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the key at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the key to obtain
*/
keyAt(index: number): Key | undefined;
/**
* Obtains unique random value(s) from this collection.
*
* @param amount - Amount of values to obtain randomly
* @returns A single value if no amount is provided or an array of values
*/
random(): Value | undefined;
random(amount: number): Value[];
/**
* Obtains unique random key(s) from this collection.
*
* @param amount - Amount of keys to obtain randomly
* @returns A single key if no amount is provided or an array
*/
randomKey(): Key | undefined;
randomKey(amount: number): Key[];
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}
* but returns a Collection instead of an Array.
*/
reverse(): this;
/**
* Searches for a single item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.
* All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you
* should use the `get` method. See
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.find(user => user.username === 'Bob');
* ```
*/
find<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): NewValue | undefined;
find(fn: (value: Value, key: Key, collection: this) => unknown): Value | undefined;
find<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): NewValue | undefined;
find<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Value | undefined;
/**
* Searches for the key of a single item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},
* but returns the key rather than the positional index.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.findKey(user => user.username === 'Bob');
* ```
*/
findKey<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): NewKey | undefined;
findKey(fn: (value: Value, key: Key, collection: this) => unknown): Key | undefined;
findKey<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): NewKey | undefined;
findKey<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Key | undefined;
/**
* Searches for a last item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLast | Array.findLast()}.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
*/
findLast<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): NewValue | undefined;
findLast(fn: (value: Value, key: Key, collection: this) => unknown): Value | undefined;
findLast<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): NewValue | undefined;
findLast<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Value | undefined;
/**
* Searches for the key of a last item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLastIndex | Array.findLastIndex()},
* but returns the key rather than the positional index.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
*/
findLastKey<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): NewKey | undefined;
findLastKey(fn: (value: Value, key: Key, collection: this) => unknown): Key | undefined;
findLastKey<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): NewKey | undefined;
findLastKey<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Key | undefined;
/**
* Removes items that satisfy the provided filter function.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @returns The number of removed entries
*/
sweep(fn: (value: Value, key: Key, collection: this) => unknown): number;
sweep<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): number;
/**
* Identical to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},
* but returns a Collection instead of an Array.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.filter(user => user.username === 'Bob');
* ```
*/
filter<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): Collection<NewKey, Value>;
filter<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): Collection<Key, NewValue>;
filter(fn: (value: Value, key: Key, collection: this) => unknown): Collection<Key, Value>;
filter<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): Collection<NewKey, Value>;
filter<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): Collection<Key, NewValue>;
filter<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Collection<Key, Value>;
/**
* Partitions the collection into two collections where the first collection
* contains the items that passed and the second contains the items that failed.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* const [big, small] = collection.partition(guild => guild.memberCount > 250);
* ```
*/
partition<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): [Collection<NewKey, Value>, Collection<Exclude<Key, NewKey>, Value>];
partition<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): [Collection<Key, NewValue>, Collection<Key, Exclude<Value, NewValue>>];
partition(fn: (value: Value, key: Key, collection: this) => unknown): [Collection<Key, Value>, Collection<Key, Value>];
partition<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): [Collection<NewKey, Value>, Collection<Exclude<Key, NewKey>, Value>];
partition<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): [Collection<Key, NewValue>, Collection<Key, Exclude<Value, NewValue>>];
partition<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): [Collection<Key, Value>, Collection<Key, Value>];
/**
* Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.
*
* @param fn - Function that produces a new Collection
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.flatMap(guild => guild.members.cache);
* ```
*/
flatMap<NewValue>(fn: (value: Value, key: Key, collection: this) => Collection<Key, NewValue>): Collection<Key, NewValue>;
flatMap<NewValue, This>(fn: (this: This, value: Value, key: Key, collection: this) => Collection<Key, NewValue>, thisArg: This): Collection<Key, NewValue>;
/**
* Maps each item to another value into an array. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.
*
* @param fn - Function that produces an element of the new array, taking three arguments
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.map(user => user.tag);
* ```
*/
map<NewValue>(fn: (value: Value, key: Key, collection: this) => NewValue): NewValue[];
map<This, NewValue>(fn: (this: This, value: Value, key: Key, collection: this) => NewValue, thisArg: This): NewValue[];
/**
* Maps each item to another value into a collection. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.
*
* @param fn - Function that produces an element of the new collection, taking three arguments
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.mapValues(user => user.tag);
* ```
*/
mapValues<NewValue>(fn: (value: Value, key: Key, collection: this) => NewValue): Collection<Key, NewValue>;
mapValues<This, NewValue>(fn: (this: This, value: Value, key: Key, collection: this) => NewValue, thisArg: This): Collection<Key, NewValue>;
/**
* Checks if there exists an item that passes a test. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.some(user => user.discriminator === '0000');
* ```
*/
some(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
some<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean;
/**
* Checks if all items passes a test. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.every(user => !user.bot);
* ```
*/
every<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): this is Collection<NewKey, Value>;
every<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): this is Collection<Key, NewValue>;
every(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
every<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): this is Collection<NewKey, Value>;
every<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): this is Collection<Key, NewValue>;
every<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean;
/**
* Applies a function to produce a single value. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,
* and `collection`
* @param initialValue - Starting value for the accumulator
* @example
* ```ts
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
reduce<InitialValue = Value>(fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue, initialValue?: InitialValue): InitialValue;
/**
* 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/reduceRight | Array.reduceRight()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `value`, `key`, and `collection`
* @param initialValue - Starting value for the accumulator
*/
reduceRight<InitialValue>(fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue, initialValue?: InitialValue): InitialValue;
/**
* Identical to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},
* but returns the collection instead of undefined.
*
* @param fn - Function to execute for each element
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection
* .each(user => console.log(user.username))
* .filter(user => user.bot)
* .each(user => console.log(user.username));
* ```
*/
each(fn: (value: Value, key: Key, collection: this) => void): this;
each<This>(fn: (this: This, value: Value, key: Key, collection: this) => void, thisArg: This): this;
/**
* Runs a function on the collection and returns the collection.
*
* @param fn - Function to execute
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection
* .tap(coll => console.log(coll.size))
* .filter(user => user.bot)
* .tap(coll => console.log(coll.size))
* ```
*/
tap(fn: (collection: this) => void): this;
tap<This>(fn: (this: This, collection: this) => void, thisArg: This): this;
/**
* Creates an identical shallow copy of this collection.
*
* @example
* ```ts
* const newColl = someColl.clone();
* ```
*/
clone(): Collection<Key, Value>;
/**
* Combines this collection with others into a new collection. None of the source collections are modified.
*
* @param collections - Collections to merge
* @example
* ```ts
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ```
*/
concat(...collections: ReadonlyCollection<Key, Value>[]): Collection<Key, Value>;
/**
* Checks if this collection shares identical items with another.
* This is different to checking for equality using equal-signs, because
* the collections may be different objects, but contain the same data.
*
* @param collection - Collection to compare with
* @returns Whether the collections have identical contents
*/
equals(collection: ReadonlyCollection<Key, Value>): boolean;
/**
* The sort method sorts the items of a collection in place and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.
* @example
* ```ts
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sort(compareFunction?: Comparator<Key, Value>): this;
/**
* The intersection method returns a new collection containing the items where the key is present in both collections.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* const intersection = col1.intersection(col2);
* console.log(col1.intersection(col2));
* // => Collection { 'a' => 1 }
* ```
*/
intersection(other: ReadonlyCollection<Key, any>): Collection<Key, Value>;
/**
* Returns a new collection containing the items where the key is present in either of the collections.
*
* @remarks
*
* If the collections have any items with the same key, the value from the first collection will be used.
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['b', 3], ['c', 3]]);
* const union = col1.union(col2);
* console.log(union);
* // => Collection { 'a' => 1, 'b' => 2, 'c' => 3 }
* ```
*/
union<OtherValue>(other: ReadonlyCollection<Key, OtherValue>): Collection<Key, OtherValue | Value>;
/**
* Returns a new collection containing the items where the key is present in this collection but not the other.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* console.log(col1.difference(col2));
* // => Collection { 'b' => 2 }
* console.log(col2.difference(col1));
* // => Collection { 'c' => 3 }
* ```
*/
difference(other: ReadonlyCollection<Key, any>): Collection<Key, Value>;
/**
* Returns a new collection containing only the items where the keys are present in either collection, but not both.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* const symmetricDifference = col1.symmetricDifference(col2);
* console.log(col1.symmetricDifference(col2));
* // => Collection { 'b' => 2, 'c' => 3 }
* ```
*/
symmetricDifference<OtherValue>(other: ReadonlyCollection<Key, OtherValue>): Collection<Key, OtherValue | Value>;
/**
* 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<OtherValue, ResultValue>(other: ReadonlyCollection<Key, OtherValue>, whenInSelf: (value: Value, key: Key) => Keep<ResultValue>, whenInOther: (valueOther: OtherValue, key: Key) => Keep<ResultValue>, whenInBoth: (value: Value, valueOther: OtherValue, key: Key) => Keep<ResultValue>): Collection<Key, ResultValue>;
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed | Array.toReversed()}
* but returns a Collection instead of an Array.
*/
toReversed(): Collection<Key, Value>;
/**
* 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);
* ```
*/
toSorted(compareFunction?: Comparator<Key, Value>): Collection<Key, Value>;
toJSON(): [Key, Value][];
private static defaultSort;
/**
* Creates a Collection from a list of entries.
*
* @param entries - The list of entries
* @param combine - Function to combine an existing entry with a new one
* @example
* ```ts
* Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
* // returns Collection { "a" => 3, "b" => 2 }
* ```
*/
static combineEntries<Key, Value>(entries: Iterable<[Key, Value]>, combine: (firstValue: Value, secondValue: Value, key: Key) => Value): Collection<Key, Value>;
}
/**
* @internal
*/
type Keep<Value> = {
keep: false;
} | {
keep: true;
value: Value;
};
/**
* @internal
*/
type Comparator<Key, Value> = (firstValue: Value, secondValue: Value, firstKey: Key, secondKey: Key) => number;
/**
* The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection#readme | @discordjs/collection} version
* that you are currently using.
*/
declare const version: string;
export { Collection, type CollectionConstructor, type Comparator, type Keep, type ReadonlyCollection, version };

View file

@ -0,0 +1,535 @@
/**
* @internal
*/
interface CollectionConstructor {
new (): Collection<unknown, unknown>;
new <Key, Value>(entries?: readonly (readonly [Key, Value])[] | null): Collection<Key, Value>;
new <Key, Value>(iterable: Iterable<readonly [Key, Value]>): Collection<Key, Value>;
readonly prototype: Collection<unknown, unknown>;
readonly [Symbol.species]: CollectionConstructor;
}
/**
* Represents an immutable version of a collection
*/
type ReadonlyCollection<Key, Value> = Omit<Collection<Key, Value>, 'clear' | 'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'> & ReadonlyMap<Key, Value>;
/**
* Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself
*
* @internal
*/
interface Collection<Key, Value> extends Map<Key, Value> {
constructor: CollectionConstructor;
}
/**
* A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has
* an ID, for significantly improved performance and ease-of-use.
*
* @typeParam Key - The key type this collection holds
* @typeParam Value - The value type this collection holds
*/
declare class Collection<Key, Value> extends Map<Key, Value> {
/**
* 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: Key, defaultValueGenerator: (key: Key, collection: this) => Value): Value;
/**
* 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: Key[]): boolean;
/**
* Checks if any of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if any of the elements exist, `false` if none exist.
*/
hasAny(...keys: Key[]): boolean;
/**
* Obtains the first value(s) in this collection.
*
* @param amount - Amount of values to obtain from the beginning
* @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative
*/
first(): Value | undefined;
first(amount: number): Value[];
/**
* Obtains the first key(s) in this collection.
*
* @param amount - Amount of keys to obtain from the beginning
* @returns A single key if no amount is provided or an array of keys, starting from the end if
* amount is negative
*/
firstKey(): Key | undefined;
firstKey(amount: number): Key[];
/**
* Obtains the last value(s) in this collection.
*
* @param amount - Amount of values to obtain from the end
* @returns A single value if no amount is provided or an array of values, starting from the start if
* amount is negative
*/
last(): Value | undefined;
last(amount: number): Value[];
/**
* Obtains the last key(s) in this collection.
*
* @param amount - Amount of keys to obtain from the end
* @returns A single key if no amount is provided or an array of keys, starting from the start if
* amount is negative
*/
lastKey(): Key | undefined;
lastKey(amount: number): Key[];
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the item at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the element to obtain
*/
at(index: number): Value | undefined;
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the key at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the key to obtain
*/
keyAt(index: number): Key | undefined;
/**
* Obtains unique random value(s) from this collection.
*
* @param amount - Amount of values to obtain randomly
* @returns A single value if no amount is provided or an array of values
*/
random(): Value | undefined;
random(amount: number): Value[];
/**
* Obtains unique random key(s) from this collection.
*
* @param amount - Amount of keys to obtain randomly
* @returns A single key if no amount is provided or an array
*/
randomKey(): Key | undefined;
randomKey(amount: number): Key[];
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}
* but returns a Collection instead of an Array.
*/
reverse(): this;
/**
* Searches for a single item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.
* All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you
* should use the `get` method. See
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.find(user => user.username === 'Bob');
* ```
*/
find<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): NewValue | undefined;
find(fn: (value: Value, key: Key, collection: this) => unknown): Value | undefined;
find<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): NewValue | undefined;
find<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Value | undefined;
/**
* Searches for the key of a single item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},
* but returns the key rather than the positional index.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.findKey(user => user.username === 'Bob');
* ```
*/
findKey<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): NewKey | undefined;
findKey(fn: (value: Value, key: Key, collection: this) => unknown): Key | undefined;
findKey<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): NewKey | undefined;
findKey<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Key | undefined;
/**
* Searches for a last item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLast | Array.findLast()}.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
*/
findLast<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): NewValue | undefined;
findLast(fn: (value: Value, key: Key, collection: this) => unknown): Value | undefined;
findLast<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): NewValue | undefined;
findLast<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Value | undefined;
/**
* Searches for the key of a last item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLastIndex | Array.findLastIndex()},
* but returns the key rather than the positional index.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
*/
findLastKey<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): NewKey | undefined;
findLastKey(fn: (value: Value, key: Key, collection: this) => unknown): Key | undefined;
findLastKey<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): NewKey | undefined;
findLastKey<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Key | undefined;
/**
* Removes items that satisfy the provided filter function.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @returns The number of removed entries
*/
sweep(fn: (value: Value, key: Key, collection: this) => unknown): number;
sweep<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): number;
/**
* Identical to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},
* but returns a Collection instead of an Array.
*
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.filter(user => user.username === 'Bob');
* ```
*/
filter<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): Collection<NewKey, Value>;
filter<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): Collection<Key, NewValue>;
filter(fn: (value: Value, key: Key, collection: this) => unknown): Collection<Key, Value>;
filter<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): Collection<NewKey, Value>;
filter<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): Collection<Key, NewValue>;
filter<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Collection<Key, Value>;
/**
* Partitions the collection into two collections where the first collection
* contains the items that passed and the second contains the items that failed.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* const [big, small] = collection.partition(guild => guild.memberCount > 250);
* ```
*/
partition<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): [Collection<NewKey, Value>, Collection<Exclude<Key, NewKey>, Value>];
partition<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): [Collection<Key, NewValue>, Collection<Key, Exclude<Value, NewValue>>];
partition(fn: (value: Value, key: Key, collection: this) => unknown): [Collection<Key, Value>, Collection<Key, Value>];
partition<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): [Collection<NewKey, Value>, Collection<Exclude<Key, NewKey>, Value>];
partition<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): [Collection<Key, NewValue>, Collection<Key, Exclude<Value, NewValue>>];
partition<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): [Collection<Key, Value>, Collection<Key, Value>];
/**
* Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.
*
* @param fn - Function that produces a new Collection
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.flatMap(guild => guild.members.cache);
* ```
*/
flatMap<NewValue>(fn: (value: Value, key: Key, collection: this) => Collection<Key, NewValue>): Collection<Key, NewValue>;
flatMap<NewValue, This>(fn: (this: This, value: Value, key: Key, collection: this) => Collection<Key, NewValue>, thisArg: This): Collection<Key, NewValue>;
/**
* Maps each item to another value into an array. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.
*
* @param fn - Function that produces an element of the new array, taking three arguments
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.map(user => user.tag);
* ```
*/
map<NewValue>(fn: (value: Value, key: Key, collection: this) => NewValue): NewValue[];
map<This, NewValue>(fn: (this: This, value: Value, key: Key, collection: this) => NewValue, thisArg: This): NewValue[];
/**
* Maps each item to another value into a collection. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.
*
* @param fn - Function that produces an element of the new collection, taking three arguments
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.mapValues(user => user.tag);
* ```
*/
mapValues<NewValue>(fn: (value: Value, key: Key, collection: this) => NewValue): Collection<Key, NewValue>;
mapValues<This, NewValue>(fn: (this: This, value: Value, key: Key, collection: this) => NewValue, thisArg: This): Collection<Key, NewValue>;
/**
* Checks if there exists an item that passes a test. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.some(user => user.discriminator === '0000');
* ```
*/
some(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
some<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean;
/**
* Checks if all items passes a test. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection.every(user => !user.bot);
* ```
*/
every<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): this is Collection<NewKey, Value>;
every<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): this is Collection<Key, NewValue>;
every(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
every<This, NewKey extends Key>(fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey, thisArg: This): this is Collection<NewKey, Value>;
every<This, NewValue extends Value>(fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue, thisArg: This): this is Collection<Key, NewValue>;
every<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean;
/**
* Applies a function to produce a single value. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,
* and `collection`
* @param initialValue - Starting value for the accumulator
* @example
* ```ts
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
reduce<InitialValue = Value>(fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue, initialValue?: InitialValue): InitialValue;
/**
* 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/reduceRight | Array.reduceRight()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `value`, `key`, and `collection`
* @param initialValue - Starting value for the accumulator
*/
reduceRight<InitialValue>(fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue, initialValue?: InitialValue): InitialValue;
/**
* Identical to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},
* but returns the collection instead of undefined.
*
* @param fn - Function to execute for each element
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection
* .each(user => console.log(user.username))
* .filter(user => user.bot)
* .each(user => console.log(user.username));
* ```
*/
each(fn: (value: Value, key: Key, collection: this) => void): this;
each<This>(fn: (this: This, value: Value, key: Key, collection: this) => void, thisArg: This): this;
/**
* Runs a function on the collection and returns the collection.
*
* @param fn - Function to execute
* @param thisArg - Value to use as `this` when executing the function
* @example
* ```ts
* collection
* .tap(coll => console.log(coll.size))
* .filter(user => user.bot)
* .tap(coll => console.log(coll.size))
* ```
*/
tap(fn: (collection: this) => void): this;
tap<This>(fn: (this: This, collection: this) => void, thisArg: This): this;
/**
* Creates an identical shallow copy of this collection.
*
* @example
* ```ts
* const newColl = someColl.clone();
* ```
*/
clone(): Collection<Key, Value>;
/**
* Combines this collection with others into a new collection. None of the source collections are modified.
*
* @param collections - Collections to merge
* @example
* ```ts
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ```
*/
concat(...collections: ReadonlyCollection<Key, Value>[]): Collection<Key, Value>;
/**
* Checks if this collection shares identical items with another.
* This is different to checking for equality using equal-signs, because
* the collections may be different objects, but contain the same data.
*
* @param collection - Collection to compare with
* @returns Whether the collections have identical contents
*/
equals(collection: ReadonlyCollection<Key, Value>): boolean;
/**
* The sort method sorts the items of a collection in place and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.
* @example
* ```ts
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sort(compareFunction?: Comparator<Key, Value>): this;
/**
* The intersection method returns a new collection containing the items where the key is present in both collections.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* const intersection = col1.intersection(col2);
* console.log(col1.intersection(col2));
* // => Collection { 'a' => 1 }
* ```
*/
intersection(other: ReadonlyCollection<Key, any>): Collection<Key, Value>;
/**
* Returns a new collection containing the items where the key is present in either of the collections.
*
* @remarks
*
* If the collections have any items with the same key, the value from the first collection will be used.
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['b', 3], ['c', 3]]);
* const union = col1.union(col2);
* console.log(union);
* // => Collection { 'a' => 1, 'b' => 2, 'c' => 3 }
* ```
*/
union<OtherValue>(other: ReadonlyCollection<Key, OtherValue>): Collection<Key, OtherValue | Value>;
/**
* Returns a new collection containing the items where the key is present in this collection but not the other.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* console.log(col1.difference(col2));
* // => Collection { 'b' => 2 }
* console.log(col2.difference(col1));
* // => Collection { 'c' => 3 }
* ```
*/
difference(other: ReadonlyCollection<Key, any>): Collection<Key, Value>;
/**
* Returns a new collection containing only the items where the keys are present in either collection, but not both.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* const symmetricDifference = col1.symmetricDifference(col2);
* console.log(col1.symmetricDifference(col2));
* // => Collection { 'b' => 2, 'c' => 3 }
* ```
*/
symmetricDifference<OtherValue>(other: ReadonlyCollection<Key, OtherValue>): Collection<Key, OtherValue | Value>;
/**
* 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<OtherValue, ResultValue>(other: ReadonlyCollection<Key, OtherValue>, whenInSelf: (value: Value, key: Key) => Keep<ResultValue>, whenInOther: (valueOther: OtherValue, key: Key) => Keep<ResultValue>, whenInBoth: (value: Value, valueOther: OtherValue, key: Key) => Keep<ResultValue>): Collection<Key, ResultValue>;
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed | Array.toReversed()}
* but returns a Collection instead of an Array.
*/
toReversed(): Collection<Key, Value>;
/**
* 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);
* ```
*/
toSorted(compareFunction?: Comparator<Key, Value>): Collection<Key, Value>;
toJSON(): [Key, Value][];
private static defaultSort;
/**
* Creates a Collection from a list of entries.
*
* @param entries - The list of entries
* @param combine - Function to combine an existing entry with a new one
* @example
* ```ts
* Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
* // returns Collection { "a" => 3, "b" => 2 }
* ```
*/
static combineEntries<Key, Value>(entries: Iterable<[Key, Value]>, combine: (firstValue: Value, secondValue: Value, key: Key) => Value): Collection<Key, Value>;
}
/**
* @internal
*/
type Keep<Value> = {
keep: false;
} | {
keep: true;
value: Value;
};
/**
* @internal
*/
type Comparator<Key, Value> = (firstValue: Value, secondValue: Value, firstKey: Key, secondKey: Key) => number;
/**
* The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection#readme | @discordjs/collection} version
* that you are currently using.
*/
declare const version: string;
export { Collection, type CollectionConstructor, type Comparator, type Keep, type ReadonlyCollection, version };

View file

@ -0,0 +1,654 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
Collection: () => Collection,
version: () => version
});
module.exports = __toCommonJS(src_exports);
// src/collection.ts
var Collection = class _Collection extends Map {
static {
__name(this, "Collection");
}
/**
* Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
*
* @param key - The key to get if it exists, or set otherwise
* @param defaultValueGenerator - A function that generates the default value
* @example
* ```ts
* collection.ensure(guildId, () => defaultGuildConfig);
* ```
*/
ensure(key, defaultValueGenerator) {
if (this.has(key))
return this.get(key);
if (typeof defaultValueGenerator !== "function")
throw new TypeError(`${defaultValueGenerator} is not a function`);
const defaultValue = defaultValueGenerator(key, this);
this.set(key, defaultValue);
return defaultValue;
}
/**
* Checks if all of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if all of the elements exist, `false` if at least one does not exist.
*/
hasAll(...keys) {
return keys.every((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((key) => super.has(key));
}
first(amount) {
if (amount === void 0)
return this.values().next().value;
if (amount < 0)
return this.last(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.values();
return Array.from({ length: amount }, () => iter.next().value);
}
firstKey(amount) {
if (amount === void 0)
return this.keys().next().value;
if (amount < 0)
return this.lastKey(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.keys();
return Array.from({ length: amount }, () => iter.next().value);
}
last(amount) {
const arr = [...this.values()];
if (amount === void 0)
return arr[arr.length - 1];
if (amount < 0)
return this.first(amount * -1);
if (!amount)
return [];
return arr.slice(-amount);
}
lastKey(amount) {
const arr = [...this.keys()];
if (amount === void 0)
return arr[arr.length - 1];
if (amount < 0)
return this.firstKey(amount * -1);
if (!amount)
return [];
return arr.slice(-amount);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the item at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the element to obtain
*/
at(index) {
index = Math.floor(index);
const arr = [...this.values()];
return arr.at(index);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the key at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the key to obtain
*/
keyAt(index) {
index = Math.floor(index);
const arr = [...this.keys()];
return arr.at(index);
}
random(amount) {
const arr = [...this.values()];
if (amount === void 0)
return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount)
return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
() => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]
);
}
randomKey(amount) {
const arr = [...this.keys()];
if (amount === void 0)
return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount)
return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
() => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]
);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}
* but returns a Collection instead of an Array.
*/
reverse() {
const entries = [...this.entries()].reverse();
this.clear();
for (const [key, value] of entries)
this.set(key, value);
return this;
}
find(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return val;
}
return void 0;
}
findKey(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return key;
}
return void 0;
}
findLast(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const entries = [...this.entries()];
for (let index = entries.length - 1; index >= 0; index--) {
const val = entries[index][1];
const key = entries[index][0];
if (fn(val, key, this))
return val;
}
return void 0;
}
findLastKey(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const entries = [...this.entries()];
for (let index = entries.length - 1; index >= 0; index--) {
const key = entries[index][0];
const val = entries[index][1];
if (fn(val, key, this))
return key;
}
return void 0;
}
sweep(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const previousSize = this.size;
for (const [key, val] of this) {
if (fn(val, key, this))
this.delete(key);
}
return previousSize - this.size;
}
filter(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const results = new this.constructor[Symbol.species]();
for (const [key, val] of this) {
if (fn(val, key, this))
results.set(key, val);
}
return results;
}
partition(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const results = [
new this.constructor[Symbol.species](),
new this.constructor[Symbol.species]()
];
for (const [key, val] of this) {
if (fn(val, key, this)) {
results[0].set(key, val);
} else {
results[1].set(key, val);
}
}
return results;
}
flatMap(fn, thisArg) {
const collections = this.map(fn, thisArg);
return new this.constructor[Symbol.species]().concat(...collections);
}
map(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const iter = this.entries();
return Array.from({ length: this.size }, () => {
const [key, value] = iter.next().value;
return fn(value, key, this);
});
}
mapValues(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const coll = new this.constructor[Symbol.species]();
for (const [key, val] of this)
coll.set(key, fn(val, key, this));
return coll;
}
some(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return true;
}
return false;
}
every(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (!fn(val, key, this))
return false;
}
return true;
}
/**
* Applies a function to produce a single value. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,
* and `collection`
* @param initialValue - Starting value for the accumulator
* @example
* ```ts
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
reduce(fn, initialValue) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
let accumulator;
const iterator = this.entries();
if (initialValue === void 0) {
if (this.size === 0)
throw new TypeError("Reduce of empty collection with no initial value");
accumulator = iterator.next().value[1];
} else {
accumulator = initialValue;
}
for (const [key, value] of iterator) {
accumulator = fn(accumulator, value, key, this);
}
return accumulator;
}
/**
* 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/reduceRight | Array.reduceRight()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `value`, `key`, and `collection`
* @param initialValue - Starting value for the accumulator
*/
reduceRight(fn, initialValue) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
const entries = [...this.entries()];
let accumulator;
let index;
if (initialValue === void 0) {
if (entries.length === 0)
throw new TypeError("Reduce of empty collection with no initial value");
accumulator = entries[entries.length - 1][1];
index = entries.length - 1;
} else {
accumulator = initialValue;
index = entries.length;
}
while (--index >= 0) {
const key = entries[index][0];
const val = entries[index][1];
accumulator = fn(accumulator, val, key, this);
}
return accumulator;
}
each(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, 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 (thisArg !== void 0)
fn = fn.bind(thisArg);
fn(this);
return this;
}
/**
* Creates an identical shallow copy of this collection.
*
* @example
* ```ts
* const newColl = someColl.clone();
* ```
*/
clone() {
return new this.constructor[Symbol.species](this);
}
/**
* Combines this collection with others into a new collection. None of the source collections are modified.
*
* @param collections - Collections to merge
* @example
* ```ts
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ```
*/
concat(...collections) {
const newColl = this.clone();
for (const coll of collections) {
for (const [key, val] of coll)
newColl.set(key, val);
}
return newColl;
}
/**
* Checks if this collection shares identical items with another.
* This is different to checking for equality using equal-signs, because
* the collections may be different objects, but contain the same data.
*
* @param collection - Collection to compare with
* @returns Whether the collections have identical contents
*/
equals(collection) {
if (!collection)
return false;
if (this === collection)
return true;
if (this.size !== collection.size)
return false;
for (const [key, value] of this) {
if (!collection.has(key) || value !== collection.get(key)) {
return false;
}
}
return true;
}
/**
* The sort method sorts the items of a collection in place and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.
* @example
* ```ts
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sort(compareFunction = _Collection.defaultSort) {
const entries = [...this.entries()];
entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0]));
super.clear();
for (const [key, value] of entries) {
super.set(key, value);
}
return this;
}
/**
* The intersection method returns a new collection containing the items where the key is present in both collections.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* const intersection = col1.intersection(col2);
* console.log(col1.intersection(col2));
* // => Collection { 'a' => 1 }
* ```
*/
intersection(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of this) {
if (other.has(key))
coll.set(key, value);
}
return coll;
}
/**
* Returns a new collection containing the items where the key is present in either of the collections.
*
* @remarks
*
* If the collections have any items with the same key, the value from the first collection will be used.
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['b', 3], ['c', 3]]);
* const union = col1.union(col2);
* console.log(union);
* // => Collection { 'a' => 1, 'b' => 2, 'c' => 3 }
* ```
*/
union(other) {
const coll = new this.constructor[Symbol.species](this);
for (const [key, value] of other) {
if (!coll.has(key))
coll.set(key, value);
}
return coll;
}
/**
* Returns a new collection containing the items where the key is present in this collection but not the other.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* console.log(col1.difference(col2));
* // => Collection { 'b' => 2 }
* console.log(col2.difference(col1));
* // => Collection { 'c' => 3 }
* ```
*/
difference(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of this) {
if (!other.has(key))
coll.set(key, value);
}
return coll;
}
/**
* Returns a new collection containing only the items where the keys are present in either collection, but not both.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* const symmetricDifference = col1.symmetricDifference(col2);
* console.log(col1.symmetricDifference(col2));
* // => Collection { 'b' => 2, 'c' => 3 }
* ```
*/
symmetricDifference(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of this) {
if (!other.has(key))
coll.set(key, value);
}
for (const [key, value] of other) {
if (!this.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 key of keys) {
const hasInSelf = this.has(key);
const hasInOther = other.has(key);
if (hasInSelf && hasInOther) {
const result = whenInBoth(this.get(key), other.get(key), key);
if (result.keep)
coll.set(key, result.value);
} else if (hasInSelf) {
const result = whenInSelf(this.get(key), key);
if (result.keep)
coll.set(key, result.value);
} else if (hasInOther) {
const result = whenInOther(other.get(key), key);
if (result.keep)
coll.set(key, result.value);
}
}
return coll;
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed | Array.toReversed()}
* but returns a Collection instead of an Array.
*/
toReversed() {
return new this.constructor[Symbol.species](this).reverse();
}
/**
* 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);
* ```
*/
toSorted(compareFunction = _Collection.defaultSort) {
return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));
}
toJSON() {
return [...this.entries()];
}
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 [key, value] of entries) {
if (coll.has(key)) {
coll.set(key, combine(coll.get(key), value, key));
} else {
coll.set(key, value);
}
}
return coll;
}
};
// src/index.ts
var version = "2.1.0";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Collection,
version
});
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,628 @@
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/collection.ts
var Collection = class _Collection extends Map {
static {
__name(this, "Collection");
}
/**
* Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
*
* @param key - The key to get if it exists, or set otherwise
* @param defaultValueGenerator - A function that generates the default value
* @example
* ```ts
* collection.ensure(guildId, () => defaultGuildConfig);
* ```
*/
ensure(key, defaultValueGenerator) {
if (this.has(key))
return this.get(key);
if (typeof defaultValueGenerator !== "function")
throw new TypeError(`${defaultValueGenerator} is not a function`);
const defaultValue = defaultValueGenerator(key, this);
this.set(key, defaultValue);
return defaultValue;
}
/**
* Checks if all of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if all of the elements exist, `false` if at least one does not exist.
*/
hasAll(...keys) {
return keys.every((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((key) => super.has(key));
}
first(amount) {
if (amount === void 0)
return this.values().next().value;
if (amount < 0)
return this.last(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.values();
return Array.from({ length: amount }, () => iter.next().value);
}
firstKey(amount) {
if (amount === void 0)
return this.keys().next().value;
if (amount < 0)
return this.lastKey(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.keys();
return Array.from({ length: amount }, () => iter.next().value);
}
last(amount) {
const arr = [...this.values()];
if (amount === void 0)
return arr[arr.length - 1];
if (amount < 0)
return this.first(amount * -1);
if (!amount)
return [];
return arr.slice(-amount);
}
lastKey(amount) {
const arr = [...this.keys()];
if (amount === void 0)
return arr[arr.length - 1];
if (amount < 0)
return this.firstKey(amount * -1);
if (!amount)
return [];
return arr.slice(-amount);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the item at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the element to obtain
*/
at(index) {
index = Math.floor(index);
const arr = [...this.values()];
return arr.at(index);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the key at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the key to obtain
*/
keyAt(index) {
index = Math.floor(index);
const arr = [...this.keys()];
return arr.at(index);
}
random(amount) {
const arr = [...this.values()];
if (amount === void 0)
return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount)
return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
() => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]
);
}
randomKey(amount) {
const arr = [...this.keys()];
if (amount === void 0)
return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount)
return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
() => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]
);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}
* but returns a Collection instead of an Array.
*/
reverse() {
const entries = [...this.entries()].reverse();
this.clear();
for (const [key, value] of entries)
this.set(key, value);
return this;
}
find(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return val;
}
return void 0;
}
findKey(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return key;
}
return void 0;
}
findLast(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const entries = [...this.entries()];
for (let index = entries.length - 1; index >= 0; index--) {
const val = entries[index][1];
const key = entries[index][0];
if (fn(val, key, this))
return val;
}
return void 0;
}
findLastKey(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const entries = [...this.entries()];
for (let index = entries.length - 1; index >= 0; index--) {
const key = entries[index][0];
const val = entries[index][1];
if (fn(val, key, this))
return key;
}
return void 0;
}
sweep(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const previousSize = this.size;
for (const [key, val] of this) {
if (fn(val, key, this))
this.delete(key);
}
return previousSize - this.size;
}
filter(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const results = new this.constructor[Symbol.species]();
for (const [key, val] of this) {
if (fn(val, key, this))
results.set(key, val);
}
return results;
}
partition(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const results = [
new this.constructor[Symbol.species](),
new this.constructor[Symbol.species]()
];
for (const [key, val] of this) {
if (fn(val, key, this)) {
results[0].set(key, val);
} else {
results[1].set(key, val);
}
}
return results;
}
flatMap(fn, thisArg) {
const collections = this.map(fn, thisArg);
return new this.constructor[Symbol.species]().concat(...collections);
}
map(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const iter = this.entries();
return Array.from({ length: this.size }, () => {
const [key, value] = iter.next().value;
return fn(value, key, this);
});
}
mapValues(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const coll = new this.constructor[Symbol.species]();
for (const [key, val] of this)
coll.set(key, fn(val, key, this));
return coll;
}
some(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return true;
}
return false;
}
every(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (!fn(val, key, this))
return false;
}
return true;
}
/**
* Applies a function to produce a single value. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,
* and `collection`
* @param initialValue - Starting value for the accumulator
* @example
* ```ts
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
reduce(fn, initialValue) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
let accumulator;
const iterator = this.entries();
if (initialValue === void 0) {
if (this.size === 0)
throw new TypeError("Reduce of empty collection with no initial value");
accumulator = iterator.next().value[1];
} else {
accumulator = initialValue;
}
for (const [key, value] of iterator) {
accumulator = fn(accumulator, value, key, this);
}
return accumulator;
}
/**
* 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/reduceRight | Array.reduceRight()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `value`, `key`, and `collection`
* @param initialValue - Starting value for the accumulator
*/
reduceRight(fn, initialValue) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
const entries = [...this.entries()];
let accumulator;
let index;
if (initialValue === void 0) {
if (entries.length === 0)
throw new TypeError("Reduce of empty collection with no initial value");
accumulator = entries[entries.length - 1][1];
index = entries.length - 1;
} else {
accumulator = initialValue;
index = entries.length;
}
while (--index >= 0) {
const key = entries[index][0];
const val = entries[index][1];
accumulator = fn(accumulator, val, key, this);
}
return accumulator;
}
each(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, 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 (thisArg !== void 0)
fn = fn.bind(thisArg);
fn(this);
return this;
}
/**
* Creates an identical shallow copy of this collection.
*
* @example
* ```ts
* const newColl = someColl.clone();
* ```
*/
clone() {
return new this.constructor[Symbol.species](this);
}
/**
* Combines this collection with others into a new collection. None of the source collections are modified.
*
* @param collections - Collections to merge
* @example
* ```ts
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ```
*/
concat(...collections) {
const newColl = this.clone();
for (const coll of collections) {
for (const [key, val] of coll)
newColl.set(key, val);
}
return newColl;
}
/**
* Checks if this collection shares identical items with another.
* This is different to checking for equality using equal-signs, because
* the collections may be different objects, but contain the same data.
*
* @param collection - Collection to compare with
* @returns Whether the collections have identical contents
*/
equals(collection) {
if (!collection)
return false;
if (this === collection)
return true;
if (this.size !== collection.size)
return false;
for (const [key, value] of this) {
if (!collection.has(key) || value !== collection.get(key)) {
return false;
}
}
return true;
}
/**
* The sort method sorts the items of a collection in place and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.
* @example
* ```ts
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sort(compareFunction = _Collection.defaultSort) {
const entries = [...this.entries()];
entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0]));
super.clear();
for (const [key, value] of entries) {
super.set(key, value);
}
return this;
}
/**
* The intersection method returns a new collection containing the items where the key is present in both collections.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* const intersection = col1.intersection(col2);
* console.log(col1.intersection(col2));
* // => Collection { 'a' => 1 }
* ```
*/
intersection(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of this) {
if (other.has(key))
coll.set(key, value);
}
return coll;
}
/**
* Returns a new collection containing the items where the key is present in either of the collections.
*
* @remarks
*
* If the collections have any items with the same key, the value from the first collection will be used.
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['b', 3], ['c', 3]]);
* const union = col1.union(col2);
* console.log(union);
* // => Collection { 'a' => 1, 'b' => 2, 'c' => 3 }
* ```
*/
union(other) {
const coll = new this.constructor[Symbol.species](this);
for (const [key, value] of other) {
if (!coll.has(key))
coll.set(key, value);
}
return coll;
}
/**
* Returns a new collection containing the items where the key is present in this collection but not the other.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* console.log(col1.difference(col2));
* // => Collection { 'b' => 2 }
* console.log(col2.difference(col1));
* // => Collection { 'c' => 3 }
* ```
*/
difference(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of this) {
if (!other.has(key))
coll.set(key, value);
}
return coll;
}
/**
* Returns a new collection containing only the items where the keys are present in either collection, but not both.
*
* @param other - The other Collection to filter against
* @example
* ```ts
* const col1 = new Collection([['a', 1], ['b', 2]]);
* const col2 = new Collection([['a', 1], ['c', 3]]);
* const symmetricDifference = col1.symmetricDifference(col2);
* console.log(col1.symmetricDifference(col2));
* // => Collection { 'b' => 2, 'c' => 3 }
* ```
*/
symmetricDifference(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of this) {
if (!other.has(key))
coll.set(key, value);
}
for (const [key, value] of other) {
if (!this.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 key of keys) {
const hasInSelf = this.has(key);
const hasInOther = other.has(key);
if (hasInSelf && hasInOther) {
const result = whenInBoth(this.get(key), other.get(key), key);
if (result.keep)
coll.set(key, result.value);
} else if (hasInSelf) {
const result = whenInSelf(this.get(key), key);
if (result.keep)
coll.set(key, result.value);
} else if (hasInOther) {
const result = whenInOther(other.get(key), key);
if (result.keep)
coll.set(key, result.value);
}
}
return coll;
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed | Array.toReversed()}
* but returns a Collection instead of an Array.
*/
toReversed() {
return new this.constructor[Symbol.species](this).reverse();
}
/**
* 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);
* ```
*/
toSorted(compareFunction = _Collection.defaultSort) {
return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));
}
toJSON() {
return [...this.entries()];
}
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 [key, value] of entries) {
if (coll.has(key)) {
coll.set(key, combine(coll.get(key), value, key));
} else {
coll.set(key, value);
}
}
return coll;
}
};
// src/index.ts
var version = "2.1.0";
export {
Collection,
version
};
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,86 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@discordjs/collection",
"version": "2.1.0",
"description": "Utility data structure used in discord.js",
"exports": {
".": {
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
}
}
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"directories": {
"lib": "src",
"test": "__tests__"
},
"files": [
"dist"
],
"contributors": [
"Crawl <icrawltogo@gmail.com>",
"Amish Shah <amishshah.2k@gmail.com>",
"SpaceEEC <spaceeec@yahoo.com>",
"Vlad Frangu <kingdgrizzle@gmail.com>",
"Aura Román <kyradiscord@gmail.com>"
],
"license": "Apache-2.0",
"keywords": [
"map",
"collection",
"utility"
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/collection"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"funding": "https://github.com/discordjs/discord.js?sponsor",
"devDependencies": {
"@favware/cliff-jumper": "^3.0.2",
"@types/node": "18.18.8",
"@vitest/coverage-v8": "^1.5.0",
"cross-env": "^7.0.3",
"esbuild-plugin-version-injector": "^1.2.1",
"eslint": "^8.57.0",
"eslint-config-neon": "^0.1.62",
"eslint-formatter-pretty": "^6.0.1",
"prettier": "^3.2.5",
"tsup": "^8.0.2",
"turbo": "^1.13.2",
"typescript": "^5.4.5",
"vitest": "^1.5.0",
"@discordjs/api-extractor": "^7.38.1",
"@discordjs/scripts": "^0.1.0"
},
"engines": {
"node": ">=18"
},
"publishConfig": {
"access": "public",
"provenance": true
},
"scripts": {
"test": "vitest run",
"build": "tsc --noEmit && tsup",
"build:docs": "tsc -p tsconfig.docs.json",
"lint": "prettier --check . && cross-env TIMING=1 eslint --format=pretty src __tests__",
"format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty src __tests__",
"fmt": "pnpm run format",
"docs": "pnpm run build:docs && api-extractor run --local --minify && generate-split-documentation",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/collection/*'",
"release": "cliff-jumper"
}
}

113
node_modules/@discordjs/ws/package.json generated vendored Normal file
View file

@ -0,0 +1,113 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@discordjs/ws",
"version": "1.1.0",
"description": "Wrapper around Discord's gateway",
"exports": {
".": {
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
}
},
"./defaultWorker": {
"require": {
"types": null,
"default": "./dist/defaultWorker.js"
},
"import": {
"types": null,
"default": "./dist/defaultWorker.mjs"
}
}
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"directories": {
"lib": "src",
"test": "__tests__"
},
"files": [
"dist"
],
"contributors": [
"Crawl <icrawltogo@gmail.com>",
"Amish Shah <amishshah.2k@gmail.com>",
"SpaceEEC <spaceeec@yahoo.com>",
"Vlad Frangu <kingdgrizzle@gmail.com>",
"Aura Román <kyradiscord@gmail.com>",
"DD <didinele.dev@gmail.com>"
],
"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",
"funding": "https://github.com/discordjs/discord.js?sponsor",
"dependencies": {
"@sapphire/async-queue": "^1.5.2",
"@types/ws": "^8.5.10",
"@vladfrangu/async_event_emitter": "^2.2.4",
"discord-api-types": "0.37.83",
"tslib": "^2.6.2",
"ws": "^8.16.0",
"@discordjs/rest": "^2.3.0",
"@discordjs/collection": "^2.1.0",
"@discordjs/util": "^1.1.0"
},
"devDependencies": {
"@favware/cliff-jumper": "^3.0.2",
"@types/node": "18.17.9",
"@vitest/coverage-v8": "^1.5.0",
"cross-env": "^7.0.3",
"esbuild-plugin-version-injector": "^1.2.1",
"eslint": "^8.57.0",
"eslint-config-neon": "^0.1.62",
"eslint-formatter-pretty": "^6.0.1",
"mock-socket": "^9.3.1",
"prettier": "^3.2.5",
"tsd": "^0.30.7",
"tsup": "^8.0.2",
"turbo": "^1.13.2",
"typescript": "^5.4.5",
"undici": "6.13.0",
"vitest": "^1.5.0",
"zlib-sync": "^0.1.9",
"@discordjs/api-extractor": "^7.38.1",
"@discordjs/scripts": "^0.1.0"
},
"engines": {
"node": ">=16.11.0"
},
"publishConfig": {
"access": "public",
"provenance": true
},
"scripts": {
"test": "vitest run",
"build": "tsc --noEmit && tsup",
"build:docs": "tsc -p tsconfig.docs.json",
"lint": "prettier --check . && cross-env TIMING=1 eslint --format=pretty src __tests__",
"format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty src __tests__",
"docs": "pnpm run build:docs && api-extractor run --local --minify && generate-split-documentation",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/ws/*'",
"release": "cliff-jumper"
}
}