chore: use descriptive type parameter names (#9937)

* chore: use descriptive type parameter names

* refactor: requested changes

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Almeida
2023-11-12 17:21:51 +00:00
committed by GitHub
parent 4ff3ea4a1b
commit 975d5f18ae
34 changed files with 1104 additions and 895 deletions

View File

@@ -6,7 +6,7 @@ import { usePathname } from 'next/navigation';
import type { PropsWithChildren } from 'react'; import type { PropsWithChildren } from 'react';
import { useCurrentPathMeta } from '~/hooks/useCurrentPathMeta'; import { useCurrentPathMeta } from '~/hooks/useCurrentPathMeta';
export interface ItemLinkProps<T extends string> extends Omit<LinkProps<T>, 'href'> { export interface ItemLinkProps<Route extends string> extends Omit<LinkProps<Route>, 'href'> {
readonly className?: string; readonly className?: string;
/** /**
* The URI of the api item to link to. (e.g. `/RestManager`) * The URI of the api item to link to. (e.g. `/RestManager`)
@@ -29,7 +29,7 @@ export interface ItemLinkProps<T extends string> extends Omit<LinkProps<T>, 'hre
* This component only needs the relative path to the item, and will automatically * This component only needs the relative path to the item, and will automatically
* generate the full path to the item client-side. * generate the full path to the item client-side.
*/ */
export function ItemLink<T extends string>(props: PropsWithChildren<ItemLinkProps<T>>) { export function ItemLink<Route extends string>(props: PropsWithChildren<ItemLinkProps<Route>>) {
const pathname = usePathname(); const pathname = usePathname();
const { packageName, version } = useCurrentPathMeta(); const { packageName, version } = useCurrentPathMeta();

View File

@@ -6,9 +6,9 @@ import type { ApiItem, ApiItemContainerMixin } from '@discordjs/api-extractor-mo
* @param parent - The parent to resolve the inherited members of. * @param parent - The parent to resolve the inherited members of.
* @param predicate - A predicate to filter the members by. * @param predicate - A predicate to filter the members by.
*/ */
export function resolveMembers<T extends ApiItem>( export function resolveMembers<WantedItem extends ApiItem>(
parent: ApiItemContainerMixin, parent: ApiItemContainerMixin,
predicate: (item: ApiItem) => item is T, predicate: (item: ApiItem) => item is WantedItem,
) { ) {
const seenItems = new Set<string>(); const seenItems = new Set<string>();
const inheritedMembers = parent.findMembersWithInheritance().items.reduce((acc, item) => { const inheritedMembers = parent.findMembersWithInheritance().items.reduce((acc, item) => {
@@ -25,14 +25,17 @@ export function resolveMembers<T extends ApiItem>(
} }
return acc; return acc;
}, new Array<{ inherited?: ApiItemContainerMixin | undefined; item: T }>()); }, new Array<{ inherited?: ApiItemContainerMixin | undefined; item: WantedItem }>());
const mergedMembers = parent const mergedMembers = parent
.getMergedSiblings() .getMergedSiblings()
.filter((sibling) => sibling.containerKey !== parent.containerKey) .filter((sibling) => sibling.containerKey !== parent.containerKey)
.flatMap((sibling) => (sibling as ApiItemContainerMixin).findMembersWithInheritance().items) .flatMap((sibling) => (sibling as ApiItemContainerMixin).findMembersWithInheritance().items)
.filter((item) => predicate(item) && !seenItems.has(item.containerKey)) .filter((item) => predicate(item) && !seenItems.has(item.containerKey))
.map((item) => ({ item: item as T, inherited: item.parent ? (item.parent as ApiItemContainerMixin) : undefined })); .map((item) => ({
item: item as WantedItem,
inherited: item.parent ? (item.parent as ApiItemContainerMixin) : undefined,
}));
return [...inheritedMembers, ...mergedMembers]; return [...inheritedMembers, ...mergedMembers];
} }

View File

@@ -25,6 +25,17 @@ const typeScriptRuleset = merge(...typescript, {
}, },
rules: { rules: {
'@typescript-eslint/consistent-type-definitions': [2, 'interface'], '@typescript-eslint/consistent-type-definitions': [2, 'interface'],
'@typescript-eslint/naming-convention': [
2,
{
selector: 'typeParameter',
format: ['PascalCase'],
custom: {
regex: '^\\w{3,}',
match: true,
},
},
],
}, },
settings: { settings: {
'import/resolver': { 'import/resolver': {
@@ -110,6 +121,10 @@ export default [
'@typescript-eslint/no-this-alias': 0, '@typescript-eslint/no-this-alias': 0,
}, },
}, },
{
files: [`packages/{api-extractor,api-extractor-model,api-extractor-utils}/**/*${commonFiles}`],
rules: { '@typescript-eslint/naming-convention': 0 },
},
reactRuleset, reactRuleset,
nextRuleset, nextRuleset,
edgeRuleset, edgeRuleset,

View File

@@ -75,7 +75,7 @@ export interface IPubSubBroker<TEvents extends Record<string, any>>
/** /**
* Publishes an event * Publishes an event
*/ */
publish<T extends keyof TEvents>(event: T, data: TEvents[T]): Promise<void>; publish<Event extends keyof TEvents>(event: Event, data: TEvents[Event]): Promise<void>;
} }
export interface IRPCBroker<TEvents extends Record<string, any>, TResponses extends Record<keyof TEvents, any>> export interface IRPCBroker<TEvents extends Record<string, any>, TResponses extends Record<keyof TEvents, any>>
@@ -84,5 +84,9 @@ export interface IRPCBroker<TEvents extends Record<string, any>, TResponses exte
/** /**
* Makes an RPC call * Makes an RPC call
*/ */
call<T extends keyof TEvents>(event: T, data: TEvents[T], timeoutDuration?: number): Promise<TResponses[T]>; call<Event extends keyof TEvents>(
event: Event,
data: TEvents[Event],
timeoutDuration?: number,
): Promise<TResponses[Event]>;
} }

View File

@@ -36,7 +36,7 @@ export class PubSubRedisBroker<TEvents extends Record<string, any>>
/** /**
* {@inheritDoc IPubSubBroker.publish} * {@inheritDoc IPubSubBroker.publish}
*/ */
public async publish<T extends keyof TEvents>(event: T, data: TEvents[T]): Promise<void> { public async publish<Event extends keyof TEvents>(event: Event, data: TEvents[Event]): Promise<void> {
await this.options.redisClient.xadd( await this.options.redisClient.xadd(
event as string, event as string,
'*', '*',

View File

@@ -83,11 +83,11 @@ export class RPCRedisBroker<TEvents extends Record<string, any>, TResponses exte
/** /**
* {@inheritDoc IRPCBroker.call} * {@inheritDoc IRPCBroker.call}
*/ */
public async call<T extends keyof TEvents>( public async call<Event extends keyof TEvents>(
event: T, event: Event,
data: TEvents[T], data: TEvents[Event],
timeoutDuration: number = this.options.timeout, timeoutDuration: number = this.options.timeout,
): Promise<TResponses[T]> { ): Promise<TResponses[Event]> {
const id = await this.options.redisClient.xadd( const id = await this.options.redisClient.xadd(
event as string, event as string,
'*', '*',
@@ -103,7 +103,7 @@ export class RPCRedisBroker<TEvents extends Record<string, any>, TResponses exte
const timedOut = new Error(`timed out after ${timeoutDuration}ms`); const timedOut = new Error(`timed out after ${timeoutDuration}ms`);
await this.streamReadClient.subscribe(rpcChannel); await this.streamReadClient.subscribe(rpcChannel);
return new Promise<TResponses[T]>((resolve, reject) => { return new Promise<TResponses[Event]>((resolve, reject) => {
const timeout = setTimeout(() => reject(timedOut), timeoutDuration).unref(); const timeout = setTimeout(() => reject(timedOut), timeoutDuration).unref();
this.promises.set(id!, { resolve, reject, timeout }); this.promises.set(id!, { resolve, reject, timeout });

View File

@@ -54,15 +54,15 @@ export type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalAction
/** /**
* A builder that creates API-compatible JSON data for action rows. * A builder that creates API-compatible JSON data for action rows.
* *
* @typeParam T - The types of components this action row holds * @typeParam ComponentType - The types of components this action row holds
*/ */
export class ActionRowBuilder<T extends AnyComponentBuilder> extends ComponentBuilder< export class ActionRowBuilder<ComponentType extends AnyComponentBuilder> extends ComponentBuilder<
APIActionRowComponent<APIMessageActionRowComponent | APIModalActionRowComponent> APIActionRowComponent<APIMessageActionRowComponent | APIModalActionRowComponent>
> { > {
/** /**
* The components within this action row. * The components within this action row.
*/ */
public readonly components: T[]; public readonly components: ComponentType[];
/** /**
* Creates a new action row from API data. * Creates a new action row from API data.
@@ -100,7 +100,7 @@ export class ActionRowBuilder<T extends AnyComponentBuilder> extends ComponentBu
*/ */
public constructor({ components, ...data }: Partial<APIActionRowComponent<APIActionRowComponentTypes>> = {}) { public constructor({ components, ...data }: Partial<APIActionRowComponent<APIActionRowComponentTypes>> = {}) {
super({ type: ComponentType.ActionRow, ...data }); super({ type: ComponentType.ActionRow, ...data });
this.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as T[]; this.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as ComponentType[];
} }
/** /**
@@ -108,7 +108,7 @@ export class ActionRowBuilder<T extends AnyComponentBuilder> extends ComponentBu
* *
* @param components - The components to add * @param components - The components to add
*/ */
public addComponents(...components: RestOrArray<T>) { public addComponents(...components: RestOrArray<ComponentType>) {
this.components.push(...normalizeArray(components)); this.components.push(...normalizeArray(components));
return this; return this;
} }
@@ -118,7 +118,7 @@ export class ActionRowBuilder<T extends AnyComponentBuilder> extends ComponentBu
* *
* @param components - The components to set * @param components - The components to set
*/ */
public setComponents(...components: RestOrArray<T>) { public setComponents(...components: RestOrArray<ComponentType>) {
this.components.splice(0, this.components.length, ...normalizeArray(components)); this.components.splice(0, this.components.length, ...normalizeArray(components));
return this; return this;
} }
@@ -126,10 +126,10 @@ export class ActionRowBuilder<T extends AnyComponentBuilder> extends ComponentBu
/** /**
* {@inheritDoc ComponentBuilder.toJSON} * {@inheritDoc ComponentBuilder.toJSON}
*/ */
public toJSON(): APIActionRowComponent<ReturnType<T['toJSON']>> { public toJSON(): APIActionRowComponent<ReturnType<ComponentType['toJSON']>> {
return { return {
...this.data, ...this.data,
components: this.components.map((component) => component.toJSON()), components: this.components.map((component) => component.toJSON()),
} as APIActionRowComponent<ReturnType<T['toJSON']>>; } as APIActionRowComponent<ReturnType<ComponentType['toJSON']>>;
} }
} }

View File

@@ -55,21 +55,23 @@ export interface MappedComponentTypes {
/** /**
* Factory for creating components from API data. * Factory for creating components from API data.
* *
* @typeParam T - The type of component to use * @typeParam ComponentType - The type of component to use
* @param data - The API data to transform to a component class * @param data - The API data to transform to a component class
*/ */
export function createComponentBuilder<T extends keyof MappedComponentTypes>( export function createComponentBuilder<ComponentType extends keyof MappedComponentTypes>(
// eslint-disable-next-line @typescript-eslint/sort-type-constituents // eslint-disable-next-line @typescript-eslint/sort-type-constituents
data: (APIModalComponent | APIMessageComponent) & { type: T }, data: (APIModalComponent | APIMessageComponent) & { type: ComponentType },
): MappedComponentTypes[T]; ): MappedComponentTypes[ComponentType];
/** /**
* Factory for creating components from API data. * Factory for creating components from API data.
* *
* @typeParam C - The type of component to use * @typeParam ComponentBuilder - The type of component to use
* @param data - The API data to transform to a component class * @param data - The API data to transform to a component class
*/ */
export function createComponentBuilder<C extends MessageComponentBuilder | ModalComponentBuilder>(data: C): C; export function createComponentBuilder<ComponentBuilder extends MessageComponentBuilder | ModalComponentBuilder>(
data: ComponentBuilder,
): ComponentBuilder;
export function createComponentBuilder( export function createComponentBuilder(
data: APIMessageComponent | APIModalComponent | MessageComponentBuilder, data: APIMessageComponent | APIModalComponent | MessageComponentBuilder,

View File

@@ -66,8 +66,8 @@ export function validateChoicesLength(amountAdding: number, choices?: APIApplica
} }
export function assertReturnOfBuilder< export function assertReturnOfBuilder<
T extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder, ReturnType extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,
>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T { >(input: unknown, ExpectedInstanceOf: new () => ReturnType): asserts input is ReturnType {
s.instance(ExpectedInstanceOf).parse(input); s.instance(ExpectedInstanceOf).parse(input);
} }

View File

@@ -14,11 +14,11 @@ const booleanPredicate = s.boolean;
/** /**
* This mixin holds choices and autocomplete symbols used for options. * This mixin holds choices and autocomplete symbols used for options.
*/ */
export class ApplicationCommandOptionWithChoicesAndAutocompleteMixin<T extends number | string> { export class ApplicationCommandOptionWithChoicesAndAutocompleteMixin<ChoiceType extends number | string> {
/** /**
* The choices of this option. * The choices of this option.
*/ */
public readonly choices?: APIApplicationCommandOptionChoice<T>[]; public readonly choices?: APIApplicationCommandOptionChoice<ChoiceType>[];
/** /**
* Whether this option utilizes autocomplete. * Whether this option utilizes autocomplete.
@@ -37,7 +37,7 @@ export class ApplicationCommandOptionWithChoicesAndAutocompleteMixin<T extends n
* *
* @param choices - The choices to add * @param choices - The choices to add
*/ */
public addChoices(...choices: APIApplicationCommandOptionChoice<T>[]): this { public addChoices(...choices: APIApplicationCommandOptionChoice<ChoiceType>[]): this {
if (choices.length > 0 && this.autocomplete) { if (choices.length > 0 && this.autocomplete) {
throw new RangeError('Autocomplete and choices are mutually exclusive to each other.'); throw new RangeError('Autocomplete and choices are mutually exclusive to each other.');
} }
@@ -69,7 +69,7 @@ export class ApplicationCommandOptionWithChoicesAndAutocompleteMixin<T extends n
* *
* @param choices - The choices to set * @param choices - The choices to set
*/ */
public setChoices<Input extends APIApplicationCommandOptionChoice<T>[]>(...choices: Input): this { public setChoices<Input extends APIApplicationCommandOptionChoice<ChoiceType>[]>(...choices: Input): this {
if (choices.length > 0 && this.autocomplete) { if (choices.length > 0 && this.autocomplete) {
throw new RangeError('Autocomplete and choices are mutually exclusive to each other.'); throw new RangeError('Autocomplete and choices are mutually exclusive to each other.');
} }

View File

@@ -148,13 +148,15 @@ export class SharedSlashCommandOptions<ShouldOmitSubcommandFunctions = true> {
* @param Instance - The instance of whatever is being added * @param Instance - The instance of whatever is being added
* @internal * @internal
*/ */
private _sharedAddOptionMethod<T extends ApplicationCommandOptionBase>( private _sharedAddOptionMethod<OptionBuilder extends ApplicationCommandOptionBase>(
input: input:
| Omit<T, 'addChoices'> | Omit<OptionBuilder, 'addChoices'>
| Omit<T, 'setAutocomplete'> | Omit<OptionBuilder, 'setAutocomplete'>
| T | OptionBuilder
| ((builder: T) => Omit<T, 'addChoices'> | Omit<T, 'setAutocomplete'> | T), | ((
Instance: new () => T, builder: OptionBuilder,
) => Omit<OptionBuilder, 'addChoices'> | Omit<OptionBuilder, 'setAutocomplete'> | OptionBuilder),
Instance: new () => OptionBuilder,
): ShouldOmitSubcommandFunctions extends true ? Omit<this, 'addSubcommand' | 'addSubcommandGroup'> : this { ): ShouldOmitSubcommandFunctions extends true ? Omit<this, 'addSubcommand' | 'addSubcommandGroup'> : this {
const { options } = this; const { options } = this;

View File

@@ -1,12 +1,12 @@
/** /**
* Normalizes data that is a rest parameter or an array into an array with a depth of 1. * Normalizes data that is a rest parameter or an array into an array with a depth of 1.
* *
* @typeParam T - The data that must satisfy {@link RestOrArray}. * @typeParam ItemType - The data that must satisfy {@link RestOrArray}.
* @param arr - The (possibly variadic) data to normalize * @param arr - The (possibly variadic) data to normalize
*/ */
export function normalizeArray<T>(arr: RestOrArray<T>): T[] { export function normalizeArray<ItemType>(arr: RestOrArray<ItemType>): ItemType[] {
if (Array.isArray(arr[0])) return arr[0]; if (Array.isArray(arr[0])) return arr[0];
return arr as T[]; return arr as ItemType[];
} }
/** /**
@@ -16,4 +16,4 @@ export function normalizeArray<T>(arr: RestOrArray<T>): T[] {
* This type is used throughout builders to ensure both an array and variadic arguments * This type is used throughout builders to ensure both an array and variadic arguments
* may be used. It is normalized with {@link normalizeArray}. * may be used. It is normalized with {@link normalizeArray}.
*/ */
export type RestOrArray<T> = T[] | [T[]]; export type RestOrArray<Type> = Type[] | [Type[]];

View File

@@ -3,13 +3,13 @@
import { describe, test, expect } from 'vitest'; import { describe, test, expect } from 'vitest';
import { Collection } from '../src/index.js'; import { Collection } from '../src/index.js';
type TestCollection<V> = Collection<string, V>; type TestCollection<Value> = Collection<string, Value>;
function createCollection<V = number>(): TestCollection<V> { function createCollection<Value = number>(): TestCollection<Value> {
return new Collection(); return new Collection();
} }
function createCollectionFrom<V = number>(...entries: [key: string, value: V][]): TestCollection<V> { function createCollectionFrom<Value = number>(...entries: [key: string, value: Value][]): TestCollection<Value> {
return new Collection(entries); return new Collection(entries);
} }

View File

@@ -4,8 +4,8 @@
*/ */
export interface CollectionConstructor { export interface CollectionConstructor {
new (): Collection<unknown, unknown>; new (): Collection<unknown, unknown>;
new <K, V>(entries?: readonly (readonly [K, V])[] | null): Collection<K, V>; new <Key, Value>(entries?: readonly (readonly [Key, Value])[] | null): Collection<Key, Value>;
new <K, V>(iterable: Iterable<readonly [K, V]>): Collection<K, V>; new <Key, Value>(iterable: Iterable<readonly [Key, Value]>): Collection<Key, Value>;
readonly prototype: Collection<unknown, unknown>; readonly prototype: Collection<unknown, unknown>;
readonly [Symbol.species]: CollectionConstructor; readonly [Symbol.species]: CollectionConstructor;
} }
@@ -13,18 +13,18 @@ export interface CollectionConstructor {
/** /**
* Represents an immutable version of a collection * Represents an immutable version of a collection
*/ */
export type ReadonlyCollection<K, V> = Omit< export type ReadonlyCollection<Key, Value> = Omit<
Collection<K, V>, Collection<Key, Value>,
'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep' 'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'
> & > &
ReadonlyMap<K, V>; ReadonlyMap<Key, Value>;
/** /**
* Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself
* *
* @internal * @internal
*/ */
export interface Collection<K, V> extends Map<K, V> { export interface Collection<Key, Value> extends Map<Key, Value> {
constructor: CollectionConstructor; constructor: CollectionConstructor;
} }
@@ -32,10 +32,10 @@ export interface Collection<K, V> extends Map<K, V> {
* A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has * 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. * an ID, for significantly improved performance and ease-of-use.
* *
* @typeParam K - The key type this collection holds * @typeParam Key - The key type this collection holds
* @typeParam V - The value type this collection holds * @typeParam Value - The value type this collection holds
*/ */
export class Collection<K, V> extends Map<K, V> { export 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. * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
* *
@@ -46,7 +46,7 @@ export class Collection<K, V> extends Map<K, V> {
* collection.ensure(guildId, () => defaultGuildConfig); * collection.ensure(guildId, () => defaultGuildConfig);
* ``` * ```
*/ */
public ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V { public ensure(key: Key, defaultValueGenerator: (key: Key, collection: this) => Value): Value {
if (this.has(key)) return this.get(key)!; if (this.has(key)) return this.get(key)!;
if (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`); if (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);
const defaultValue = defaultValueGenerator(key, this); const defaultValue = defaultValueGenerator(key, this);
@@ -60,7 +60,7 @@ export class Collection<K, V> extends Map<K, V> {
* @param keys - The keys of the elements to check for * @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. * @returns `true` if all of the elements exist, `false` if at least one does not exist.
*/ */
public hasAll(...keys: K[]) { public hasAll(...keys: Key[]) {
return keys.every((key) => super.has(key)); return keys.every((key) => super.has(key));
} }
@@ -70,7 +70,7 @@ export class Collection<K, V> extends Map<K, V> {
* @param keys - The keys of the elements to check for * @param keys - The keys of the elements to check for
* @returns `true` if any of the elements exist, `false` if none exist. * @returns `true` if any of the elements exist, `false` if none exist.
*/ */
public hasAny(...keys: K[]) { public hasAny(...keys: Key[]) {
return keys.some((key) => super.has(key)); return keys.some((key) => super.has(key));
} }
@@ -80,14 +80,14 @@ export class Collection<K, V> extends Map<K, V> {
* @param amount - Amount of values to obtain from the beginning * @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 * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative
*/ */
public first(): V | undefined; public first(): Value | undefined;
public first(amount: number): V[]; public first(amount: number): Value[];
public first(amount?: number): V | V[] | undefined { public first(amount?: number): Value | Value[] | undefined {
if (amount === undefined) return this.values().next().value; if (amount === undefined) return this.values().next().value;
if (amount < 0) return this.last(amount * -1); if (amount < 0) return this.last(amount * -1);
amount = Math.min(this.size, amount); amount = Math.min(this.size, amount);
const iter = this.values(); const iter = this.values();
return Array.from({ length: amount }, (): V => iter.next().value); return Array.from({ length: amount }, (): Value => iter.next().value);
} }
/** /**
@@ -97,14 +97,14 @@ export class Collection<K, V> extends Map<K, V> {
* @returns A single key if no amount is provided or an array of keys, starting from the end if * @returns A single key if no amount is provided or an array of keys, starting from the end if
* amount is negative * amount is negative
*/ */
public firstKey(): K | undefined; public firstKey(): Key | undefined;
public firstKey(amount: number): K[]; public firstKey(amount: number): Key[];
public firstKey(amount?: number): K | K[] | undefined { public firstKey(amount?: number): Key | Key[] | undefined {
if (amount === undefined) return this.keys().next().value; if (amount === undefined) return this.keys().next().value;
if (amount < 0) return this.lastKey(amount * -1); if (amount < 0) return this.lastKey(amount * -1);
amount = Math.min(this.size, amount); amount = Math.min(this.size, amount);
const iter = this.keys(); const iter = this.keys();
return Array.from({ length: amount }, (): K => iter.next().value); return Array.from({ length: amount }, (): Key => iter.next().value);
} }
/** /**
@@ -114,9 +114,9 @@ export class Collection<K, V> extends Map<K, V> {
* @returns A single value if no amount is provided or an array of values, starting from the start if * @returns A single value if no amount is provided or an array of values, starting from the start if
* amount is negative * amount is negative
*/ */
public last(): V | undefined; public last(): Value | undefined;
public last(amount: number): V[]; public last(amount: number): Value[];
public last(amount?: number): V | V[] | undefined { public last(amount?: number): Value | Value[] | undefined {
const arr = [...this.values()]; const arr = [...this.values()];
if (amount === undefined) return arr[arr.length - 1]; if (amount === undefined) return arr[arr.length - 1];
if (amount < 0) return this.first(amount * -1); if (amount < 0) return this.first(amount * -1);
@@ -131,9 +131,9 @@ export class Collection<K, V> extends Map<K, V> {
* @returns A single key if no amount is provided or an array of keys, starting from the start if * @returns A single key if no amount is provided or an array of keys, starting from the start if
* amount is negative * amount is negative
*/ */
public lastKey(): K | undefined; public lastKey(): Key | undefined;
public lastKey(amount: number): K[]; public lastKey(amount: number): Key[];
public lastKey(amount?: number): K | K[] | undefined { public lastKey(amount?: number): Key | Key[] | undefined {
const arr = [...this.keys()]; const arr = [...this.keys()];
if (amount === undefined) return arr[arr.length - 1]; if (amount === undefined) return arr[arr.length - 1];
if (amount < 0) return this.firstKey(amount * -1); if (amount < 0) return this.firstKey(amount * -1);
@@ -173,15 +173,15 @@ export class Collection<K, V> extends Map<K, V> {
* @param amount - Amount of values to obtain randomly * @param amount - Amount of values to obtain randomly
* @returns A single value if no amount is provided or an array of values * @returns A single value if no amount is provided or an array of values
*/ */
public random(): V | undefined; public random(): Value | undefined;
public random(amount: number): V[]; public random(amount: number): Value[];
public random(amount?: number): V | V[] | undefined { public random(amount?: number): Value | Value[] | undefined {
const arr = [...this.values()]; const arr = [...this.values()];
if (amount === undefined) return arr[Math.floor(Math.random() * arr.length)]; if (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount) return []; if (!arr.length || !amount) return [];
return Array.from( return Array.from(
{ length: Math.min(amount, arr.length) }, { length: Math.min(amount, arr.length) },
(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!, (): Value => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,
); );
} }
@@ -191,15 +191,15 @@ export class Collection<K, V> extends Map<K, V> {
* @param amount - Amount of keys to obtain randomly * @param amount - Amount of keys to obtain randomly
* @returns A single key if no amount is provided or an array * @returns A single key if no amount is provided or an array
*/ */
public randomKey(): K | undefined; public randomKey(): Key | undefined;
public randomKey(amount: number): K[]; public randomKey(amount: number): Key[];
public randomKey(amount?: number): K | K[] | undefined { public randomKey(amount?: number): Key | Key[] | undefined {
const arr = [...this.keys()]; const arr = [...this.keys()];
if (amount === undefined) return arr[Math.floor(Math.random() * arr.length)]; if (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount) return []; if (!arr.length || !amount) return [];
return Array.from( return Array.from(
{ length: Math.min(amount, arr.length) }, { length: Math.min(amount, arr.length) },
(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!, (): Key => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,
); );
} }
@@ -228,14 +228,19 @@ export class Collection<K, V> extends Map<K, V> {
* collection.find(user => user.username === 'Bob'); * collection.find(user => user.username === 'Bob');
* ``` * ```
*/ */
public find<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined; public find<NewValue extends Value>(
public find(fn: (value: V, key: K, collection: this) => unknown): V | undefined; fn: (value: Value, key: Key, collection: this) => value is NewValue,
public find<This, V2 extends V>( ): NewValue | undefined;
fn: (this: This, value: V, key: K, collection: this) => value is V2, public find(fn: (value: Value, key: Key, collection: this) => unknown): Value | undefined;
public find<This, NewValue extends Value>(
fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue,
thisArg: This, thisArg: This,
): V2 | undefined; ): NewValue | undefined;
public find<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined; public find<This>(
public find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined { fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This,
): Value | undefined;
public find(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Value | undefined {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) { for (const [key, val] of this) {
@@ -257,14 +262,19 @@ export class Collection<K, V> extends Map<K, V> {
* collection.findKey(user => user.username === 'Bob'); * collection.findKey(user => user.username === 'Bob');
* ``` * ```
*/ */
public findKey<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined; public findKey<NewKey extends Key>(
public findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined; fn: (value: Value, key: Key, collection: this) => key is NewKey,
public findKey<This, K2 extends K>( ): NewKey | undefined;
fn: (this: This, value: V, key: K, collection: this) => key is K2, public findKey(fn: (value: Value, key: Key, collection: this) => unknown): Key | undefined;
public findKey<This, NewKey extends Key>(
fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey,
thisArg: This, thisArg: This,
): K2 | undefined; ): NewKey | undefined;
public findKey<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined; public findKey<This>(
public findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined { fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This,
): Key | undefined;
public findKey(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Key | undefined {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) { for (const [key, val] of this) {
@@ -281,14 +291,19 @@ export class Collection<K, V> extends Map<K, V> {
* @param fn - The function to test with (should return a boolean) * @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function * @param thisArg - Value to use as `this` when executing the function
*/ */
public findLast<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined; public findLast<NewValue extends Value>(
public findLast(fn: (value: V, key: K, collection: this) => unknown): V | undefined; fn: (value: Value, key: Key, collection: this) => value is NewValue,
public findLast<This, V2 extends V>( ): NewValue | undefined;
fn: (this: This, value: V, key: K, collection: this) => value is V2, public findLast(fn: (value: Value, key: Key, collection: this) => unknown): Value | undefined;
public findLast<This, NewValue extends Value>(
fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue,
thisArg: This, thisArg: This,
): V2 | undefined; ): NewValue | undefined;
public findLast<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined; public findLast<This>(
public findLast(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined { fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This,
): Value | undefined;
public findLast(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Value | undefined {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
const entries = [...this.entries()]; const entries = [...this.entries()];
@@ -309,17 +324,19 @@ export class Collection<K, V> extends Map<K, V> {
* @param fn - The function to test with (should return a boolean) * @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as `this` when executing the function * @param thisArg - Value to use as `this` when executing the function
*/ */
public findLastKey<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined; public findLastKey<NewKey extends Key>(
public findLastKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined; fn: (value: Value, key: Key, collection: this) => key is NewKey,
public findLastKey<This, K2 extends K>( ): NewKey | undefined;
fn: (this: This, value: V, key: K, collection: this) => key is K2, public findLastKey(fn: (value: Value, key: Key, collection: this) => unknown): Key | undefined;
public findLastKey<This, NewKey extends Key>(
fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey,
thisArg: This, thisArg: This,
): K2 | undefined; ): NewKey | undefined;
public findLastKey<This>( public findLastKey<This>(
fn: (this: This, value: V, key: K, collection: this) => unknown, fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This, thisArg: This,
): K | undefined; ): Key | undefined;
public findLastKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined { public findLastKey(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Key | undefined {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
const entries = [...this.entries()]; const entries = [...this.entries()];
@@ -339,9 +356,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing the function * @param thisArg - Value to use as `this` when executing the function
* @returns The number of removed entries * @returns The number of removed entries
*/ */
public sweep(fn: (value: V, key: K, collection: this) => unknown): number; public sweep(fn: (value: Value, key: Key, collection: this) => unknown): number;
public sweep<T>(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number; public sweep<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): number;
public sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number { public sweep(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): number {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
const previousSize = this.size; const previousSize = this.size;
@@ -364,22 +381,29 @@ export class Collection<K, V> extends Map<K, V> {
* collection.filter(user => user.username === 'Bob'); * collection.filter(user => user.username === 'Bob');
* ``` * ```
*/ */
public filter<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): Collection<K2, V>; public filter<NewKey extends Key>(
public filter<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): Collection<K, V2>; fn: (value: Value, key: Key, collection: this) => key is NewKey,
public filter(fn: (value: V, key: K, collection: this) => unknown): Collection<K, V>; ): Collection<NewKey, Value>;
public filter<This, K2 extends K>( public filter<NewValue extends Value>(
fn: (this: This, value: V, key: K, collection: this) => key is K2, fn: (value: Value, key: Key, collection: this) => value is NewValue,
): Collection<Key, NewValue>;
public filter(fn: (value: Value, key: Key, collection: this) => unknown): Collection<Key, Value>;
public filter<This, NewKey extends Key>(
fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey,
thisArg: This, thisArg: This,
): Collection<K2, V>; ): Collection<NewKey, Value>;
public filter<This, V2 extends V>( public filter<This, NewValue extends Value>(
fn: (this: This, value: V, key: K, collection: this) => value is V2, fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue,
thisArg: This, thisArg: This,
): Collection<K, V2>; ): Collection<Key, NewValue>;
public filter<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection<K, V>; public filter<This>(
public filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection<K, V> { fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This,
): Collection<Key, Value>;
public filter(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Collection<Key, Value> {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
const results = new this.constructor[Symbol.species]<K, V>(); const results = new this.constructor[Symbol.species]<Key, Value>();
for (const [key, val] of this) { for (const [key, val] of this) {
if (fn(val, key, this)) results.set(key, val); if (fn(val, key, this)) results.set(key, val);
} }
@@ -398,34 +422,36 @@ export class Collection<K, V> extends Map<K, V> {
* const [big, small] = collection.partition(guild => guild.memberCount > 250); * const [big, small] = collection.partition(guild => guild.memberCount > 250);
* ``` * ```
*/ */
public partition<K2 extends K>( public partition<NewKey extends Key>(
fn: (value: V, key: K, collection: this) => key is K2, fn: (value: Value, key: Key, collection: this) => key is NewKey,
): [Collection<K2, V>, Collection<Exclude<K, K2>, V>]; ): [Collection<NewKey, Value>, Collection<Exclude<Key, NewKey>, Value>];
public partition<V2 extends V>( public partition<NewValue extends Value>(
fn: (value: V, key: K, collection: this) => value is V2, fn: (value: Value, key: Key, collection: this) => value is NewValue,
): [Collection<K, V2>, Collection<K, Exclude<V, V2>>]; ): [Collection<Key, NewValue>, Collection<Key, Exclude<Value, NewValue>>];
public partition(fn: (value: V, key: K, collection: this) => unknown): [Collection<K, V>, Collection<K, V>];
public partition<This, K2 extends K>(
fn: (this: This, value: V, key: K, collection: this) => key is K2,
thisArg: This,
): [Collection<K2, V>, Collection<Exclude<K, K2>, V>];
public partition<This, V2 extends V>(
fn: (this: This, value: V, key: K, collection: this) => value is V2,
thisArg: This,
): [Collection<K, V2>, Collection<K, Exclude<V, V2>>];
public partition<This>(
fn: (this: This, value: V, key: K, collection: this) => unknown,
thisArg: This,
): [Collection<K, V>, Collection<K, V>];
public partition( public partition(
fn: (value: V, key: K, collection: this) => unknown, fn: (value: Value, key: Key, collection: this) => unknown,
): [Collection<Key, Value>, Collection<Key, Value>];
public 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>];
public 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>>];
public partition<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This,
): [Collection<Key, Value>, Collection<Key, Value>];
public partition(
fn: (value: Value, key: Key, collection: this) => unknown,
thisArg?: unknown, thisArg?: unknown,
): [Collection<K, V>, Collection<K, V>] { ): [Collection<Key, Value>, Collection<Key, Value>] {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
const results: [Collection<K, V>, Collection<K, V>] = [ const results: [Collection<Key, Value>, Collection<Key, Value>] = [
new this.constructor[Symbol.species]<K, V>(), new this.constructor[Symbol.species]<Key, Value>(),
new this.constructor[Symbol.species]<K, V>(), new this.constructor[Symbol.species]<Key, Value>(),
]; ];
for (const [key, val] of this) { for (const [key, val] of this) {
if (fn(val, key, this)) { if (fn(val, key, this)) {
@@ -449,15 +475,20 @@ export class Collection<K, V> extends Map<K, V> {
* collection.flatMap(guild => guild.members.cache); * collection.flatMap(guild => guild.members.cache);
* ``` * ```
*/ */
public flatMap<T>(fn: (value: V, key: K, collection: this) => Collection<K, T>): Collection<K, T>; public flatMap<NewValue>(
public flatMap<T, This>( fn: (value: Value, key: Key, collection: this) => Collection<Key, NewValue>,
fn: (this: This, value: V, key: K, collection: this) => Collection<K, T>, ): Collection<Key, NewValue>;
public flatMap<NewValue, This>(
fn: (this: This, value: Value, key: Key, collection: this) => Collection<Key, NewValue>,
thisArg: This, thisArg: This,
): Collection<K, T>; ): Collection<Key, NewValue>;
public flatMap<T>(fn: (value: V, key: K, collection: this) => Collection<K, T>, thisArg?: unknown): Collection<K, T> { public flatMap<NewValue>(
fn: (value: Value, key: Key, collection: this) => Collection<Key, NewValue>,
thisArg?: unknown,
): Collection<Key, NewValue> {
// eslint-disable-next-line unicorn/no-array-method-this-argument // eslint-disable-next-line unicorn/no-array-method-this-argument
const collections = this.map(fn, thisArg); const collections = this.map(fn, thisArg);
return new this.constructor[Symbol.species]<K, T>().concat(...collections); return new this.constructor[Symbol.species]<Key, NewValue>().concat(...collections);
} }
/** /**
@@ -471,13 +502,16 @@ export class Collection<K, V> extends Map<K, V> {
* collection.map(user => user.tag); * collection.map(user => user.tag);
* ``` * ```
*/ */
public map<T>(fn: (value: V, key: K, collection: this) => T): T[]; public map<NewValue>(fn: (value: Value, key: Key, collection: this) => NewValue): NewValue[];
public map<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[]; public map<This, NewValue>(
public map<T>(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] { fn: (this: This, value: Value, key: Key, collection: this) => NewValue,
thisArg: This,
): NewValue[];
public map<NewValue>(fn: (value: Value, key: Key, collection: this) => NewValue, thisArg?: unknown): NewValue[] {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
const iter = this.entries(); const iter = this.entries();
return Array.from({ length: this.size }, (): T => { return Array.from({ length: this.size }, (): NewValue => {
const [key, value] = iter.next().value; const [key, value] = iter.next().value;
return fn(value, key, this); return fn(value, key, this);
}); });
@@ -494,12 +528,18 @@ export class Collection<K, V> extends Map<K, V> {
* collection.mapValues(user => user.tag); * collection.mapValues(user => user.tag);
* ``` * ```
*/ */
public mapValues<T>(fn: (value: V, key: K, collection: this) => T): Collection<K, T>; public mapValues<NewValue>(fn: (value: Value, key: Key, collection: this) => NewValue): Collection<Key, NewValue>;
public mapValues<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection<K, T>; public mapValues<This, NewValue>(
public mapValues<T>(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection<K, T> { fn: (this: This, value: Value, key: Key, collection: this) => NewValue,
thisArg: This,
): Collection<Key, NewValue>;
public mapValues<NewValue>(
fn: (value: Value, key: Key, collection: this) => NewValue,
thisArg?: unknown,
): Collection<Key, NewValue> {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
const coll = new this.constructor[Symbol.species]<K, T>(); const coll = new this.constructor[Symbol.species]<Key, NewValue>();
for (const [key, val] of this) coll.set(key, fn(val, key, this)); for (const [key, val] of this) coll.set(key, fn(val, key, this));
return coll; return coll;
} }
@@ -515,9 +555,9 @@ export class Collection<K, V> extends Map<K, V> {
* collection.some(user => user.discriminator === '0000'); * collection.some(user => user.discriminator === '0000');
* ``` * ```
*/ */
public some(fn: (value: V, key: K, collection: this) => unknown): boolean; public some(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
public some<T>(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean; public some<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean;
public some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean { public some(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): boolean {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) { for (const [key, val] of this) {
@@ -538,19 +578,23 @@ export class Collection<K, V> extends Map<K, V> {
* collection.every(user => !user.bot); * collection.every(user => !user.bot);
* ``` * ```
*/ */
public every<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): this is Collection<K2, V>; public every<NewKey extends Key>(
public every<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): this is Collection<K, V2>; fn: (value: Value, key: Key, collection: this) => key is NewKey,
public every(fn: (value: V, key: K, collection: this) => unknown): boolean; ): this is Collection<NewKey, Value>;
public every<This, K2 extends K>( public every<NewValue extends Value>(
fn: (this: This, value: V, key: K, collection: this) => key is K2, fn: (value: Value, key: Key, collection: this) => value is NewValue,
): this is Collection<Key, NewValue>;
public every(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
public every<This, NewKey extends Key>(
fn: (this: This, value: Value, key: Key, collection: this) => key is NewKey,
thisArg: This, thisArg: This,
): this is Collection<K2, V>; ): this is Collection<NewKey, Value>;
public every<This, V2 extends V>( public every<This, NewValue extends Value>(
fn: (this: This, value: V, key: K, collection: this) => value is V2, fn: (this: This, value: Value, key: Key, collection: this) => value is NewValue,
thisArg: This, thisArg: This,
): this is Collection<K, V2>; ): this is Collection<Key, NewValue>;
public every<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean; public every<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean;
public every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean { public every(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): boolean {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) { for (const [key, val] of this) {
@@ -572,9 +616,12 @@ export class Collection<K, V> extends Map<K, V> {
* collection.reduce((acc, guild) => acc + guild.memberCount, 0); * collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ``` * ```
*/ */
public reduce<T = V>(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T { public reduce<InitialValue = Value>(
fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue,
initialValue?: InitialValue,
): InitialValue {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
let accumulator!: T; let accumulator!: InitialValue;
const iterator = this.entries(); const iterator = this.entries();
if (initialValue === undefined) { if (initialValue === undefined) {
@@ -598,15 +645,18 @@ export class Collection<K, V> extends Map<K, V> {
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `value`, `key`, and `collection` * @param fn - Function used to reduce, taking four arguments; `accumulator`, `value`, `key`, and `collection`
* @param initialValue - Starting value for the accumulator * @param initialValue - Starting value for the accumulator
*/ */
public reduceRight<T>(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T { public reduceRight<InitialValue>(
fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue,
initialValue?: InitialValue,
): InitialValue {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
const entries = [...this.entries()]; const entries = [...this.entries()];
let accumulator!: T; let accumulator!: InitialValue;
let index: number; let index: number;
if (initialValue === undefined) { if (initialValue === undefined) {
if (entries.length === 0) throw new TypeError('Reduce of empty collection with no initial value'); if (entries.length === 0) throw new TypeError('Reduce of empty collection with no initial value');
accumulator = entries[entries.length - 1]![1] as unknown as T; accumulator = entries[entries.length - 1]![1] as unknown as InitialValue;
index = entries.length - 1; index = entries.length - 1;
} else { } else {
accumulator = initialValue; accumulator = initialValue;
@@ -637,9 +687,9 @@ export class Collection<K, V> extends Map<K, V> {
* .each(user => console.log(user.username)); * .each(user => console.log(user.username));
* ``` * ```
*/ */
public each(fn: (value: V, key: K, collection: this) => void): this; public each(fn: (value: Value, key: Key, collection: this) => void): this;
public each<T>(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this; public each<This>(fn: (this: This, value: Value, key: Key, collection: this) => void, thisArg: This): this;
public each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this { public each(fn: (value: Value, key: Key, collection: this) => void, thisArg?: unknown): this {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
@@ -664,7 +714,7 @@ export class Collection<K, V> extends Map<K, V> {
* ``` * ```
*/ */
public tap(fn: (collection: this) => void): this; public tap(fn: (collection: this) => void): this;
public tap<T>(fn: (this: T, collection: this) => void, thisArg: T): this; public tap<This>(fn: (this: This, collection: this) => void, thisArg: This): this;
public tap(fn: (collection: this) => void, thisArg?: unknown): this { public tap(fn: (collection: this) => void, thisArg?: unknown): this {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg); if (thisArg !== undefined) fn = fn.bind(thisArg);
@@ -680,7 +730,7 @@ export class Collection<K, V> extends Map<K, V> {
* const newColl = someColl.clone(); * const newColl = someColl.clone();
* ``` * ```
*/ */
public clone(): Collection<K, V> { public clone(): Collection<Key, Value> {
return new this.constructor[Symbol.species](this); return new this.constructor[Symbol.species](this);
} }
@@ -693,7 +743,7 @@ export class Collection<K, V> extends Map<K, V> {
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ``` * ```
*/ */
public concat(...collections: ReadonlyCollection<K, V>[]) { public concat(...collections: ReadonlyCollection<Key, Value>[]) {
const newColl = this.clone(); const newColl = this.clone();
for (const coll of collections) { for (const coll of collections) {
for (const [key, val] of coll) newColl.set(key, val); for (const [key, val] of coll) newColl.set(key, val);
@@ -710,7 +760,7 @@ export class Collection<K, V> extends Map<K, V> {
* @param collection - Collection to compare with * @param collection - Collection to compare with
* @returns Whether the collections have identical contents * @returns Whether the collections have identical contents
*/ */
public equals(collection: ReadonlyCollection<K, V>) { public equals(collection: ReadonlyCollection<Key, Value>) {
if (!collection) return false; // runtime check if (!collection) return false; // runtime check
if (this === collection) return true; if (this === collection) return true;
if (this.size !== collection.size) return false; if (this.size !== collection.size) return false;
@@ -735,7 +785,7 @@ export class Collection<K, V> extends Map<K, V> {
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ``` * ```
*/ */
public sort(compareFunction: Comparator<K, V> = Collection.defaultSort) { public sort(compareFunction: Comparator<Key, Value> = Collection.defaultSort) {
const entries = [...this.entries()]; const entries = [...this.entries()];
entries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0])); entries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));
@@ -763,8 +813,8 @@ export class Collection<K, V> extends Map<K, V> {
* // => Collection { 'a' => 1 } * // => Collection { 'a' => 1 }
* ``` * ```
*/ */
public intersection<T>(other: ReadonlyCollection<K, T>): Collection<K, T | V> { public intersection(other: ReadonlyCollection<Key, any>): Collection<Key, Value> {
const coll = new this.constructor[Symbol.species]<K, T | V>(); const coll = new this.constructor[Symbol.species]<Key, Value>();
for (const [key, value] of this) { for (const [key, value] of this) {
if (other.has(key)) coll.set(key, value); if (other.has(key)) coll.set(key, value);
@@ -789,8 +839,8 @@ export class Collection<K, V> extends Map<K, V> {
* // => Collection { 'a' => 1, 'b' => 2, 'c' => 3 } * // => Collection { 'a' => 1, 'b' => 2, 'c' => 3 }
* ``` * ```
*/ */
public union<T>(other: ReadonlyCollection<K, T>): Collection<K, T | V> { public union<OtherValue>(other: ReadonlyCollection<Key, OtherValue>): Collection<Key, OtherValue | Value> {
const coll = new this.constructor[Symbol.species]<K, T | V>(this); const coll = new this.constructor[Symbol.species]<Key, OtherValue | Value>(this);
for (const [key, value] of other) { for (const [key, value] of other) {
if (!coll.has(key)) coll.set(key, value); if (!coll.has(key)) coll.set(key, value);
@@ -813,8 +863,8 @@ export class Collection<K, V> extends Map<K, V> {
* // => Collection { 'c' => 3 } * // => Collection { 'c' => 3 }
* ``` * ```
*/ */
public difference<T>(other: ReadonlyCollection<K, T>): Collection<K, V> { public difference(other: ReadonlyCollection<Key, any>): Collection<Key, Value> {
const coll = new this.constructor[Symbol.species]<K, V>(); const coll = new this.constructor[Symbol.species]<Key, Value>();
for (const [key, value] of this) { for (const [key, value] of this) {
if (!other.has(key)) coll.set(key, value); if (!other.has(key)) coll.set(key, value);
@@ -836,8 +886,10 @@ export class Collection<K, V> extends Map<K, V> {
* // => Collection { 'b' => 2, 'c' => 3 } * // => Collection { 'b' => 2, 'c' => 3 }
* ``` * ```
*/ */
public symmetricDifference<T>(other: ReadonlyCollection<K, T>): Collection<K, T | V> { public symmetricDifference<OtherValue>(
const coll = new this.constructor[Symbol.species]<K, T | V>(); other: ReadonlyCollection<Key, OtherValue>,
): Collection<Key, OtherValue | Value> {
const coll = new this.constructor[Symbol.species]<Key, OtherValue | Value>();
for (const [key, value] of this) { for (const [key, value] of this) {
if (!other.has(key)) coll.set(key, value); if (!other.has(key)) coll.set(key, value);
@@ -878,13 +930,13 @@ export class Collection<K, V> extends Map<K, V> {
* ); * );
* ``` * ```
*/ */
public merge<T, R>( public merge<OtherValue, ResultValue>(
other: ReadonlyCollection<K, T>, other: ReadonlyCollection<Key, OtherValue>,
whenInSelf: (value: V, key: K) => Keep<R>, whenInSelf: (value: Value, key: Key) => Keep<ResultValue>,
whenInOther: (valueOther: T, key: K) => Keep<R>, whenInOther: (valueOther: OtherValue, key: Key) => Keep<ResultValue>,
whenInBoth: (value: V, valueOther: T, key: K) => Keep<R>, whenInBoth: (value: Value, valueOther: OtherValue, key: Key) => Keep<ResultValue>,
): Collection<K, R> { ): Collection<Key, ResultValue> {
const coll = new this.constructor[Symbol.species]<K, R>(); const coll = new this.constructor[Symbol.species]<Key, ResultValue>();
const keys = new Set([...this.keys(), ...other.keys()]); const keys = new Set([...this.keys(), ...other.keys()]);
for (const key of keys) { for (const key of keys) {
@@ -927,7 +979,7 @@ export class Collection<K, V> extends Map<K, V> {
* collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ``` * ```
*/ */
public toSorted(compareFunction: Comparator<K, V> = Collection.defaultSort) { public toSorted(compareFunction: Comparator<Key, Value> = Collection.defaultSort) {
return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk)); return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));
} }
@@ -936,7 +988,7 @@ export class Collection<K, V> extends Map<K, V> {
return [...this.entries()]; return [...this.entries()];
} }
private static defaultSort<V>(firstValue: V, secondValue: V): number { private static defaultSort<Value>(firstValue: Value, secondValue: Value): number {
return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1; return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;
} }
@@ -951,11 +1003,11 @@ export class Collection<K, V> extends Map<K, V> {
* // returns Collection { "a" => 3, "b" => 2 } * // returns Collection { "a" => 3, "b" => 2 }
* ``` * ```
*/ */
public static combineEntries<K, V>( public static combineEntries<Key, Value>(
entries: Iterable<[K, V]>, entries: Iterable<[Key, Value]>,
combine: (firstValue: V, secondValue: V, key: K) => V, combine: (firstValue: Value, secondValue: Value, key: Key) => Value,
): Collection<K, V> { ): Collection<Key, Value> {
const coll = new Collection<K, V>(); const coll = new Collection<Key, Value>();
for (const [key, value] of entries) { for (const [key, value] of entries) {
if (coll.has(key)) { if (coll.has(key)) {
coll.set(key, combine(coll.get(key)!, value, key)); coll.set(key, combine(coll.get(key)!, value, key));
@@ -971,9 +1023,9 @@ export class Collection<K, V> extends Map<K, V> {
/** /**
* @internal * @internal
*/ */
export type Keep<V> = { keep: false } | { keep: true; value: V }; export type Keep<Value> = { keep: false } | { keep: true; value: Value };
/** /**
* @internal * @internal
*/ */
export type Comparator<K, V> = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number; export type Comparator<Key, Value> = (firstValue: Value, secondValue: Value, firstKey: Key, secondKey: Key) => number;

View File

@@ -85,8 +85,8 @@ export interface IntrinsicProps {
shardId: number; shardId: number;
} }
export interface WithIntrinsicProps<T> extends IntrinsicProps { export interface WithIntrinsicProps<Data> extends IntrinsicProps {
data: T; data: Data;
} }
export interface MappedEvents { export interface MappedEvents {
@@ -332,7 +332,7 @@ export class Client extends AsyncEventEmitter<ManagerShardEventsMap> {
}); });
} }
private wrapIntrinsicProps<T>(obj: T, shardId: number): WithIntrinsicProps<T> { private wrapIntrinsicProps<ObjectType>(obj: ObjectType, shardId: number): WithIntrinsicProps<ObjectType> {
return { return {
api: this.api, api: this.api,
shardId, shardId,

View File

@@ -1 +0,0 @@
typings

View File

@@ -1,200 +1,223 @@
{ {
"$schema": "https://json.schemastore.org/eslintrc.json", "$schema": "https://json.schemastore.org/eslintrc.json",
"root": true, "root": true,
"extends": ["eslint:recommended"], "overrides": [
"plugins": ["import"], {
"parserOptions": { "files": ["src/**/*.js"],
"ecmaVersion": 2022 "extends": ["eslint:recommended"],
}, "plugins": ["import"],
"env": { "parserOptions": {
"es2022": true, "ecmaVersion": 2022
"node": true },
}, "env": {
"rules": { "es2022": true,
"import/order": [ "node": true
"error", },
{ "rules": {
"groups": ["builtin", "external", "internal", "index", "sibling", "parent"], "import/order": [
"alphabetize": { "error",
"order": "asc" {
} "groups": ["builtin", "external", "internal", "index", "sibling", "parent"],
"alphabetize": {
"order": "asc"
}
}
],
"strict": ["error", "global"],
"no-await-in-loop": "warn",
"no-compare-neg-zero": "error",
"no-template-curly-in-string": "error",
"no-unsafe-negation": "error",
"valid-jsdoc": [
"error",
{
"requireReturn": false,
"requireReturnDescription": false,
"prefer": {
"return": "returns",
"arg": "param"
},
"preferType": {
"String": "string",
"Number": "number",
"Boolean": "boolean",
"Symbol": "symbol",
"object": "Object",
"function": "Function",
"array": "Array",
"date": "Date",
"error": "Error",
"null": "void"
}
}
],
"accessor-pairs": "warn",
"array-callback-return": "error",
"consistent-return": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"dot-notation": "error",
"eqeqeq": "error",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-implied-eval": "error",
"no-invalid-this": "error",
"no-lone-blocks": "error",
"no-multi-spaces": "error",
"no-new-func": "error",
"no-new-wrappers": "error",
"no-new": "error",
"no-octal-escape": "error",
"no-return-assign": "error",
"no-return-await": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-throw-literal": "error",
"no-unmodified-loop-condition": "error",
"no-unused-expressions": "error",
"no-useless-call": "error",
"no-useless-concat": "error",
"no-useless-escape": "error",
"no-useless-return": "error",
"no-void": "error",
"no-warning-comments": "warn",
"prefer-promise-reject-errors": "error",
"require-await": "warn",
"wrap-iife": "error",
"yoda": "error",
"no-label-var": "error",
"no-shadow": "error",
"no-undef-init": "error",
"callback-return": "error",
"getter-return": "off",
"handle-callback-err": "error",
"no-mixed-requires": "error",
"no-new-require": "error",
"no-path-concat": "error",
"array-bracket-spacing": "error",
"block-spacing": "error",
"brace-style": ["error", "1tbs", { "allowSingleLine": true }],
"capitalized-comments": ["error", "always", { "ignoreConsecutiveComments": true }],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
"computed-property-spacing": "error",
"consistent-this": ["error", "$this"],
"eol-last": "error",
"func-names": "error",
"func-name-matching": "error",
"func-style": ["error", "declaration", { "allowArrowFunctions": true }],
"key-spacing": "error",
"keyword-spacing": "error",
"max-depth": "error",
"max-len": ["error", 120, 2],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],
"new-cap": "off",
"newline-per-chained-call": ["error", { "ignoreChainWithDepth": 3 }],
"no-array-constructor": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
"no-new-object": "error",
"no-spaced-func": "error",
"no-trailing-spaces": "error",
"no-unneeded-ternary": "error",
"no-whitespace-before-property": "error",
"nonblock-statement-body-position": "error",
"object-curly-spacing": ["error", "always"],
"operator-assignment": "error",
"padded-blocks": ["error", "never"],
"quote-props": ["error", "as-needed"],
"quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
"semi-spacing": "error",
"semi": "error",
"space-before-blocks": "error",
"space-before-function-paren": [
"error",
{
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}
],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"template-tag-spacing": "error",
"unicode-bom": "error",
"arrow-body-style": "error",
"arrow-parens": ["error", "as-needed"],
"arrow-spacing": "error",
"no-duplicate-imports": "error",
"no-useless-computed-key": "error",
"no-useless-constructor": "error",
"prefer-arrow-callback": "error",
"prefer-numeric-literals": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"prefer-object-has-own": "error",
"rest-spread-spacing": "error",
"template-curly-spacing": "error",
"yield-star-spacing": "error",
"no-restricted-globals": [
"error",
{
"name": "Buffer",
"message": "Import Buffer from `node:buffer` instead"
},
{
"name": "process",
"message": "Import process from `node:process` instead"
},
{
"name": "setTimeout",
"message": "Import setTimeout from `node:timers` instead"
},
{
"name": "setInterval",
"message": "Import setInterval from `node:timers` instead"
},
{
"name": "setImmediate",
"message": "Import setImmediate from `node:timers` instead"
},
{
"name": "clearTimeout",
"message": "Import clearTimeout from `node:timers` instead"
},
{
"name": "clearInterval",
"message": "Import clearInterval from `node:timers` instead"
}
]
} }
], },
"strict": ["error", "global"], {
"no-await-in-loop": "warn", "files": ["typings/*.ts"],
"no-compare-neg-zero": "error", "parser": "@typescript-eslint/parser",
"no-template-curly-in-string": "error", "plugins": ["@typescript-eslint"],
"no-unsafe-negation": "error", "rules": {
"valid-jsdoc": [ "@typescript-eslint/naming-convention": [
"error", 2,
{ {
"requireReturn": false, "selector": "typeParameter",
"requireReturnDescription": false, "format": ["PascalCase"],
"prefer": { "custom": {
"return": "returns", "regex": "^\\w{3,}",
"arg": "param" "match": true
}, }
"preferType": { }
"String": "string", ]
"Number": "number",
"Boolean": "boolean",
"Symbol": "symbol",
"object": "Object",
"function": "Function",
"array": "Array",
"date": "Date",
"error": "Error",
"null": "void"
}
} }
], }
]
"accessor-pairs": "warn",
"array-callback-return": "error",
"consistent-return": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"dot-notation": "error",
"eqeqeq": "error",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-implied-eval": "error",
"no-invalid-this": "error",
"no-lone-blocks": "error",
"no-multi-spaces": "error",
"no-new-func": "error",
"no-new-wrappers": "error",
"no-new": "error",
"no-octal-escape": "error",
"no-return-assign": "error",
"no-return-await": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-throw-literal": "error",
"no-unmodified-loop-condition": "error",
"no-unused-expressions": "error",
"no-useless-call": "error",
"no-useless-concat": "error",
"no-useless-escape": "error",
"no-useless-return": "error",
"no-void": "error",
"no-warning-comments": "warn",
"prefer-promise-reject-errors": "error",
"require-await": "warn",
"wrap-iife": "error",
"yoda": "error",
"no-label-var": "error",
"no-shadow": "error",
"no-undef-init": "error",
"callback-return": "error",
"getter-return": "off",
"handle-callback-err": "error",
"no-mixed-requires": "error",
"no-new-require": "error",
"no-path-concat": "error",
"array-bracket-spacing": "error",
"block-spacing": "error",
"brace-style": ["error", "1tbs", { "allowSingleLine": true }],
"capitalized-comments": ["error", "always", { "ignoreConsecutiveComments": true }],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
"computed-property-spacing": "error",
"consistent-this": ["error", "$this"],
"eol-last": "error",
"func-names": "error",
"func-name-matching": "error",
"func-style": ["error", "declaration", { "allowArrowFunctions": true }],
"key-spacing": "error",
"keyword-spacing": "error",
"max-depth": "error",
"max-len": ["error", 120, 2],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],
"new-cap": "off",
"newline-per-chained-call": ["error", { "ignoreChainWithDepth": 3 }],
"no-array-constructor": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
"no-new-object": "error",
"no-spaced-func": "error",
"no-trailing-spaces": "error",
"no-unneeded-ternary": "error",
"no-whitespace-before-property": "error",
"nonblock-statement-body-position": "error",
"object-curly-spacing": ["error", "always"],
"operator-assignment": "error",
"padded-blocks": ["error", "never"],
"quote-props": ["error", "as-needed"],
"quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
"semi-spacing": "error",
"semi": "error",
"space-before-blocks": "error",
"space-before-function-paren": [
"error",
{
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}
],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"template-tag-spacing": "error",
"unicode-bom": "error",
"arrow-body-style": "error",
"arrow-parens": ["error", "as-needed"],
"arrow-spacing": "error",
"no-duplicate-imports": "error",
"no-useless-computed-key": "error",
"no-useless-constructor": "error",
"prefer-arrow-callback": "error",
"prefer-numeric-literals": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"prefer-object-has-own": "error",
"rest-spread-spacing": "error",
"template-curly-spacing": "error",
"yield-star-spacing": "error",
"no-restricted-globals": [
"error",
{
"name": "Buffer",
"message": "Import Buffer from `node:buffer` instead"
},
{
"name": "process",
"message": "Import process from `node:process` instead"
},
{
"name": "setTimeout",
"message": "Import setTimeout from `node:timers` instead"
},
{
"name": "setInterval",
"message": "Import setInterval from `node:timers` instead"
},
{
"name": "setImmediate",
"message": "Import setImmediate from `node:timers` instead"
},
{
"name": "clearTimeout",
"message": "Import clearTimeout from `node:timers` instead"
},
{
"name": "clearInterval",
"message": "Import clearInterval from `node:timers` instead"
}
]
}
} }

View File

@@ -6,7 +6,7 @@
"scripts": { "scripts": {
"test": "pnpm run docs:test && pnpm run test:typescript", "test": "pnpm run docs:test && pnpm run test:typescript",
"test:typescript": "tsc --noEmit && tsd", "test:typescript": "tsc --noEmit && tsd",
"lint": "prettier --check . && tslint typings/index.d.ts && cross-env ESLINT_USE_FLAT_CONFIG=false eslint --format=pretty src", "lint": "prettier --check . && tslint typings/index.d.ts && cross-env ESLINT_USE_FLAT_CONFIG=false eslint --format=pretty src typings",
"format": "prettier --write . && cross-env ESLINT_USE_FLAT_CONFIG=false eslint --fix --format=pretty src", "format": "prettier --write . && cross-env ESLINT_USE_FLAT_CONFIG=false eslint --fix --format=pretty src",
"fmt": "pnpm run format", "fmt": "pnpm run format",
"docs": "docgen -i './src/*.js' './src/**/*.js' -c ./docs/index.json -r ../../ -o ./docs/docs.json && pnpm run docs:new", "docs": "docgen -i './src/*.js' './src/**/*.js' -c ./docs/index.json -r ../../ -o ./docs/docs.json && pnpm run docs:new",
@@ -72,6 +72,8 @@
"@discordjs/docgen": "workspace:^", "@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "2.2.1", "@favware/cliff-jumper": "2.2.1",
"@types/node": "16.18.60", "@types/node": "16.18.60",
"@typescript-eslint/eslint-plugin": "^6.10.0",
"@typescript-eslint/parser": "^6.10.0",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"dtslint": "4.2.1", "dtslint": "4.2.1",
"eslint": "8.53.0", "eslint": "8.53.0",

File diff suppressed because it is too large Load Diff

View File

@@ -190,8 +190,11 @@ import { expectAssignable, expectNotAssignable, expectNotType, expectType } from
import type { ContextMenuCommandBuilder, SlashCommandBuilder } from '@discordjs/builders'; import type { ContextMenuCommandBuilder, SlashCommandBuilder } from '@discordjs/builders';
// Test type transformation: // Test type transformation:
declare const serialize: <T>(value: T) => Serialized<T>; declare const serialize: <Value>(value: Value) => Serialized<Value>;
declare const notPropertyOf: <T, P extends PropertyKey>(value: T, property: P & Exclude<P, keyof T>) => void; declare const notPropertyOf: <Value, Property extends PropertyKey>(
value: Value,
property: Property & Exclude<Property, keyof Value>,
) => void;
const client: Client = new Client({ const client: Client = new Client({
intents: GatewayIntentBits.Guilds, intents: GatewayIntentBits.Guilds,

View File

@@ -1,9 +1,9 @@
import type { DeclarationReflection } from 'typedoc'; import type { DeclarationReflection } from 'typedoc';
import type { Config, Item } from '../interfaces/index.js'; import type { Config, Item } from '../interfaces/index.js';
export class DocumentedItem<T = DeclarationReflection | Item> { export class DocumentedItem<Data = DeclarationReflection | Item> {
public constructor( public constructor(
public readonly data: T, public readonly data: Data,
public readonly config: Config, public readonly config: Config,
) {} ) {}

View File

@@ -4,20 +4,23 @@ import type { Snowflake } from 'discord-api-types/globals';
/** /**
* Wraps the content inside a code block with no language. * Wraps the content inside a code block with no language.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function codeBlock<C extends string>(content: C): `\`\`\`\n${C}\n\`\`\``; export function codeBlock<Content extends string>(content: Content): `\`\`\`\n${Content}\n\`\`\``;
/** /**
* Wraps the content inside a code block with the specified language. * Wraps the content inside a code block with the specified language.
* *
* @typeParam L - This is inferred by the supplied language * @typeParam Language - This is inferred by the supplied language
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param language - The language for the code block * @param language - The language for the code block
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function codeBlock<L extends string, C extends string>(language: L, content: C): `\`\`\`${L}\n${C}\n\`\`\``; export function codeBlock<Language extends string, Content extends string>(
language: Language,
content: Content,
): `\`\`\`${Language}\n${Content}\n\`\`\``;
export function codeBlock(language: string, content?: string): string { export function codeBlock(language: string, content?: string): string {
return content === undefined ? `\`\`\`\n${language}\n\`\`\`` : `\`\`\`${language}\n${content}\n\`\`\``; return content === undefined ? `\`\`\`\n${language}\n\`\`\`` : `\`\`\`${language}\n${content}\n\`\`\``;
@@ -26,50 +29,50 @@ export function codeBlock(language: string, content?: string): string {
/** /**
* Wraps the content inside \`backticks\` which formats it as inline code. * Wraps the content inside \`backticks\` which formats it as inline code.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function inlineCode<C extends string>(content: C): `\`${C}\`` { export function inlineCode<Content extends string>(content: Content): `\`${Content}\`` {
return `\`${content}\``; return `\`${content}\``;
} }
/** /**
* Formats the content into italic text. * Formats the content into italic text.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function italic<C extends string>(content: C): `_${C}_` { export function italic<Content extends string>(content: Content): `_${Content}_` {
return `_${content}_`; return `_${content}_`;
} }
/** /**
* Formats the content into bold text. * Formats the content into bold text.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function bold<C extends string>(content: C): `**${C}**` { export function bold<Content extends string>(content: Content): `**${Content}**` {
return `**${content}**`; return `**${content}**`;
} }
/** /**
* Formats the content into underscored text. * Formats the content into underscored text.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function underscore<C extends string>(content: C): `__${C}__` { export function underscore<Content extends string>(content: Content): `__${Content}__` {
return `__${content}__`; return `__${content}__`;
} }
/** /**
* Formats the content into strike-through text. * Formats the content into strike-through text.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function strikethrough<C extends string>(content: C): `~~${C}~~` { export function strikethrough<Content extends string>(content: Content): `~~${Content}~~` {
return `~~${content}~~`; return `~~${content}~~`;
} }
@@ -77,10 +80,10 @@ export function strikethrough<C extends string>(content: C): `~~${C}~~` {
* Formats the content into a quote. * Formats the content into a quote.
* *
* @remarks This needs to be at the start of the line for Discord to format it. * @remarks This needs to be at the start of the line for Discord to format it.
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function quote<C extends string>(content: C): `> ${C}` { export function quote<Content extends string>(content: Content): `> ${Content}` {
return `> ${content}`; return `> ${content}`;
} }
@@ -88,20 +91,20 @@ export function quote<C extends string>(content: C): `> ${C}` {
* Formats the content into a block quote. * Formats the content into a block quote.
* *
* @remarks This needs to be at the start of the line for Discord to format it. * @remarks This needs to be at the start of the line for Discord to format it.
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function blockQuote<C extends string>(content: C): `>>> ${C}` { export function blockQuote<Content extends string>(content: Content): `>>> ${Content}` {
return `>>> ${content}`; return `>>> ${content}`;
} }
/** /**
* Wraps the URL into `<>` which stops it from embedding. * Wraps the URL into `<>` which stops it from embedding.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param url - The URL to wrap * @param url - The URL to wrap
*/ */
export function hideLinkEmbed<C extends string>(url: C): `<${C}>`; export function hideLinkEmbed<Content extends string>(url: Content): `<${Content}>`;
/** /**
* Wraps the URL into `<>` which stops it from embedding. * Wraps the URL into `<>` which stops it from embedding.
@@ -117,52 +120,55 @@ export function hideLinkEmbed(url: URL | string) {
/** /**
* Formats the content and the URL into a masked URL. * Formats the content and the URL into a masked URL.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to display * @param content - The content to display
* @param url - The URL the content links to * @param url - The URL the content links to
*/ */
export function hyperlink<C extends string>(content: C, url: URL): `[${C}](${string})`; export function hyperlink<Content extends string>(content: Content, url: URL): `[${Content}](${string})`;
/** /**
* Formats the content and the URL into a masked URL. * Formats the content and the URL into a masked URL.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @typeParam U - This is inferred by the supplied URL * @typeParam Url - This is inferred by the supplied URL
* @param content - The content to display * @param content - The content to display
* @param url - The URL the content links to * @param url - The URL the content links to
*/ */
export function hyperlink<C extends string, U extends string>(content: C, url: U): `[${C}](${U})`; export function hyperlink<Content extends string, Url extends string>(
content: Content,
url: Url,
): `[${Content}](${Url})`;
/** /**
* Formats the content and the URL into a masked URL with a custom tooltip. * Formats the content and the URL into a masked URL with a custom tooltip.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @typeParam T - This is inferred by the supplied title * @typeParam Title - This is inferred by the supplied title
* @param content - The content to display * @param content - The content to display
* @param url - The URL the content links to * @param url - The URL the content links to
* @param title - The title shown when hovering on the masked link * @param title - The title shown when hovering on the masked link
*/ */
export function hyperlink<C extends string, T extends string>( export function hyperlink<Content extends string, Title extends string>(
content: C, content: Content,
url: URL, url: URL,
title: T, title: Title,
): `[${C}](${string} "${T}")`; ): `[${Content}](${string} "${Title}")`;
/** /**
* Formats the content and the URL into a masked URL with a custom tooltip. * Formats the content and the URL into a masked URL with a custom tooltip.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @typeParam U - This is inferred by the supplied URL * @typeParam Url - This is inferred by the supplied URL
* @typeParam T - This is inferred by the supplied title * @typeParam Title - This is inferred by the supplied title
* @param content - The content to display * @param content - The content to display
* @param url - The URL the content links to * @param url - The URL the content links to
* @param title - The title shown when hovering on the masked link * @param title - The title shown when hovering on the masked link
*/ */
export function hyperlink<C extends string, U extends string, T extends string>( export function hyperlink<Content extends string, Url extends string, Title extends string>(
content: C, content: Content,
url: U, url: Url,
title: T, title: Title,
): `[${C}](${U} "${T}")`; ): `[${Content}](${Url} "${Title}")`;
export function hyperlink(content: string, url: URL | string, title?: string) { export function hyperlink(content: string, url: URL | string, title?: string) {
return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`; return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`;
@@ -171,102 +177,114 @@ export function hyperlink(content: string, url: URL | string, title?: string) {
/** /**
* Formats the content into a spoiler. * Formats the content into a spoiler.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
*/ */
export function spoiler<C extends string>(content: C): `||${C}||` { export function spoiler<Content extends string>(content: Content): `||${Content}||` {
return `||${content}||`; return `||${content}||`;
} }
/** /**
* Formats a user id into a user mention. * Formats a user id into a user mention.
* *
* @typeParam C - This is inferred by the supplied user id * @typeParam UserId - This is inferred by the supplied user id
* @param userId - The user id to format * @param userId - The user id to format
*/ */
export function userMention<C extends Snowflake>(userId: C): `<@${C}>` { export function userMention<UserId extends Snowflake>(userId: UserId): `<@${UserId}>` {
return `<@${userId}>`; return `<@${userId}>`;
} }
/** /**
* Formats a channel id into a channel mention. * Formats a channel id into a channel mention.
* *
* @typeParam C - This is inferred by the supplied channel id * @typeParam ChannelId - This is inferred by the supplied channel id
* @param channelId - The channel id to format * @param channelId - The channel id to format
*/ */
export function channelMention<C extends Snowflake>(channelId: C): `<#${C}>` { export function channelMention<ChannelId extends Snowflake>(channelId: ChannelId): `<#${ChannelId}>` {
return `<#${channelId}>`; return `<#${channelId}>`;
} }
/** /**
* Formats a role id into a role mention. * Formats a role id into a role mention.
* *
* @typeParam C - This is inferred by the supplied role id * @typeParam RoleId - This is inferred by the supplied role id
* @param roleId - The role id to format * @param roleId - The role id to format
*/ */
export function roleMention<C extends Snowflake>(roleId: C): `<@&${C}>` { export function roleMention<RoleId extends Snowflake>(roleId: RoleId): `<@&${RoleId}>` {
return `<@&${roleId}>`; return `<@&${roleId}>`;
} }
/** /**
* Formats an application command name, subcommand group name, subcommand name, and id into an application command mention. * Formats an application command name, subcommand group name, subcommand name, and id into an application command mention.
* *
* @typeParam N - This is inferred by the supplied command name * @typeParam CommandName - This is inferred by the supplied command name
* @typeParam G - This is inferred by the supplied subcommand group name * @typeParam SubcommandGroupName - This is inferred by the supplied subcommand group name
* @typeParam S - This is inferred by the supplied subcommand name * @typeParam SubcommandName - This is inferred by the supplied subcommand name
* @typeParam I - This is inferred by the supplied command id * @typeParam CommandId - This is inferred by the supplied command id
* @param commandName - The application command name to format * @param commandName - The application command name to format
* @param subcommandGroupName - The subcommand group name to format * @param subcommandGroupName - The subcommand group name to format
* @param subcommandName - The subcommand name to format * @param subcommandName - The subcommand name to format
* @param commandId - The application command id to format * @param commandId - The application command id to format
*/ */
export function chatInputApplicationCommandMention< export function chatInputApplicationCommandMention<
N extends string, CommandName extends string,
G extends string, SubcommandGroupName extends string,
S extends string, SubcommandName extends string,
I extends Snowflake, CommandId extends Snowflake,
>(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): `</${N} ${G} ${S}:${I}>`; >(
commandName: CommandName,
subcommandGroupName: SubcommandGroupName,
subcommandName: SubcommandName,
commandId: CommandId,
): `</${CommandName} ${SubcommandGroupName} ${SubcommandName}:${CommandId}>`;
/** /**
* Formats an application command name, subcommand name, and id into an application command mention. * Formats an application command name, subcommand name, and id into an application command mention.
* *
* @typeParam N - This is inferred by the supplied command name * @typeParam CommandName - This is inferred by the supplied command name
* @typeParam S - This is inferred by the supplied subcommand name * @typeParam SubcommandName - This is inferred by the supplied subcommand name
* @typeParam I - This is inferred by the supplied command id * @typeParam CommandId - This is inferred by the supplied command id
* @param commandName - The application command name to format * @param commandName - The application command name to format
* @param subcommandName - The subcommand name to format * @param subcommandName - The subcommand name to format
* @param commandId - The application command id to format * @param commandId - The application command id to format
*/ */
export function chatInputApplicationCommandMention<N extends string, S extends string, I extends Snowflake>( export function chatInputApplicationCommandMention<
commandName: N, CommandName extends string,
subcommandName: S, SubcommandName extends string,
commandId: I, CommandId extends Snowflake,
): `</${N} ${S}:${I}>`; >(
commandName: CommandName,
subcommandName: SubcommandName,
commandId: CommandId,
): `</${CommandName} ${SubcommandName}:${CommandId}>`;
/** /**
* Formats an application command name and id into an application command mention. * Formats an application command name and id into an application command mention.
* *
* @typeParam N - This is inferred by the supplied command name * @typeParam CommandName - This is inferred by the supplied command name
* @typeParam I - This is inferred by the supplied command id * @typeParam CommandId - This is inferred by the supplied command id
* @param commandName - The application command name to format * @param commandName - The application command name to format
* @param commandId - The application command id to format * @param commandId - The application command id to format
*/ */
export function chatInputApplicationCommandMention<N extends string, I extends Snowflake>( export function chatInputApplicationCommandMention<CommandName extends string, CommandId extends Snowflake>(
commandName: N, commandName: CommandName,
commandId: I, commandId: CommandId,
): `</${N}:${I}>`; ): `</${CommandName}:${CommandId}>`;
export function chatInputApplicationCommandMention< export function chatInputApplicationCommandMention<
N extends string, CommandName extends string,
G extends Snowflake | string, SubcommandGroupName extends Snowflake | string,
S extends Snowflake | string, SubcommandName extends Snowflake | string,
I extends Snowflake, CommandId extends Snowflake,
>( >(
commandName: N, commandName: CommandName,
subcommandGroupName: G, subcommandGroupName: SubcommandGroupName,
subcommandName?: S, subcommandName?: SubcommandName,
commandId?: I, commandId?: CommandId,
): `</${N} ${G} ${S}:${I}>` | `</${N} ${G}:${S}>` | `</${N}:${G}>` { ):
| `</${CommandName} ${SubcommandGroupName} ${SubcommandName}:${CommandId}>`
| `</${CommandName} ${SubcommandGroupName}:${SubcommandName}>`
| `</${CommandName}:${SubcommandGroupName}>` {
if (commandId !== undefined) { if (commandId !== undefined) {
return `</${commandName} ${subcommandGroupName} ${subcommandName!}:${commandId}>`; return `</${commandName} ${subcommandGroupName} ${subcommandName!}:${commandId}>`;
} }
@@ -281,95 +299,105 @@ export function chatInputApplicationCommandMention<
/** /**
* Formats a non-animated emoji id into a fully qualified emoji identifier. * Formats a non-animated emoji id into a fully qualified emoji identifier.
* *
* @typeParam C - This is inferred by the supplied emoji id * @typeParam EmojiId - This is inferred by the supplied emoji id
* @param emojiId - The emoji id to format * @param emojiId - The emoji id to format
*/ */
export function formatEmoji<C extends Snowflake>(emojiId: C, animated?: false): `<:_:${C}>`; export function formatEmoji<EmojiId extends Snowflake>(emojiId: EmojiId, animated?: false): `<:_:${EmojiId}>`;
/** /**
* Formats an animated emoji id into a fully qualified emoji identifier. * Formats an animated emoji id into a fully qualified emoji identifier.
* *
* @typeParam C - This is inferred by the supplied emoji id * @typeParam EmojiId - This is inferred by the supplied emoji id
* @param emojiId - The emoji id to format * @param emojiId - The emoji id to format
* @param animated - Whether the emoji is animated * @param animated - Whether the emoji is animated
*/ */
export function formatEmoji<C extends Snowflake>(emojiId: C, animated?: true): `<a:_:${C}>`; export function formatEmoji<EmojiId extends Snowflake>(emojiId: EmojiId, animated?: true): `<a:_:${EmojiId}>`;
/** /**
* Formats an emoji id into a fully qualified emoji identifier. * Formats an emoji id into a fully qualified emoji identifier.
* *
* @typeParam C - This is inferred by the supplied emoji id * @typeParam EmojiId - This is inferred by the supplied emoji id
* @param emojiId - The emoji id to format * @param emojiId - The emoji id to format
* @param animated - Whether the emoji is animated * @param animated - Whether the emoji is animated
*/ */
export function formatEmoji<C extends Snowflake>(emojiId: C, animated?: boolean): `<:_:${C}>` | `<a:_:${C}>`; export function formatEmoji<EmojiId extends Snowflake>(
emojiId: EmojiId,
animated?: boolean,
): `<:_:${EmojiId}>` | `<a:_:${EmojiId}>`;
export function formatEmoji<C extends Snowflake>(emojiId: C, animated = false): `<:_:${C}>` | `<a:_:${C}>` { export function formatEmoji<EmojiId extends Snowflake>(
emojiId: EmojiId,
animated = false,
): `<:_:${EmojiId}>` | `<a:_:${EmojiId}>` {
return `<${animated ? 'a' : ''}:_:${emojiId}>`; return `<${animated ? 'a' : ''}:_:${emojiId}>`;
} }
/** /**
* Formats a channel link for a direct message channel. * Formats a channel link for a direct message channel.
* *
* @typeParam C - This is inferred by the supplied channel id * @typeParam ChannelId - This is inferred by the supplied channel id
* @param channelId - The channel's id * @param channelId - The channel's id
*/ */
export function channelLink<C extends Snowflake>(channelId: C): `https://discord.com/channels/@me/${C}`; export function channelLink<ChannelId extends Snowflake>(
channelId: ChannelId,
): `https://discord.com/channels/@me/${ChannelId}`;
/** /**
* Formats a channel link for a guild channel. * Formats a channel link for a guild channel.
* *
* @typeParam C - This is inferred by the supplied channel id * @typeParam ChannelId - This is inferred by the supplied channel id
* @typeParam G - This is inferred by the supplied guild id * @typeParam GuildId - This is inferred by the supplied guild id
* @param channelId - The channel's id * @param channelId - The channel's id
* @param guildId - The guild's id * @param guildId - The guild's id
*/ */
export function channelLink<C extends Snowflake, G extends Snowflake>( export function channelLink<ChannelId extends Snowflake, GuildId extends Snowflake>(
channelId: C, channelId: ChannelId,
guildId: G, guildId: GuildId,
): `https://discord.com/channels/${G}/${C}`; ): `https://discord.com/channels/${GuildId}/${ChannelId}`;
export function channelLink<C extends Snowflake, G extends Snowflake>( export function channelLink<ChannelId extends Snowflake, GuildId extends Snowflake>(
channelId: C, channelId: ChannelId,
guildId?: G, guildId?: GuildId,
): `https://discord.com/channels/@me/${C}` | `https://discord.com/channels/${G}/${C}` { ): `https://discord.com/channels/@me/${ChannelId}` | `https://discord.com/channels/${GuildId}/${ChannelId}` {
return `https://discord.com/channels/${guildId ?? '@me'}/${channelId}`; return `https://discord.com/channels/${guildId ?? '@me'}/${channelId}`;
} }
/** /**
* Formats a message link for a direct message channel. * Formats a message link for a direct message channel.
* *
* @typeParam C - This is inferred by the supplied channel id * @typeParam ChannelId - This is inferred by the supplied channel id
* @typeParam M - This is inferred by the supplied message id * @typeParam MessageId - This is inferred by the supplied message id
* @param channelId - The channel's id * @param channelId - The channel's id
* @param messageId - The message's id * @param messageId - The message's id
*/ */
export function messageLink<C extends Snowflake, M extends Snowflake>( export function messageLink<ChannelId extends Snowflake, MessageId extends Snowflake>(
channelId: C, channelId: ChannelId,
messageId: M, messageId: MessageId,
): `https://discord.com/channels/@me/${C}/${M}`; ): `https://discord.com/channels/@me/${ChannelId}/${MessageId}`;
/** /**
* Formats a message link for a guild channel. * Formats a message link for a guild channel.
* *
* @typeParam C - This is inferred by the supplied channel id * @typeParam ChannelId - This is inferred by the supplied channel id
* @typeParam M - This is inferred by the supplied message id * @typeParam MessageId - This is inferred by the supplied message id
* @typeParam G - This is inferred by the supplied guild id * @typeParam GuildId - This is inferred by the supplied guild id
* @param channelId - The channel's id * @param channelId - The channel's id
* @param messageId - The message's id * @param messageId - The message's id
* @param guildId - The guild's id * @param guildId - The guild's id
*/ */
export function messageLink<C extends Snowflake, M extends Snowflake, G extends Snowflake>( export function messageLink<ChannelId extends Snowflake, MessageId extends Snowflake, GuildId extends Snowflake>(
channelId: C, channelId: ChannelId,
messageId: M, messageId: MessageId,
guildId: G, guildId: GuildId,
): `https://discord.com/channels/${G}/${C}/${M}`; ): `https://discord.com/channels/${GuildId}/${ChannelId}/${MessageId}`;
export function messageLink<C extends Snowflake, M extends Snowflake, G extends Snowflake>( export function messageLink<ChannelId extends Snowflake, MessageId extends Snowflake, GuildId extends Snowflake>(
channelId: C, channelId: ChannelId,
messageId: M, messageId: MessageId,
guildId?: G, guildId?: GuildId,
): `https://discord.com/channels/@me/${C}/${M}` | `https://discord.com/channels/${G}/${C}/${M}` { ):
| `https://discord.com/channels/@me/${ChannelId}/${MessageId}`
| `https://discord.com/channels/${GuildId}/${ChannelId}/${MessageId}` {
return `${guildId === undefined ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`; return `${guildId === undefined ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`;
} }
@@ -394,29 +422,29 @@ export enum HeadingLevel {
/** /**
* Formats the content into a heading level. * Formats the content into a heading level.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
* @param level - The heading level * @param level - The heading level
*/ */
export function heading<C extends string>(content: C, level?: HeadingLevel.One): `# ${C}`; export function heading<Content extends string>(content: Content, level?: HeadingLevel.One): `# ${Content}`;
/** /**
* Formats the content into a heading level. * Formats the content into a heading level.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
* @param level - The heading level * @param level - The heading level
*/ */
export function heading<C extends string>(content: C, level: HeadingLevel.Two): `## ${C}`; export function heading<Content extends string>(content: Content, level: HeadingLevel.Two): `## ${Content}`;
/** /**
* Formats the content into a heading level. * Formats the content into a heading level.
* *
* @typeParam C - This is inferred by the supplied content * @typeParam Content - This is inferred by the supplied content
* @param content - The content to wrap * @param content - The content to wrap
* @param level - The heading level * @param level - The heading level
*/ */
export function heading<C extends string>(content: C, level: HeadingLevel.Three): `### ${C}`; export function heading<Content extends string>(content: Content, level: HeadingLevel.Three): `### ${Content}`;
export function heading(content: string, level?: HeadingLevel) { export function heading(content: string, level?: HeadingLevel) {
switch (level) { switch (level) {
@@ -432,7 +460,7 @@ export function heading(content: string, level?: HeadingLevel) {
/** /**
* A type that recursively traverses into arrays. * A type that recursively traverses into arrays.
*/ */
export type RecursiveArray<T> = readonly (RecursiveArray<T> | T)[]; export type RecursiveArray<ItemType> = readonly (ItemType | RecursiveArray<ItemType>)[];
/** /**
* Callback function for list formatters. * Callback function for list formatters.
@@ -476,29 +504,32 @@ export function time(date?: Date): `<t:${bigint}>`;
/** /**
* Formats a date given a format style. * Formats a date given a format style.
* *
* @typeParam S - This is inferred by the supplied {@link TimestampStylesString} * @typeParam Style - This is inferred by the supplied {@link TimestampStylesString}
* @param date - The date to format * @param date - The date to format
* @param style - The style to use * @param style - The style to use
*/ */
export function time<S extends TimestampStylesString>(date: Date, style: S): `<t:${bigint}:${S}>`; export function time<Style extends TimestampStylesString>(date: Date, style: Style): `<t:${bigint}:${Style}>`;
/** /**
* Formats the given timestamp into a short date-time string. * Formats the given timestamp into a short date-time string.
* *
* @typeParam C - This is inferred by the supplied timestamp * @typeParam Seconds - This is inferred by the supplied timestamp
* @param seconds - A Unix timestamp in seconds * @param seconds - A Unix timestamp in seconds
*/ */
export function time<C extends number>(seconds: C): `<t:${C}>`; export function time<Seconds extends number>(seconds: Seconds): `<t:${Seconds}>`;
/** /**
* Formats the given timestamp into a short date-time string. * Formats the given timestamp into a short date-time string.
* *
* @typeParam C - This is inferred by the supplied timestamp * @typeParam Seconds - This is inferred by the supplied timestamp
* @typeParam S - This is inferred by the supplied {@link TimestampStylesString} * @typeParam Style - This is inferred by the supplied {@link TimestampStylesString}
* @param seconds - A Unix timestamp in seconds * @param seconds - A Unix timestamp in seconds
* @param style - The style to use * @param style - The style to use
*/ */
export function time<C extends number, S extends TimestampStylesString>(seconds: C, style: S): `<t:${C}:${S}>`; export function time<Seconds extends number, Style extends TimestampStylesString>(
seconds: Seconds,
style: Style,
): `<t:${Seconds}:${Style}>`;
export function time(timeOrSeconds?: Date | number, style?: TimestampStylesString): string { export function time(timeOrSeconds?: Date | number, style?: TimestampStylesString): string {
if (typeof timeOrSeconds !== 'number') { if (typeof timeOrSeconds !== 'number') {

View File

@@ -33,7 +33,7 @@ function serializeSearchParam(value: unknown): string | null {
* @param options - The options to use * @param options - The options to use
* @returns A populated URLSearchParams instance * @returns A populated URLSearchParams instance
*/ */
export function makeURLSearchParams<T extends object>(options?: Readonly<T>) { export function makeURLSearchParams<OptionsType extends object>(options?: Readonly<OptionsType>) {
const params = new URLSearchParams(); const params = new URLSearchParams();
if (!options) return params; if (!options) return params;

View File

@@ -2,13 +2,13 @@
* Represents a structure that can be checked against another * Represents a structure that can be checked against another
* given structure for equality * given structure for equality
* *
* @typeParam T - The type of object to compare the current object to * @typeParam Value - The type of object to compare the current object to
*/ */
export interface Equatable<T> { export interface Equatable<Value> {
/** /**
* Whether or not this is equal to another structure * Whether or not this is equal to another structure
*/ */
equals(other: T): boolean; equals(other: Value): boolean;
} }
/** /**

View File

@@ -1,13 +1,13 @@
/** /**
* Represents an object capable of representing itself as a JSON object * Represents an object capable of representing itself as a JSON object
* *
* @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs. * @typeParam Value - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.
*/ */
export interface JSONEncodable<T> { export interface JSONEncodable<Value> {
/** /**
* Transforms this object to its JSON format * Transforms this object to its JSON format
*/ */
toJSON(): T; toJSON(): Value;
} }
/** /**

View File

@@ -4,15 +4,15 @@
* be needed at all. * be needed at all.
* *
* @param cb - The callback to lazily evaluate * @param cb - The callback to lazily evaluate
* @typeParam T - The type of the value * @typeParam Value - The type of the value
* @example * @example
* ```ts * ```ts
* const value = lazy(() => computeExpensiveValue()); * const value = lazy(() => computeExpensiveValue());
* ``` * ```
*/ */
// eslint-disable-next-line promise/prefer-await-to-callbacks // eslint-disable-next-line promise/prefer-await-to-callbacks
export function lazy<T>(cb: () => T): () => T { export function lazy<Value>(cb: () => Value): () => Value {
let defaultValue: T; let defaultValue: Value;
// eslint-disable-next-line promise/prefer-await-to-callbacks // eslint-disable-next-line promise/prefer-await-to-callbacks
return () => (defaultValue ??= cb()); return () => (defaultValue ??= cb());
} }

View File

@@ -1,4 +1,4 @@
/** /**
* Represents a type that may or may not be a promise * Represents a type that may or may not be a promise
*/ */
export type Awaitable<T> = PromiseLike<T> | T; export type Awaitable<Value> = PromiseLike<Value> | Value;

View File

@@ -2,7 +2,7 @@ import { type EventEmitter, once } from 'node:events';
import process from 'node:process'; import process from 'node:process';
import { SSRCMap, type VoiceUserData } from '../src/receive/SSRCMap'; import { SSRCMap, type VoiceUserData } from '../src/receive/SSRCMap';
async function onceOrThrow<T extends EventEmitter>(target: T, event: string, after: number) { async function onceOrThrow<Emitter extends EventEmitter>(target: Emitter, event: string, after: number) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
target.on(event, resolve); target.on(event, resolve);
setTimeout(() => reject(new Error('Time up')), after); setTimeout(() => reject(new Error('Time up')), after);

View File

@@ -7,13 +7,13 @@ beforeEach(() => {
WS.clean(); WS.clean();
}); });
async function onceIgnoreError<T extends EventEmitter>(target: T, event: string) { async function onceIgnoreError<Emitter extends EventEmitter>(target: Emitter, event: string) {
return new Promise((resolve) => { return new Promise((resolve) => {
target.on(event, resolve); target.on(event, resolve);
}); });
} }
async function onceOrThrow<T extends EventEmitter>(target: T, event: string, after: number) { async function onceOrThrow<Emitter extends EventEmitter>(target: Emitter, event: string, after: number) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
target.on(event, resolve); target.on(event, resolve);
setTimeout(() => reject(new Error('Time up')), after); setTimeout(() => reject(new Error('Time up')), after);

View File

@@ -187,9 +187,9 @@ export interface VoiceConnection extends EventEmitter {
* *
* @eventProperty * @eventProperty
*/ */
on<T extends VoiceConnectionStatus>( on<Event extends VoiceConnectionStatus>(
event: T, event: Event,
listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState & { status: T }) => void, listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState & { status: Event }) => void,
): this; ): this;
} }

View File

@@ -182,9 +182,9 @@ export interface AudioPlayer extends EventEmitter {
* *
* @eventProperty * @eventProperty
*/ */
on<T extends AudioPlayerStatus>( on<Event extends AudioPlayerStatus>(
event: T, event: Event,
listener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: T }) => void, listener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: Event }) => void,
): this; ): this;
} }
@@ -375,7 +375,7 @@ export class AudioPlayer extends EventEmitter {
* @param resource - The resource to play * @param resource - The resource to play
* @throws Will throw if attempting to play an audio resource that has already ended, or is being played by another player * @throws Will throw if attempting to play an audio resource that has already ended, or is being played by another player
*/ */
public play<T>(resource: AudioResource<T>) { public play<Metadata>(resource: AudioResource<Metadata>) {
if (resource.ended) { if (resource.ended) {
throw new Error('Cannot play a resource that has already ended.'); throw new Error('Cannot play a resource that has already ended.');
} }

View File

@@ -8,9 +8,9 @@ import { findPipeline, StreamType, TransformerType, type Edge } from './Transfor
/** /**
* Options that are set when creating a new audio resource. * Options that are set when creating a new audio resource.
* *
* @typeParam T - the type for the metadata (if any) of the audio resource * @typeParam Metadata - the type for the metadata (if any) of the audio resource
*/ */
export interface CreateAudioResourceOptions<T> { export interface CreateAudioResourceOptions<Metadata> {
/** /**
* Whether or not inline volume should be enabled. If enabled, you will be able to change the volume * Whether or not inline volume should be enabled. If enabled, you will be able to change the volume
* of the stream on-the-fly. However, this also increases the performance cost of playback. Defaults to `false`. * of the stream on-the-fly. However, this also increases the performance cost of playback. Defaults to `false`.
@@ -27,7 +27,7 @@ export interface CreateAudioResourceOptions<T> {
* This is useful for identification purposes when the resource is passed around in events. * This is useful for identification purposes when the resource is passed around in events.
* See {@link AudioResource.metadata} * See {@link AudioResource.metadata}
*/ */
metadata?: T; metadata?: Metadata;
/** /**
* The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches. * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches.
@@ -39,9 +39,9 @@ export interface CreateAudioResourceOptions<T> {
/** /**
* Represents an audio resource that can be played by an audio player. * Represents an audio resource that can be played by an audio player.
* *
* @typeParam T - the type for the metadata (if any) of the audio resource * @typeParam Metadata - the type for the metadata (if any) of the audio resource
*/ */
export class AudioResource<T = unknown> { export class AudioResource<Metadata = unknown> {
/** /**
* An object-mode Readable stream that emits Opus packets. This is what is played by audio players. * An object-mode Readable stream that emits Opus packets. This is what is played by audio players.
*/ */
@@ -57,7 +57,7 @@ export class AudioResource<T = unknown> {
/** /**
* Optional metadata that can be used to identify the resource. * Optional metadata that can be used to identify the resource.
*/ */
public metadata: T; public metadata: Metadata;
/** /**
* If the resource was created with inline volume transformation enabled, then this will be a * If the resource was created with inline volume transformation enabled, then this will be a
@@ -96,7 +96,12 @@ export class AudioResource<T = unknown> {
*/ */
public silenceRemaining = -1; public silenceRemaining = -1;
public constructor(edges: readonly Edge[], streams: readonly Readable[], metadata: T, silencePaddingFrames: number) { public constructor(
edges: readonly Edge[],
streams: readonly Readable[],
metadata: Metadata,
silencePaddingFrames: number,
) {
this.edges = edges; this.edges = edges;
this.playStream = streams.length > 1 ? (pipeline(streams, noop) as any as Readable) : streams[0]!; this.playStream = streams.length > 1 ? (pipeline(streams, noop) as any as Readable) : streams[0]!;
this.metadata = metadata; this.metadata = metadata;
@@ -206,16 +211,18 @@ export function inferStreamType(stream: Readable): {
* Opus transcoders, and Ogg/WebM demuxers. * Opus transcoders, and Ogg/WebM demuxers.
* @param input - The resource to play * @param input - The resource to play
* @param options - Configurable options for creating the resource * @param options - Configurable options for creating the resource
* @typeParam T - the type for the metadata (if any) of the audio resource * @typeParam Metadata - the type for the metadata (if any) of the audio resource
*/ */
export function createAudioResource<T>( export function createAudioResource<Metadata>(
input: Readable | string, input: Readable | string,
options: CreateAudioResourceOptions<T> & options: CreateAudioResourceOptions<Metadata> &
Pick< Pick<
T extends null | undefined ? CreateAudioResourceOptions<T> : Required<CreateAudioResourceOptions<T>>, Metadata extends null | undefined
? CreateAudioResourceOptions<Metadata>
: Required<CreateAudioResourceOptions<Metadata>>,
'metadata' 'metadata'
>, >,
): AudioResource<T extends null | undefined ? null : T>; ): AudioResource<Metadata extends null | undefined ? null : Metadata>;
/** /**
* Creates an audio resource that can be played by audio players. * Creates an audio resource that can be played by audio players.
@@ -228,11 +235,11 @@ export function createAudioResource<T>(
* Opus transcoders, and Ogg/WebM demuxers. * Opus transcoders, and Ogg/WebM demuxers.
* @param input - The resource to play * @param input - The resource to play
* @param options - Configurable options for creating the resource * @param options - Configurable options for creating the resource
* @typeParam T - the type for the metadata (if any) of the audio resource * @typeParam Metadata - the type for the metadata (if any) of the audio resource
*/ */
export function createAudioResource<T extends null | undefined>( export function createAudioResource<Metadata extends null | undefined>(
input: Readable | string, input: Readable | string,
options?: Omit<CreateAudioResourceOptions<T>, 'metadata'>, options?: Omit<CreateAudioResourceOptions<Metadata>, 'metadata'>,
): AudioResource<null>; ): AudioResource<null>;
/** /**
@@ -246,12 +253,12 @@ export function createAudioResource<T extends null | undefined>(
* Opus transcoders, and Ogg/WebM demuxers. * Opus transcoders, and Ogg/WebM demuxers.
* @param input - The resource to play * @param input - The resource to play
* @param options - Configurable options for creating the resource * @param options - Configurable options for creating the resource
* @typeParam T - the type for the metadata (if any) of the audio resource * @typeParam Metadata - the type for the metadata (if any) of the audio resource
*/ */
export function createAudioResource<T>( export function createAudioResource<Metadata>(
input: Readable | string, input: Readable | string,
options: CreateAudioResourceOptions<T> = {}, options: CreateAudioResourceOptions<Metadata> = {},
): AudioResource<T> { ): AudioResource<Metadata> {
let inputType = options.inputType; let inputType = options.inputType;
let needsInlineVolume = Boolean(options.inlineVolume); let needsInlineVolume = Boolean(options.inlineVolume);
@@ -269,16 +276,21 @@ export function createAudioResource<T>(
if (transformerPipeline.length === 0) { if (transformerPipeline.length === 0) {
if (typeof input === 'string') throw new Error(`Invalid pipeline constructed for string resource '${input}'`); if (typeof input === 'string') throw new Error(`Invalid pipeline constructed for string resource '${input}'`);
// No adjustments required // No adjustments required
return new AudioResource<T>([], [input], (options.metadata ?? null) as T, options.silencePaddingFrames ?? 5); return new AudioResource<Metadata>(
[],
[input],
(options.metadata ?? null) as Metadata,
options.silencePaddingFrames ?? 5,
);
} }
const streams = transformerPipeline.map((edge) => edge.transformer(input)); const streams = transformerPipeline.map((edge) => edge.transformer(input));
if (typeof input !== 'string') streams.unshift(input); if (typeof input !== 'string') streams.unshift(input);
return new AudioResource<T>( return new AudioResource<Metadata>(
transformerPipeline, transformerPipeline,
streams, streams,
(options.metadata ?? null) as T, (options.metadata ?? null) as Metadata,
options.silencePaddingFrames ?? 5, options.silencePaddingFrames ?? 5,
); );
} }

View File

@@ -36,8 +36,8 @@ export function entersState(
* @param status - The status that the target should be in * @param status - The status that the target should be in
* @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation
*/ */
export async function entersState<T extends AudioPlayer | VoiceConnection>( export async function entersState<Target extends AudioPlayer | VoiceConnection>(
target: T, target: Target,
status: AudioPlayerStatus | VoiceConnectionStatus, status: AudioPlayerStatus | VoiceConnectionStatus,
timeoutOrSignal: AbortSignal | number, timeoutOrSignal: AbortSignal | number,
) { ) {

6
pnpm-lock.yaml generated
View File

@@ -947,6 +947,12 @@ importers:
'@types/node': '@types/node':
specifier: 16.18.60 specifier: 16.18.60
version: 16.18.60 version: 16.18.60
'@typescript-eslint/eslint-plugin':
specifier: ^6.10.0
version: 6.10.0(@typescript-eslint/parser@6.10.0)(eslint@8.53.0)(typescript@5.2.2)
'@typescript-eslint/parser':
specifier: ^6.10.0
version: 6.10.0(eslint@8.53.0)(typescript@5.2.2)
cross-env: cross-env:
specifier: ^7.0.3 specifier: ^7.0.3
version: 7.0.3 version: 7.0.3