chore: fix leftover eslint exceptions

This commit is contained in:
iCrawl
2022-09-01 21:26:09 +02:00
parent edadb9fe5d
commit 3b7ba4062e
80 changed files with 141 additions and 337 deletions

View File

@@ -2,18 +2,18 @@ import { relative, resolve } from 'node:path';
import glob from 'fast-glob';
import isCi from 'is-ci';
import typescript from 'rollup-plugin-typescript2';
import { defineBuildConfig, BuildEntry } from 'unbuild';
import { defineBuildConfig, type BuildEntry } from 'unbuild';
interface ConfigOptions {
entries: (BuildEntry | string)[];
minify: boolean;
emitCJS: boolean;
externals: string[];
cjsBridge: boolean;
sourcemap: boolean;
declaration: boolean;
emitCJS: boolean;
entries: (BuildEntry | string)[];
externals: string[];
minify: boolean;
preserveModules: boolean;
preserveModulesRoot: string;
declaration: boolean;
sourcemap: boolean;
typeCheck: boolean;
}
@@ -31,8 +31,7 @@ export function createUnbuildConfig({
}: Partial<ConfigOptions> = {}) {
const files = glob
.sync('**', { cwd: 'src' })
.map((file) => [`${file.slice(0, -2)}cjs`, `${file.slice(0, -2)}mjs`])
.flat();
.flatMap((file) => [`${file.slice(0, -2)}cjs`, `${file.slice(0, -2)}mjs`]);
return defineBuildConfig({
entries,
@@ -55,7 +54,6 @@ export function createUnbuildConfig({
hooks: {
'rollup:options': (_, options) => {
// @ts-expect-error: This will always be an array
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
options.output![0] = {
// @ts-expect-error: This will always be an array
...options.output![0],
@@ -66,7 +64,6 @@ export function createUnbuildConfig({
if (emitCJS) {
// @ts-expect-error: This will always be an array
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
options.output![1] = {
// @ts-expect-error: This will always be an array
...options.output![1],

View File

@@ -20,8 +20,8 @@ import {
} from '@microsoft/api-extractor-model';
import { generateTypeParamData } from './TypeParameterJSONEncoder.js';
import { type TokenDocumentation, resolveName, genReference, genToken, genParameter, generatePath } from './parse.js';
import type { DocBlockJSON } from './tsdoc/CommentBlock';
import type { AnyDocNodeJSON } from './tsdoc/CommentNode';
import type { DocBlockJSON } from './tsdoc/CommentBlock.js';
import type { AnyDocNodeJSON } from './tsdoc/CommentNode.js';
import { type DocNodeContainerJSON, nodeContainer } from './tsdoc/CommentNodeContainer.js';
import { createCommentNode } from './tsdoc/index.js';
@@ -140,7 +140,6 @@ export interface ApiConstructorJSON extends ApiItemJSON, ApiParameterListJSON {
protected: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class ApiNodeJSONEncoder {
public static encode(model: ApiModel, node: ApiItem, version: string) {
if (!(node instanceof ApiDeclaredItem)) {

View File

@@ -1,11 +1,11 @@
import type { DocNode, DocNodeKind } from '@microsoft/tsdoc';
import type { DocBlockJSON } from './CommentBlock';
import type { DocCodeSpanJSON } from './CommentCodeSpan';
import type { DocNodeContainerJSON } from './CommentNodeContainer';
import type { DocFencedCodeJSON } from './FencedCodeCommentNode';
import type { DocLinkTagJSON } from './LinkTagCommentNode';
import type { DocPlainTextJSON } from './PlainTextCommentNode';
import type { DocCommentJSON } from './RootComment';
import type { DocBlockJSON } from './CommentBlock.js';
import type { DocCodeSpanJSON } from './CommentCodeSpan.js';
import type { DocNodeContainerJSON } from './CommentNodeContainer.js';
import type { DocFencedCodeJSON } from './FencedCodeCommentNode.js';
import type { DocLinkTagJSON } from './LinkTagCommentNode.js';
import type { DocPlainTextJSON } from './PlainTextCommentNode.js';
import type { DocCommentJSON } from './RootComment.js';
export interface DocNodeJSON {
kind: DocNodeKind;

View File

@@ -71,7 +71,7 @@ describe('Button Components', () => {
}).toThrowError();
expect(() => {
// @ts-expect-error: invalid emoji
// @ts-expect-error: Invalid emoji
const button = buttonComponent().setEmoji('test');
button.toJSON();
}).toThrowError();
@@ -103,9 +103,9 @@ describe('Button Components', () => {
expect(() => buttonComponent().setStyle(24)).toThrowError();
expect(() => buttonComponent().setLabel(longStr)).toThrowError();
// @ts-expect-error: invalid parameter for disabled
// @ts-expect-error: Invalid parameter for disabled
expect(() => buttonComponent().setDisabled(0)).toThrowError();
// @ts-expect-error: invalid emoji
// @ts-expect-error: Invalid emoji
expect(() => buttonComponent().setEmoji('foo')).toThrowError();
expect(() => buttonComponent().setURL('foobar')).toThrowError();

View File

@@ -98,30 +98,30 @@ describe('Select Menu Components', () => {
expect(() => selectMenu().setCustomId(longStr)).toThrowError();
expect(() => selectMenu().setMaxValues(30)).toThrowError();
expect(() => selectMenu().setMinValues(-20)).toThrowError();
// @ts-expect-error: invalid disabled value
// @ts-expect-error: Invalid disabled value
expect(() => selectMenu().setDisabled(0)).toThrowError();
expect(() => selectMenu().setPlaceholder(longStr)).toThrowError();
// @ts-expect-error: invalid option
// @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions({ label: 'test' })).toThrowError();
expect(() => selectMenu().addOptions({ label: longStr, value: 'test' })).toThrowError();
expect(() => selectMenu().addOptions({ value: longStr, label: 'test' })).toThrowError();
expect(() => selectMenu().addOptions({ label: 'test', value: 'test', description: longStr })).toThrowError();
// @ts-expect-error: invalid option
// @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions({ label: 'test', value: 'test', default: 100 })).toThrowError();
// @ts-expect-error: invalid option
// @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions({ value: 'test' })).toThrowError();
// @ts-expect-error: invalid option
// @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions({ default: true })).toThrowError();
// @ts-expect-error: invalid option
// @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions([{ label: 'test' }])).toThrowError();
expect(() => selectMenu().addOptions([{ label: longStr, value: 'test' }])).toThrowError();
expect(() => selectMenu().addOptions([{ value: longStr, label: 'test' }])).toThrowError();
expect(() => selectMenu().addOptions([{ label: 'test', value: 'test', description: longStr }])).toThrowError();
// @ts-expect-error: invalid option
// @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions([{ label: 'test', value: 'test', default: 100 }])).toThrowError();
// @ts-expect-error: invalid option
// @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions([{ value: 'test' }])).toThrowError();
// @ts-expect-error: invalid option
// @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions([{ default: true }])).toThrowError();
const tooManyOptions = Array.from<APISelectMenuOption>({ length: 26 }).fill({ label: 'test', value: 'test' });
@@ -144,9 +144,9 @@ describe('Select Menu Components', () => {
selectMenuOption()
.setLabel(longStr)
.setValue(longStr)
// @ts-expect-error: invalid default value
// @ts-expect-error: Invalid default value
.setDefault(-1)
// @ts-expect-error: invalid emoji
// @ts-expect-error: Invalid emoji
.setEmoji({ name: 1 })
.setDescription(longStr);
}).toThrowError();

View File

@@ -85,7 +85,7 @@ describe('Text Input Components', () => {
expect(() => {
// Issue #8107
// @ts-expect-error: shapeshift maps the enum key to the value when parsing
// @ts-expect-error: Shapeshift maps the enum key to the value when parsing
textInputComponent().setCustomId('Custom').setLabel('Guess').setStyle('Short').toJSON();
}).not.toThrowError();
});

View File

@@ -105,9 +105,9 @@ describe('Context Menu Commands', () => {
});
test('GIVEN invalid name localizations THEN does throw error', () => {
// @ts-expect-error: invalid localization
// @ts-expect-error: Invalid localization
expect(() => getBuilder().setNameLocalization('en-U', 'foobar')).toThrowError();
// @ts-expect-error: invalid localization
// @ts-expect-error: Invalid localization
expect(() => getBuilder().setNameLocalizations({ 'en-U': 'foobar' })).toThrowError();
});

View File

@@ -101,7 +101,8 @@ describe('Application Command toJSON() results', () => {
max_value: 10,
min_value: -1,
autocomplete: true,
// @ts-expect-error TODO: you *can* send an empty array with autocomplete: true, should correct that in types
// TODO
// @ts-expect-error You *can* send an empty array with autocomplete: true, should correct that in types
choices: [],
});
@@ -145,7 +146,8 @@ describe('Application Command toJSON() results', () => {
max_value: 10,
min_value: -1.23,
autocomplete: true,
// @ts-expect-error TODO: you *can* send an empty array with autocomplete: true, should correct that in types
// TODO
// @ts-expect-error You *can* send an empty array with autocomplete: true, should correct that in types
choices: [],
});
@@ -187,7 +189,8 @@ describe('Application Command toJSON() results', () => {
type: ApplicationCommandOptionType.String,
required: true,
autocomplete: true,
// @ts-expect-error TODO: you *can* send an empty array with autocomplete: true, should correct that in types
// TODO
// @ts-expect-error you *can* send an empty array with autocomplete: true, should correct that in types
choices: [],
});

View File

@@ -176,7 +176,7 @@ describe('Slash Commands', () => {
});
test('GIVEN a builder with invalid autocomplete THEN does throw an error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addStringOption(getStringOption().setAutocomplete('not a boolean'))).toThrowError();
});
@@ -246,16 +246,16 @@ describe('Slash Commands', () => {
});
test('GIVEN a builder with invalid number min/max options THEN does throw an error', () => {
// @ts-expect-error: invalid max value
// @ts-expect-error: Invalid max value
expect(() => getBuilder().addNumberOption(getNumberOption().setMaxValue('test'))).toThrowError();
// @ts-expect-error: invalid max value
// @ts-expect-error: Invalid max value
expect(() => getBuilder().addIntegerOption(getIntegerOption().setMaxValue('test'))).toThrowError();
// @ts-expect-error: invalid min value
// @ts-expect-error: Invalid min value
expect(() => getBuilder().addNumberOption(getNumberOption().setMinValue('test'))).toThrowError();
// @ts-expect-error: invalid min value
// @ts-expect-error: Invalid min value
expect(() => getBuilder().addIntegerOption(getIntegerOption().setMinValue('test'))).toThrowError();
expect(() => getBuilder().addIntegerOption(getIntegerOption().setMinValue(1.5))).toThrowError();
@@ -292,10 +292,10 @@ describe('Slash Commands', () => {
});
test('GIVEN no valid return for an addOption method THEN throw error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption()).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(getRoleOption())).toThrowError();
});
@@ -316,18 +316,18 @@ describe('Slash Commands', () => {
});
test('GIVEN invalid returns for builder THEN throw error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(true)).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(null)).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(undefined)).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(() => SlashCommandStringOption)).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(() => new Collection())).toThrowError();
});
@@ -387,30 +387,29 @@ describe('Slash Commands', () => {
test('GIVEN builder with a subcommand that tries to add an invalid result THEN throw error', () => {
expect(() =>
// @ts-expect-error Checking if check works JS-side too
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call
// @ts-expect-error: Checking if check works JS-side too
getNamedBuilder().addSubcommand(getSubcommand()).addInteger(getInteger()),
).toThrowError();
});
test('GIVEN no valid return for an addSubcommand(Group) method THEN throw error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addSubcommandGroup()).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addSubcommand()).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addSubcommand(getSubcommandGroup())).toThrowError();
});
});
describe('Subcommand group builder', () => {
test('GIVEN no valid subcommand THEN throw error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getSubcommandGroup().addSubcommand()).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error
// @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getSubcommandGroup().addSubcommand(getSubcommandGroup())).toThrowError();
});
@@ -442,9 +441,9 @@ describe('Slash Commands', () => {
});
test('GIVEN invalid name localizations THEN does throw error', () => {
// @ts-expect-error: invalid localization
// @ts-expect-error: Invalid localization
expect(() => getBuilder().setNameLocalization('en-U', 'foobar')).toThrowError();
// @ts-expect-error: invalid localization
// @ts-expect-error: Invalid localization
expect(() => getBuilder().setNameLocalizations({ 'en-U': 'foobar' })).toThrowError();
});
@@ -465,9 +464,9 @@ describe('Slash Commands', () => {
});
test('GIVEN invalid description localizations THEN does throw error', () => {
// @ts-expect-error: invalid localization description
// @ts-expect-error: Invalid localization description
expect(() => getBuilder().setDescriptionLocalization('en-U', 'foobar')).toThrowError();
// @ts-expect-error: invalid localization description
// @ts-expect-error: Invalid localization description
expect(() => getBuilder().setDescriptionLocalizations({ 'en-U': 'foobar' })).toThrowError();
});

View File

@@ -46,7 +46,7 @@ describe('Modals', () => {
test('GIVEN invalid required parameters THEN validator does throw', () => {
expect(() =>
// @ts-expect-error: missing required parameter
// @ts-expect-error: Missing required parameter
validateRequiredParameters('123', undefined, [new ActionRowBuilder(), new ButtonBuilder()]),
).toThrowError();
});
@@ -66,7 +66,7 @@ describe('Modals', () => {
test('GIVEN invalid fields THEN builder does throw', () => {
expect(() => modal().setTitle('test').setCustomId('foobar').toJSON()).toThrowError();
// @ts-expect-error: customId is invalid
// @ts-expect-error: CustomId is invalid
expect(() => modal().setTitle('test').setCustomId(42).toJSON()).toThrowError();
});

View File

@@ -130,9 +130,9 @@ describe('Embed', () => {
test('GIVEN an embed with an invalid color THEN throws error', () => {
const embed = new EmbedBuilder();
// @ts-expect-error: invalid color
// @ts-expect-error: Invalid color
expect(() => embed.setColor('RED')).toThrowError();
// @ts-expect-error: invalid color
// @ts-expect-error: Invalid color
expect(() => embed.setColor([42, 36])).toThrowError();
expect(() => embed.setColor([42, 36, 1_000])).toThrowError();
});

View File

@@ -8,9 +8,9 @@ import {
import { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';
import { ComponentBuilder } from './Component.js';
import { createComponentBuilder } from './Components.js';
import type { ButtonBuilder } from './button/Button';
import type { SelectMenuBuilder } from './selectMenu/SelectMenu';
import type { TextInputBuilder } from './textInput/TextInput';
import type { ButtonBuilder } from './button/Button.js';
import type { SelectMenuBuilder } from './selectMenu/SelectMenu.js';
import type { TextInputBuilder } from './textInput/TextInput.js';
export type MessageComponentBuilder =
| ActionRowBuilder<MessageActionRowComponentBuilder>
@@ -62,7 +62,6 @@ export class ActionRowBuilder<T extends AnyComponentBuilder> extends ComponentBu
* {@inheritDoc ComponentBuilder.toJSON}
*/
public toJSON(): APIActionRowComponent<ReturnType<T['toJSON']>> {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {
...this.data,
components: this.components.map((component) => component.toJSON()),

View File

@@ -45,7 +45,6 @@ export function createComponentBuilder(
return new TextInputBuilder(data);
default:
// @ts-expect-error: This case can still occur if we get a newer unsupported component type
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Cannot properly serialize component type: ${data.type}`);
}
}

View File

@@ -129,7 +129,7 @@ export class ButtonBuilder extends ComponentBuilder<APIButtonComponent> {
(this.data as APIButtonComponentWithCustomId).custom_id,
(this.data as APIButtonComponentWithURL).url,
);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {
...this.data,
} as APIButtonComponent;

View File

@@ -123,7 +123,7 @@ export class SelectMenuBuilder extends ComponentBuilder<APISelectMenuComponent>
*/
public toJSON(): APISelectMenuComponent {
validateRequiredSelectMenuParameters(this.options, this.data.custom_id);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {
...this.data,
options: this.options.map((option) => option.toJSON()),

View File

@@ -68,7 +68,7 @@ export class SelectMenuOptionBuilder implements JSONEncodable<APISelectMenuOptio
*/
public toJSON(): APISelectMenuOption {
validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {
...this.data,
} as APISelectMenuOption;

View File

@@ -108,7 +108,7 @@ export class TextInputBuilder
*/
public toJSON(): APITextInputComponent {
validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {
...this.data,
} as APITextInputComponent;

View File

@@ -1,7 +1,7 @@
import { s } from '@sapphire/shapeshift';
import { ApplicationCommandType } from 'discord-api-types/v10';
import { isValidationEnabled } from '../../util/validation.js';
import type { ContextMenuCommandType } from './ContextMenuCommandBuilder';
import type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';
const namePredicate = s.string
.lengthGreaterThanOrEqual(1)

View File

@@ -76,7 +76,7 @@ export class ModalBuilder implements JSONEncodable<APIModalInteractionResponseCa
*/
public toJSON(): APIModalInteractionResponseCallbackData {
validateRequiredParameters(this.data.custom_id, this.data.title, this.components);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {
...this.data,
components: this.components.map((component) => component.toJSON()),

View File

@@ -1,9 +1,9 @@
import { s } from '@sapphire/shapeshift';
import { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';
import { isValidationEnabled } from '../../util/validation.js';
import type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder';
import type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands';
import type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase';
import type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';
import type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';
import type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';
const namePredicate = s.string
.lengthGreaterThanOrEqual(1)

View File

@@ -6,7 +6,7 @@ import {
import { mix } from 'ts-mixer';
import { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';
import type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';
import type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase';
import type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';
import { SharedNameAndDescription } from './mixins/NameAndDescription.js';
import { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';

View File

@@ -96,7 +96,6 @@ export function hideLinkEmbed<C extends string>(url: C): `<${C}>`;
*/
export function hideLinkEmbed(url: URL): `<${string}>`;
export function hideLinkEmbed(url: URL | string) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `<${url}>`;
}
@@ -142,7 +141,6 @@ export function hyperlink<C extends string, U extends string, T extends string>(
title: T,
): `[${C}](${U} "${T}")`;
export function hyperlink(content: string, url: URL | string, title?: string) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`;
}

View File

@@ -20,7 +20,6 @@ function createTestCollection(): TestCollection {
function expectInvalidFunctionError(cb: () => unknown, val?: unknown): void {
expect(() => {
cb();
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
}).toThrowError(new TypeError(`${val} is not a function`));
}
@@ -133,9 +132,9 @@ describe('each() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.each());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.each(123), 123);
});
@@ -154,7 +153,7 @@ describe('each() tests', () => {
describe('ensure() tests', () => {
test('throws if defaultValueGenerator is not a function', () => {
const coll = createTestCollection();
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.ensure('d', 'abc'), 'abc');
});
@@ -178,7 +177,7 @@ describe('equals() tests', () => {
const coll2 = createTestCollection();
test('returns false if no collection is passed', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expect(coll1.equals()).toBeFalsy();
});
@@ -200,9 +199,9 @@ describe('every() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.every());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.every(123), 123);
});
@@ -226,9 +225,9 @@ describe('filter() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.filter());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.filter(123), 123);
});
@@ -253,9 +252,9 @@ describe('find() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => createCollection().find());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => createCollection().find(123), 123);
});
@@ -277,9 +276,9 @@ describe('findKey() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.findKey());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.findKey(123), 123);
});
@@ -508,9 +507,9 @@ describe('map() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.map());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.map(123), 123);
});
@@ -531,9 +530,9 @@ describe('mapValues() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.mapValues());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.mapValues(123), 123);
});
@@ -608,9 +607,9 @@ describe('partition() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.partition());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.partition(123), 123);
});
@@ -692,9 +691,9 @@ describe('reduce() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.reduce());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.reduce(123), 123);
});
@@ -731,9 +730,9 @@ describe('some() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.some());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.some(123), 123);
});
@@ -775,9 +774,9 @@ describe('sweep() test', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.sweep());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.sweep(123), 123);
});
@@ -802,9 +801,9 @@ describe('tap() tests', () => {
const coll = createTestCollection();
test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.tap());
// @ts-expect-error: invalid function
// @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.tap(123), 123);
});

View File

@@ -85,12 +85,10 @@ export class Collection<K, V> extends Map<K, V> {
public first(): V | undefined;
public first(amount: number): V[];
public first(amount?: number): V | V[] | undefined {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
if (typeof amount === 'undefined') return this.values().next().value;
if (amount < 0) return this.last(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.values();
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return Array.from({ length: amount }, (): V => iter.next().value);
}
@@ -104,12 +102,10 @@ export class Collection<K, V> extends Map<K, V> {
public firstKey(): K | undefined;
public firstKey(amount: number): K[];
public firstKey(amount?: number): K | K[] | undefined {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
if (typeof amount === 'undefined') return this.keys().next().value;
if (amount < 0) return this.lastKey(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.keys();
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return Array.from({ length: amount }, (): K => iter.next().value);
}
@@ -426,9 +422,7 @@ export class Collection<K, V> extends Map<K, V> {
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
const iter = this.entries();
return Array.from({ length: this.size }, (): T => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const [key, value] = iter.next().value;
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return fn(value, key, this);
});
}
@@ -636,7 +630,6 @@ export class Collection<K, V> extends Map<K, V> {
* @returns Whether the collections have identical contents
*/
public equals(collection: ReadonlyCollection<K, V>) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!collection) return false; // runtime check
if (this === collection) return true;
if (this.size !== collection.size) return false;

View File

@@ -123,7 +123,6 @@ export class Documentation {
case 'Method': {
const event = prop?.groups?.find((group) => group.title === 'Events');
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if ((event?.children as unknown as number[])?.includes(member.id)) {
item = new DocumentedEvent(member, this.config);
break;
@@ -139,7 +138,6 @@ export class Documentation {
}
default: {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.warn(`- Unknown documentation kind "${member.kindString}" - \n${JSON.stringify(member)}\n`);
}
}
@@ -212,7 +210,6 @@ export class Documentation {
default: {
// @ts-expect-error: This is a valid case
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.warn(`- Unknown documentation kind "${member.kind}" - \n${JSON.stringify(member)}\n`);
}
}
@@ -233,7 +230,6 @@ export class Documentation {
const info = [];
const name = (member.name || item?.data.name) ?? 'UNKNOWN';
// @ts-expect-error: Typescript can't infer this
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unnecessary-condition
const memberof = member.memberof ?? item?.data?.memberof;
const meta =
member.kind === 'constructor'

View File

@@ -2,9 +2,9 @@ import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, extname, basename, relative } from 'node:path';
import jsdoc2md from 'jsdoc-to-markdown';
import { type DeclarationReflection, Application, TSConfigReader } from 'typedoc';
import type { CLIOptions } from './cli';
import type { CLIOptions } from './cli.js';
import { Documentation } from './documentation.js';
import type { RootTypes, ChildTypes, CustomDocs } from './interfaces';
import type { RootTypes, ChildTypes, CustomDocs } from './interfaces/index.js';
interface CustomFiles {
files: {

View File

@@ -58,7 +58,6 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
this.construct = item;
} else if (item instanceof DocumentedMethod) {
// @ts-expect-error: No type for methods
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const prefix = item.data.scope === 'static' || item.data.flags?.isStatic ? 's-' : '';
if (this.methods.has(prefix + item.data.name)) {
throw new Error(`Doc ${this.data.name} already has method ${item.data.name}`);
@@ -91,7 +90,6 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
meta = new DocumentedItemMeta(sources, this.config).serialize();
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags
.filter((block) => block.tag === '@see')
@@ -100,7 +98,6 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
return {
// @ts-expect-error: Type cannot be inferred
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
name: signature.name === 'default' ? parse(meta?.file ?? 'default').name : signature.name,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
@@ -109,13 +106,11 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
implements: this.implements?.serialize(),
access:
data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private'
: undefined,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, @typescript-eslint/no-unnecessary-condition
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
abstract: signature.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags
.find((block) => block.tag === '@deprecated')

View File

@@ -9,7 +9,6 @@ export class DocumentedConstructor extends DocumentedItem<Constructor | Declarat
const data = this.data as DeclarationReflection;
const signature = (data.signatures ?? [])[0] ?? data;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags
.filter((block) => block.tag === '@see')
@@ -18,12 +17,11 @@ export class DocumentedConstructor extends DocumentedItem<Constructor | Declarat
return {
name: signature.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see,
access:
data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private'
: undefined,

View File

@@ -18,14 +18,12 @@ export class DocumentedEvent extends DocumentedItem<DeclarationReflection | Even
meta = new DocumentedItemMeta(sources, this.config).serialize();
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags
.filter((block) => block.tag === '@see')
.map((block) => block.content.find((contentText) => contentText.kind === 'text')?.text.trim())
: undefined;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const examples = signature.comment?.blockTags?.filter((block) => block.tag === '@example').length
? signature.comment.blockTags
.filter((block) => block.tag === '@example')
@@ -35,19 +33,16 @@ export class DocumentedEvent extends DocumentedItem<DeclarationReflection | Even
return {
// @ts-expect-error: No type for params
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
name: signature.parameters?.[0]?.type?.value,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see,
access:
data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private'
: undefined,
examples,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags
.find((block) => block.tag === '@deprecated')
@@ -68,7 +63,6 @@ export class DocumentedEvent extends DocumentedItem<DeclarationReflection | Even
names: [parseType(signature.type)],
description:
signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -81,7 +75,6 @@ export class DocumentedEvent extends DocumentedItem<DeclarationReflection | Even
: undefined,
returnsDescription:
signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -18,7 +18,6 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
meta = new DocumentedItemMeta(sources, this.config).serialize();
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags
.filter((block) => block.tag === '@see')
@@ -27,20 +26,18 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
const base = {
name: signature.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see,
scope: data.flags.isStatic ? 'static' : undefined,
access:
data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private'
: undefined,
readonly: data.flags.isReadonly,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
abstract: signature.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags
.find((block) => block.tag === '@deprecated')
@@ -51,7 +48,6 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
default:
(data.defaultValue === '...' ? undefined : data.defaultValue) ??
(signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -76,7 +72,6 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
base.readonly = true;
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = getter.comment?.blockTags?.filter((block) => block.tag === '@see').length
? getter.comment.blockTags
.filter((block) => block.tag === '@see')
@@ -85,19 +80,17 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
return {
...base,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: getter.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see,
access:
data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
getter.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private'
: undefined,
readonly: base.readonly || !hasSetter,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
abstract: getter.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: getter.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? getter.comment.blockTags
.find((block) => block.tag === '@deprecated')
@@ -108,7 +101,6 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
default:
base.default ??
(getter.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -18,14 +18,12 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
meta = new DocumentedItemMeta(sources, this.config).serialize();
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags
.filter((block) => block.tag === '@see')
.map((block) => block.content.find((innerContent) => innerContent.kind === 'text')?.text.trim())
: undefined;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const examples = signature.comment?.blockTags?.filter((block) => block.tag === '@example').length
? signature.comment.blockTags
.filter((block) => block.tag === '@example')
@@ -35,20 +33,18 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
return {
name: signature.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see,
scope: data.flags.isStatic ? 'static' : undefined,
access:
data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private'
: undefined,
examples,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
abstract: signature.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags
.find((block) => block.tag === '@deprecated')
@@ -56,7 +52,6 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
?.content.reduce((prev, curr) => (prev += curr.text), '')
.trim() ?? true
: undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
// emits: signature.comment?.blockTags?.filter((t) => t.tag === '@emits').map((t) => t.content),
// @ts-expect-error: Typescript doesn't know that this is a SignatureReflection
params: signature.parameters
@@ -71,7 +66,6 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
names: [parseType(signature.type)],
description:
signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -84,7 +78,6 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
: undefined,
returnsDescription:
signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -11,13 +11,12 @@ export class DocumentedParam extends DocumentedItem<Param | ParameterReflection>
return {
name: data.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: data.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
optional: data.flags.isOptional || typeof data.defaultValue !== 'undefined',
default:
(data.defaultValue === '...' ? undefined : data.defaultValue) ??
(data.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -19,7 +19,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
meta = new DocumentedItemMeta(sources, this.config).serialize();
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags
.filter((block) => block.tag === '@see')
@@ -28,16 +27,14 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
const baseReturn = {
name: signature.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see,
access:
data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private'
: undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags
.find((block) => block.tag === '@deprecated')
@@ -64,7 +61,7 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
name: child.name,
description:
child.comment?.summary
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, no-param-reassign
// eslint-disable-next-line no-param-reassign
?.reduce((prev, curr) => (prev += curr.text), '')
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
.trim() || undefined,
@@ -82,18 +79,17 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
name: child.name,
description:
child.comment?.summary
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, no-param-reassign
// eslint-disable-next-line no-param-reassign
?.reduce((prev, curr) => (prev += curr.text), '')
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
.trim() ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
child.signatures?.[0]?.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() ||
undefined,
optional: child.flags.isOptional || typeof child.defaultValue !== 'undefined',
default:
(child.defaultValue === '...' ? undefined : child.defaultValue) ??
(child.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -112,7 +108,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
}),
],
description: child.signatures?.[0]?.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -134,13 +129,12 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
const params = sig?.parameters?.map((param) => ({
name: param.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: param.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
optional: param.flags.isOptional || typeof param.defaultValue !== 'undefined',
default:
(param.defaultValue === '...' ? undefined : param.defaultValue) ??
(param.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -152,7 +146,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
: undefined,
}));
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = sig?.comment?.blockTags?.filter((block) => block.tag === '@see').length
? sig.comment.blockTags
.filter((block) => block.tag === '@see')
@@ -161,16 +154,14 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
return {
...baseReturn,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: sig?.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see,
access:
sig?.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
sig?.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private'
: undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: sig?.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? sig.comment.blockTags
.find((block) => block.tag === '@deprecated')
@@ -186,7 +177,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
names: [parseType(sig.type)],
description:
sig.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -199,7 +189,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
: undefined,
returnsDescription:
sig?.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -91,7 +91,6 @@ export function parseType(someType: JSONOutput.SomeType | JSONOutput.Type | stri
return `'${someType.value}'`;
}
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `${someType.value}`;
}

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import type { JSONOutput } from 'typedoc';
interface QueryType {

View File

@@ -9,7 +9,6 @@ if (!process.env.DISCORD_TOKEN) {
// We want to let upstream handle retrying
const api = new REST({ rejectOnRateLimit: () => true, retries: 0 }).setToken(process.env.DISCORD_TOKEN);
// eslint-disable-next-line @typescript-eslint/no-misused-promises
const server = createServer(proxyRequests(api));
const port = Number.parseInt(process.env.PORT ?? '8080', 10);

View File

@@ -16,7 +16,6 @@ const responseOptions: MockInterceptor.MockResponseOptions = {
};
const api = new REST().setToken('A-Very-Fake-Token');
// eslint-disable-next-line @typescript-eslint/no-misused-promises
const server = createServer(proxyRequests(api));
beforeEach(() => {

View File

@@ -58,7 +58,6 @@ const sublimit = { body: { name: 'newname' } };
const noSublimit = { body: { bitrate: 40_000 } };
function startSublimitIntervals() {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!sublimitIntervals.reset) {
sublimitResetAfter = Date.now() + 250;
sublimitIntervals.reset = setInterval(() => {
@@ -67,7 +66,6 @@ function startSublimitIntervals() {
}, 250);
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!sublimitIntervals.retry) {
retryAfter = Date.now() + 1_000;
sublimitIntervals.retry = setInterval(() => {

View File

@@ -62,7 +62,7 @@ test('resolveBody', async () => {
};
await expect(resolveBody(asyncIterable)).resolves.toStrictEqual(Buffer.from([1, 2, 3, 1, 2, 3, 1, 2, 3]));
// unknown type
// @ts-expect-error This test is ensuring that this throws
// Unknown type
// @ts-expect-error: This test is ensuring that this throws
await expect(resolveBody(true)).rejects.toThrow(TypeError);
});

View File

@@ -11,7 +11,7 @@ import {
type RequestData,
type RouteLike,
} from './RequestManager.js';
import type { IHandler } from './handlers/IHandler';
import type { IHandler } from './handlers/IHandler.js';
import { DefaultRestOptions, RESTEvents } from './utils/constants.js';
import { parseResponse } from './utils/utils.js';

View File

@@ -5,8 +5,8 @@ import type { URLSearchParams } from 'node:url';
import { Collection } from '@discordjs/collection';
import { DiscordSnowflake } from '@sapphire/snowflake';
import { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';
import type { RESTOptions, RestEvents, RequestOptions } from './REST';
import type { IHandler } from './handlers/IHandler';
import type { RESTOptions, RestEvents, RequestOptions } from './REST.js';
import type { IHandler } from './handlers/IHandler.js';
import { SequentialHandler } from './handlers/SequentialHandler.js';
import { DefaultRestOptions, DefaultUserAgent, RESTEvents } from './utils/constants.js';
import { resolveBody } from './utils/utils.js';
@@ -208,7 +208,6 @@ export class RequestManager extends EventEmitter {
*/
public readonly handlers = new Collection<string, IHandler>();
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#token: string | null = null;
private hashTimer!: NodeJS.Timer;
@@ -422,7 +421,6 @@ export class RequestManager extends EventEmitter {
const contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime;
formData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);
} else {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
formData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);
}
}
@@ -457,7 +455,6 @@ export class RequestManager extends EventEmitter {
finalBody = await resolveBody(finalBody);
const fetchOptions: RequestOptions = {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
headers: { ...request.headers, ...additionalHeaders, ...headers } as Record<string, string>,
method: request.method.toUpperCase() as Dispatcher.HttpMethod,
};

View File

@@ -101,13 +101,11 @@ export class DiscordAPIError extends Error {
if (typeof val === 'string') {
yield val;
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
} else if (isErrorGroupWrapper(val)) {
for (const error of val._errors) {
yield* this.flattenDiscordError(error, nextKey);
}
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
yield* this.flattenDiscordError(val, nextKey);
}
}

View File

@@ -10,7 +10,6 @@ export interface IHandler {
/**
* If the bucket is currently inactive (no pending requests)
*/
// eslint-disable-next-line @typescript-eslint/method-signature-style -- This is meant to be a getter returning a bool
get inactive(): boolean;
/**
* Queues a request to be sent

View File

@@ -53,25 +53,21 @@ export class SequentialHandler implements IHandler {
/**
* The interface used to sequence async requests sequentially
*/
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#asyncQueue = new AsyncQueue();
/**
* The interface used to sequence sublimited async requests sequentially
*/
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#sublimitedQueue: AsyncQueue | null = null;
/**
* A promise wrapper for when the sublimited queue is finished being processed or null when not being processed
*/
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#sublimitPromise: { promise: Promise<void>; resolve(): void } | null = null;
/**
* Whether the sublimit queue needs to be shifted in the finally block
*/
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#shiftSublimit = false;
/**

View File

@@ -2,10 +2,9 @@ import process from 'node:process';
import { APIVersion } from 'discord-api-types/v10';
import { getGlobalDispatcher } from 'undici';
import type { RESTOptions } from '../REST.js';
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
const Package = require('../../../package.json');
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-unsafe-member-access
export const DefaultUserAgent = `DiscordBot (${Package.homepage}, ${Package.version})`;
export const DefaultRestOptions: Required<RESTOptions> = {

View File

@@ -113,7 +113,6 @@ export async function resolveBody(body: RequestInit['body']): Promise<RequestOpt
return new Uint8Array(await body.arrayBuffer());
} else if (body instanceof FormData) {
return body;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
} else if ((body as Iterable<Uint8Array>)[Symbol.iterator]) {
const chunks = [...(body as Iterable<Uint8Array>)];
const length = chunks.reduce((a, b) => a + b.length, 0);
@@ -126,7 +125,6 @@ export async function resolveBody(body: RequestInit['body']): Promise<RequestOpt
lengthUsed += b.length;
return a;
}, uint8);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
} else if ((body as AsyncIterable<Uint8Array>)[Symbol.asyncIterator]) {
const chunks: Uint8Array[] = [];

View File

@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/dot-notation */
import { Buffer } from 'node:buffer';
import { once } from 'node:events';
@@ -8,7 +6,7 @@ import process from 'node:process';
import { Readable } from 'node:stream';
import { addAudioPlayer, deleteAudioPlayer } from '../src/DataStore';
import { VoiceConnection, VoiceConnectionStatus } from '../src/VoiceConnection';
import { createAudioPlayer, AudioPlayerStatus, SILENCE_FRAME, type AudioPlayerState } from '../src/audio/AudioPlayer';
import { createAudioPlayer, AudioPlayerStatus, SILENCE_FRAME } from '../src/audio/AudioPlayer';
import { AudioPlayerError } from '../src/audio/AudioPlayerError';
import { AudioResource } from '../src/audio/AudioResource';
import { NoSubscriberBehavior } from '../src/index';
@@ -23,7 +21,6 @@ const AudioPlayerErrorMock = AudioPlayerError as unknown as jest.Mock<typeof Aud
const VoiceConnectionMock = VoiceConnection as unknown as jest.Mock<VoiceConnection>;
function* silence() {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
while (true) {
yield Buffer.from([0xf8, 0xff, 0xfe]);
}

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
import { Buffer } from 'node:buffer';
import process from 'node:process';
import { PassThrough, Readable } from 'node:stream';
@@ -26,7 +25,7 @@ async function started(resource: AudioResource) {
const findPipeline = _findPipeline as unknown as jest.MockedFunction<typeof _findPipeline>;
beforeAll(() => {
// @ts-expect-error no type
// @ts-expect-error: No type
findPipeline.mockImplementation((from: StreamType, constraint: (path: Edge[]) => boolean) => {
const base = [
{
@@ -38,7 +37,6 @@ beforeAll(() => {
if (constraint === VOLUME_CONSTRAINT) {
base.push({
cost: 1,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
transformer: () => new VolumeTransformer({} as any),
type: TransformerType.InlineVolume,
});
@@ -98,7 +96,6 @@ describe('createAudioResource', () => {
});
test('Infers from VolumeTransformer', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const stream = new VolumeTransformer({} as any);
const resource = createAudioResource(stream, { inlineVolume: true });
expect(findPipeline).toHaveBeenCalledWith(StreamType.Raw, NO_CONSTRAINT);

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/dot-notation */
import { GatewayOpcodes } from 'discord-api-types/v10';
import * as DataStore from '../src/DataStore';

View File

@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import type EventEmitter from 'node:events';
import { once } from 'node:events';
import { type EventEmitter, once } from 'node:events';
import process from 'node:process';
import { SSRCMap, type VoiceUserData } from '../src/receive/SSRCMap';

View File

@@ -1,10 +1,6 @@
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable @typescript-eslint/dot-notation */
import EventEmitter from 'node:events';
import { EventEmitter } from 'node:events';
import * as _DataStore from '../src/DataStore';
import {
createVoiceConnection,

View File

@@ -1,5 +1,4 @@
/* eslint-disable id-length */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/dot-notation */
import { Buffer } from 'node:buffer';
import { once } from 'node:events';
@@ -39,7 +38,6 @@ describe('VoiceReceiver', () => {
let receiver: VoiceReceiver;
beforeEach(() => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
voiceConnection = new VoiceConnection({} as any, {} as any);
voiceConnection.state = {
status: VoiceConnectionStatus.Signalling,

View File

@@ -1,9 +1,6 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Buffer } from 'node:buffer';
import { createSocket as _createSocket } from 'node:dgram';
import EventEmitter, { once } from 'node:events';
import { EventEmitter } from 'node:events';
import { VoiceUDPSocket } from '../src/networking/VoiceUDPSocket';
jest.mock('node:dgram');

View File

@@ -1,5 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { type EventEmitter, once } from 'node:events';
import { VoiceOpcodes } from 'discord-api-types/voice/v4';
import WS from 'jest-websocket-mock';
@@ -115,7 +113,6 @@ describe.skip('VoiceWebSocket: heartbeating', () => {
const endpoint = 'ws://localhost:1234';
const server = new WS(endpoint, { jsonProtocol: true });
const ws = new VoiceWebSocket(endpoint, false);
// eslint-disable-next-line @typescript-eslint/no-empty-function
ws.on('error', () => {});
await server.connected;
const rcv = onceIgnoreError(ws, 'close');

View File

@@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { Buffer } from 'node:buffer';
import EventEmitter, { once } from 'node:events';
import process from 'node:process';
@@ -27,8 +24,7 @@ async function* gen(num: number) {
}
function range(num: number) {
// eslint-disable-next-line unicorn/no-new-array
return Buffer.from(Array.from(new Array(num).keys()));
return Buffer.from(Array.from(Array.from({ length: num }).keys()));
}
const validHead = Buffer.from([
@@ -80,7 +76,6 @@ describe('demuxProbe', () => {
test('Detects WebM', async () => {
const stream = Readable.from(gen(10), { objectMode: false });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
webmWrite.mockImplementation(function mock(data: Buffer) {
if (data[0] === 5) this.emit('head', validHead);
} as any);
@@ -91,7 +86,6 @@ describe('demuxProbe', () => {
test('Detects Ogg', async () => {
const stream = Readable.from(gen(10), { objectMode: false });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
oggWrite.mockImplementation(function mock(data: Buffer) {
if (data[0] === 5) this.emit('head', validHead);
} as any);
@@ -102,7 +96,6 @@ describe('demuxProbe', () => {
test('Rejects invalid OpusHead', async () => {
const stream = Readable.from(gen(10), { objectMode: false });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
oggWrite.mockImplementation(function mock(data: Buffer) {
if (data[0] === 5) this.emit('head', invalidHead);
} as any);

View File

@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import EventEmitter from 'node:events';
import { EventEmitter } from 'node:events';
import process from 'node:process';
import { VoiceConnectionStatus, type VoiceConnection } from '../src/VoiceConnection';
import { entersState } from '../src/util/entersState';
@@ -19,7 +17,6 @@ describe('entersState', () => {
test('Returns the target once the state has been entered before timeout', async () => {
jest.useRealTimers();
const vc = createFakeVoiceConnection();
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
process.nextTick(() => vc.emit(VoiceConnectionStatus.Ready, null as any, null as any));
const result = await entersState(vc, VoiceConnectionStatus.Ready, 1_000);
expect(result).toEqual(vc);
@@ -36,7 +33,6 @@ describe('entersState', () => {
jest.useRealTimers();
const vc = createFakeVoiceConnection();
const ac = new AbortController();
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
process.nextTick(() => vc.emit(VoiceConnectionStatus.Ready, null as any, null as any));
const result = await entersState(vc, VoiceConnectionStatus.Ready, ac.signal);
expect(result).toEqual(vc);

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
import * as VoiceConnection from '../src/VoiceConnection';
import { joinVoiceChannel } from '../src/joinVoiceChannel';

View File

@@ -4,7 +4,6 @@ import Discord, { Interaction, Constants } from 'discord.js';
import { deploy } from './deploy';
import { interactionHandlers } from './interactions';
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
const { token } = require('../auth.json') as { token: string };
const client = new Discord.Client({

View File

@@ -1,6 +1,6 @@
import { GatewayOpcodes } from 'discord-api-types/v10';
import type { VoiceConnection } from './VoiceConnection';
import type { AudioPlayer } from './audio';
import type { AudioPlayer } from './audio/index';
export interface JoinConfig {
channelId: string | null;

View File

@@ -325,7 +325,6 @@ export class VoiceConnection extends EventEmitter {
this.emit('stateChange', oldState, newState);
if (oldState.status !== newState.status) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.emit(newState.status, oldState, newState as any);
}
}
@@ -391,7 +390,6 @@ export class VoiceConnection extends EventEmitter {
newUdp?.on('message', this.receiver.onUdpMessage);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.receiver.connectionData = Reflect.get(newState, 'connectionData') ?? {};
}

View File

@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/prefer-ts-expect-error, @typescript-eslint/method-signature-style */
import { Buffer } from 'node:buffer';
import EventEmitter from 'node:events';
import { EventEmitter } from 'node:events';
import { addAudioPlayer, deleteAudioPlayer } from '../DataStore';
import { VoiceConnectionStatus, type VoiceConnection } from '../VoiceConnection';
import { noop } from '../util/util';
@@ -356,7 +356,6 @@ export class AudioPlayer extends EventEmitter {
this.emit('stateChange', oldState, this._state);
if (oldState.status !== newState.status || didChangeResources) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.emit(newState.status, oldState, this._state as any);
}
@@ -600,7 +599,6 @@ export class AudioPlayer extends EventEmitter {
*/
const packet: Buffer | null = state.resource.read();
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (state.status === AudioPlayerStatus.Playing) {
if (packet) {
this._preparePacket(packet, playable, state);

View File

@@ -387,22 +387,16 @@ export class Networking extends EventEmitter {
* @param packet - The received packet
*/
private onWsPacket(packet: any) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (packet.op === VoiceOpcodes.Hello && this.state.code !== NetworkingStatusCode.Closed) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
this.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} else if (packet.op === VoiceOpcodes.Ready && this.state.code === NetworkingStatusCode.Identifying) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
const { ip, port, ssrc, modes } = packet.d;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const udp = new VoiceUDPSocket({ ip, port });
udp.on('error', this.onChildError);
udp.on('debug', this.onUdpDebug);
udp.once('close', this.onUdpClose);
udp
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
.performIPDiscovery(ssrc)
// eslint-disable-next-line promise/prefer-await-to-then
.then((localConfig) => {
@@ -414,7 +408,6 @@ export class Networking extends EventEmitter {
data: {
address: localConfig.ip,
port: localConfig.port,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
mode: chooseEncryptionMode(modes),
},
},
@@ -432,25 +425,20 @@ export class Networking extends EventEmitter {
code: NetworkingStatusCode.UdpHandshaking,
udp,
connectionData: {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
ssrc,
},
};
} else if (
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
packet.op === VoiceOpcodes.SessionDescription &&
this.state.code === NetworkingStatusCode.SelectingProtocol
) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
const { mode: encryptionMode, secret_key: secretKey } = packet.d;
this.state = {
...this.state,
code: NetworkingStatusCode.Ready,
connectionData: {
...this.state.connectionData,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
encryptionMode,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
secretKey: new Uint8Array(secretKey),
sequence: randomNBit(16),
timestamp: randomNBit(32),
@@ -460,7 +448,6 @@ export class Networking extends EventEmitter {
packetsPlayed: 0,
},
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} else if (packet.op === VoiceOpcodes.Resumed && this.state.code === NetworkingStatusCode.Resuming) {
this.state = {
...this.state,

View File

@@ -73,7 +73,6 @@ export class VoiceWebSocket extends EventEmitter {
this.ws = new WebSocket(address);
this.ws.onmessage = (err) => this.onMessage(err);
this.ws.onopen = (err) => this.emit('open', err);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.ws.onerror = (err: Error | WebSocket.ErrorEvent) => this.emit('error', err instanceof Error ? err : err.error);
this.ws.onclose = (err) => this.emit('close', err);
@@ -110,7 +109,6 @@ export class VoiceWebSocket extends EventEmitter {
let packet: any;
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
packet = JSON.parse(event.data);
} catch (error) {
const err = error as Error;
@@ -118,7 +116,6 @@ export class VoiceWebSocket extends EventEmitter {
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (packet.op === VoiceOpcodes.HeartbeatAck) {
this.lastHeartbeatAck = Date.now();
this.missedHeartbeats = 0;

View File

@@ -85,6 +85,5 @@ export class AudioReceiveStream extends Readable {
this.endTimeout = setTimeout(() => this.push(null), end.duration);
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
public override _read() {}
}

View File

@@ -64,34 +64,22 @@ export class VoiceReceiver {
* @internal
*/
public onWsPacket(packet: any) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (packet.op === VoiceOpcodes.ClientDisconnect && typeof packet.d?.user_id === 'string') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
this.ssrcMap.delete(packet.d.user_id);
} else if (
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
packet.op === VoiceOpcodes.Speaking &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
typeof packet.d?.user_id === 'string' &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
typeof packet.d?.ssrc === 'number'
) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
this.ssrcMap.update({ userId: packet.d.user_id, audioSSRC: packet.d.ssrc });
} else if (
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
packet.op === VoiceOpcodes.ClientConnect &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
typeof packet.d?.user_id === 'string' &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
typeof packet.d?.audio_ssrc === 'number'
) {
this.ssrcMap.update({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
userId: packet.d.user_id,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
audioSSRC: packet.d.audio_ssrc,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
videoSSRC: packet.d.video_ssrc === 0 ? undefined : packet.d.video_ssrc,
});
}

View File

@@ -9,56 +9,40 @@ interface Methods {
const libs = {
'sodium-native': (sodium: any): Methods => ({
open: (buffer: Buffer, nonce: Buffer, secretKey: Uint8Array) => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (buffer) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const output = Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
if (sodium.crypto_secretbox_open_easy(output, buffer, nonce, secretKey)) return output;
}
return null;
},
close: (opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument, @typescript-eslint/restrict-plus-operands
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
const output = Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
sodium.crypto_secretbox_easy(output, opusPacket, nonce, secretKey);
return output;
},
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
random: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
sodium.randombytes_buf(buffer);
return buffer;
},
}),
sodium: (sodium: any): Methods => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
open: sodium.api.crypto_secretbox_open_easy,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
close: sodium.api.crypto_secretbox_easy,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
random: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
sodium.api.randombytes_buf(buffer);
return buffer;
},
}),
'libsodium-wrappers': (sodium: any): Methods => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
open: sodium.crypto_secretbox_open_easy,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
close: sodium.crypto_secretbox_easy,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
random: sodium.randombytes_buf,
}),
tweetnacl: (tweetnacl: any): Methods => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
open: tweetnacl.secretbox.open,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
close: tweetnacl.secretbox,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
random: tweetnacl.randomBytes,
}),
} as const;
@@ -82,7 +66,6 @@ void (async () => {
try {
// eslint-disable-next-line unicorn/no-abusive-eslint-disable, @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
const lib = require(libName);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (libName === 'libsodium-wrappers' && lib.ready) await lib.ready;
Object.assign(methods, libs[libName](lib));
break;

View File

@@ -7,7 +7,6 @@ export function abortAfter(delay: number): [AbortController, AbortSignal] {
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), delay);
// @ts-expect-error: No type for timeout
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
ac.signal.addEventListener('abort', () => clearTimeout(timeout));
return [ac, ac.signal];
}

View File

@@ -18,11 +18,8 @@ function findPackageJSON(
if (depth === 0) return undefined;
const attemptedPath = resolve(dir, './package.json');
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pkg = require(attemptedPath);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (pkg.name !== packageName) throw new Error('package.json does not match');
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return pkg;
} catch {
return findPackageJSON(resolve(dir, '..'), packageName, depth - 1);
@@ -36,12 +33,10 @@ function findPackageJSON(
*/
function version(name: string): string {
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pkg =
name === '@discordjs/voice'
? require('../../package.json')
: findPackageJSON(dirname(require.resolve(name)), name, 3);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access
return pkg?.version ?? 'not found';
} catch {
return 'not found';

View File

@@ -1,2 +1 @@
// eslint-disable-next-line @typescript-eslint/no-empty-function
export const noop = () => {};

View File

@@ -67,7 +67,6 @@ function resolveIcon(item: keyof GroupedMembers) {
}
const useStyles = createStyles((theme) => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
link: {
...theme.fn.focusStyles(),
fontWeight: 500,

View File

@@ -4,7 +4,6 @@ import { useMemo } from 'react';
import { VscListSelection, VscSymbolMethod, VscSymbolProperty } from 'react-icons/vsc';
const useStyles = createStyles((theme) => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
link: {
...theme.fn.focusStyles(),
fontWeight: 500,

View File

@@ -47,16 +47,13 @@ export const getStaticPaths: GetStaticPaths = async () => {
let versions: string[] = [];
if (process.env.NEXT_PUBLIC_LOCAL_DEV) {
const res = await readFile(join(cwd(), '..', packageName, 'docs', 'docs.api.json'), 'utf8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
data = JSON.parse(res);
} else {
const response = await fetch(`https://docs.discordjs.dev/api/info?package=${packageName}`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
versions = await response.json();
for (const version of versions) {
const res = await fetch(`https://docs.discordjs.dev/docs/${packageName}/${version}.api.json`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
data = [...data, await res.json()];
}
}
@@ -142,11 +139,9 @@ export const getStaticProps: GetStaticProps = async ({ params }) => {
let data;
if (process.env.NEXT_PUBLIC_LOCAL_DEV) {
const res = await readFile(join(cwd(), '..', packageName, 'docs', 'docs.api.json'), 'utf8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
data = JSON.parse(res);
} else {
const res = await fetch(`https://docs.discordjs.dev/docs/${packageName}/${branchName}.api.json`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
data = await res.json();
}

View File

@@ -38,7 +38,6 @@ export const getStaticProps: GetStaticProps = async ({ params }) => {
try {
const res = await fetch(`https://docs.discordjs.dev/api/info?package=${packageName ?? 'builders'}`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const data: string[] = await res.json();
if (!data.length) {

View File

@@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { ApiModel, ApiItem, type ApiPackage } from '@microsoft/api-extractor-model';
import { TSDocConfiguration } from '@microsoft/tsdoc';
import { TSDocConfigFile } from '@microsoft/tsdoc-config';
@@ -11,7 +8,6 @@ export function createApiModel(data: any) {
const tsdocConfigFile = TSDocConfigFile.loadFromObject(data.metadata.tsdocConfig);
tsdocConfigFile.configureParser(tsdocConfiguration);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const apiPackage = ApiItem.deserialize(data, {
apiJsonFilename: '',
toolPackage: data.metadata.toolPackage,

View File

@@ -50,14 +50,12 @@ vi.mock('node:worker_threads', async () => {
class MockWorker extends EventEmitter {
public constructor(...args: any[]) {
super();
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
mockConstructor(...args);
// need to delay this by an event loop cycle to allow the strategy to attach a listener
setImmediate(() => this.emit('online'));
}
public postMessage(message: WorkerSendPayload) {
// eslint-disable-next-line default-case
switch (message.op) {
case WorkerSendPayloadOp.Connect: {
const response: WorkerRecievePayload = {
@@ -180,7 +178,6 @@ test('spawn, connect, send a message, session info, and destroy', async () => {
await manager.connect();
expect(mockConstructor).toHaveBeenCalledWith(
expect.stringContaining('worker.cjs'),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
expect.objectContaining({ workerData: expect.objectContaining({ shardIds: [0, 1] }) }),
);

View File

@@ -1,3 +1,4 @@
/* eslint-disable unicorn/require-post-message-target-origin */
import { isMainThread, parentPort } from 'node:worker_threads';
import { Collection } from '@discordjs/collection';
import type { SessionInfo } from '../../ws/WebSocketManager.js';
@@ -35,7 +36,6 @@ export class WorkerContextFetchingStrategy implements IContextFetchingStrategy {
};
// eslint-disable-next-line no-promise-executor-return
const promise = new Promise<SessionInfo | null>((resolve) => this.sessionPromises.set(nonce, resolve));
// eslint-disable-next-line unicorn/require-post-message-target-origin
parentPort!.postMessage(payload);
return promise;
}
@@ -46,7 +46,6 @@ export class WorkerContextFetchingStrategy implements IContextFetchingStrategy {
shardId,
session: sessionInfo,
};
// eslint-disable-next-line unicorn/require-post-message-target-origin
parentPort!.postMessage(payload);
}
}

View File

@@ -1,3 +1,4 @@
/* eslint-disable unicorn/require-post-message-target-origin */
import { once } from 'node:events';
import { join } from 'node:path';
import { Worker } from 'node:worker_threads';
@@ -100,7 +101,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
.on('messageerror', (err) => {
throw err;
})
// eslint-disable-next-line @typescript-eslint/no-misused-promises
.on('message', async (payload: WorkerRecievePayload) => this.onMessage(worker, payload));
this.#workers.push(worker);
@@ -128,7 +128,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
// eslint-disable-next-line no-promise-executor-return
const promise = new Promise<void>((resolve) => this.connectPromises.set(shardId, resolve));
// eslint-disable-next-line unicorn/require-post-message-target-origin
worker.postMessage(payload);
promises.push(promise);
}
@@ -153,7 +152,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
// eslint-disable-next-line no-promise-executor-return, promise/prefer-await-to-then
new Promise<void>((resolve) => this.destroyPromises.set(shardId, resolve)).then(async () => worker.terminate()),
);
// eslint-disable-next-line unicorn/require-post-message-target-origin
worker.postMessage(payload);
}
@@ -177,12 +175,10 @@ export class WorkerShardingStrategy implements IShardingStrategy {
shardId,
payload: data,
};
// eslint-disable-next-line unicorn/require-post-message-target-origin
worker.postMessage(payload);
}
private async onMessage(worker: Worker, payload: WorkerRecievePayload) {
// eslint-disable-next-line default-case
switch (payload.op) {
case WorkerRecievePayloadOp.Connected: {
const resolve = this.connectPromises.get(payload.shardId)!;
@@ -199,7 +195,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
}
case WorkerRecievePayloadOp.Event: {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.manager.emit(payload.event, { ...payload.data, shardId: payload.shardId });
break;
}
@@ -211,7 +206,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
nonce: payload.nonce,
session,
};
// eslint-disable-next-line unicorn/require-post-message-target-origin
worker.postMessage(response);
break;
}

View File

@@ -58,9 +58,7 @@ parentPort!
.on('messageerror', (err) => {
throw err;
})
// eslint-disable-next-line @typescript-eslint/no-misused-promises
.on('message', async (payload: WorkerSendPayload) => {
// eslint-disable-next-line default-case
switch (payload.op) {
case WorkerSendPayloadOp.Connect: {
await connect(payload.shardId);

View File

@@ -21,10 +21,8 @@ export enum CompressionMethod {
}
const packageJson = readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const Package = JSON.parse(packageJson);
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-unsafe-member-access
export const DefaultDeviceProperty = `@discordjs/ws ${Package.version}`;
const getDefaultSessionStore = lazy(() => new Collection<number, SessionInfo | null>());

View File

@@ -384,7 +384,6 @@ export class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
return;
}
// eslint-disable-next-line default-case
switch (payload.op) {
case GatewayOpcodes.Dispatch: {
if (this.status === WebSocketShardStatus.Ready || this.status === WebSocketShardStatus.Resuming) {