refactor: use eslint-config-neon for packages. (#8579)

Co-authored-by: Noel <buechler.noel@outlook.com>
This commit is contained in:
Suneet Tipirneni
2022-09-01 14:50:16 -04:00
committed by GitHub
parent 4bdb0593ae
commit edadb9fe5d
219 changed files with 2608 additions and 2053 deletions

View File

@@ -1,11 +1,11 @@
import { test, expect } from 'vitest';
import { CDN } from '../src';
import { CDN } from '../src/index.js';
const base = 'https://discord.com';
const id = '123456';
const hash = 'abcdef';
const animatedHash = 'a_bcdef';
const defaultAvatar = 1234 % 5;
const defaultAvatar = 1_234 % 5;
const cdn = new CDN(base);

View File

@@ -1,5 +1,6 @@
import { URLSearchParams } from 'node:url';
import { test, expect } from 'vitest';
import { DiscordAPIError } from '../src';
import { DiscordAPIError } from '../src/index.js';
test('Unauthorized', () => {
const error = new DiscordAPIError(
@@ -27,13 +28,13 @@ test('Unauthorized', () => {
test('Invalid Form Body Error (error.{property}._errors.{index})', () => {
const error = new DiscordAPIError(
{
code: 50035,
code: 50_035,
errors: {
username: { _errors: [{ code: 'BASE_TYPE_BAD_LENGTH', message: 'Must be between 2 and 32 in length.' }] },
},
message: 'Invalid Form Body',
},
50035,
50_035,
400,
'PATCH',
'https://discord.com/api/v10/users/@me',
@@ -45,7 +46,7 @@ test('Invalid Form Body Error (error.{property}._errors.{index})', () => {
},
);
expect(error.code).toEqual(50035);
expect(error.code).toEqual(50_035);
expect(error.message).toEqual(
['Invalid Form Body', 'username[BASE_TYPE_BAD_LENGTH]: Must be between 2 and 32 in length.'].join('\n'),
);
@@ -60,7 +61,7 @@ test('Invalid Form Body Error (error.{property}._errors.{index})', () => {
test('Invalid FormFields Error (error.errors.{property}.{property}.{index}.{property}._errors.{index})', () => {
const error = new DiscordAPIError(
{
code: 50035,
code: 50_035,
errors: {
embed: {
fields: { '0': { value: { _errors: [{ code: 'BASE_TYPE_REQUIRED', message: 'This field is required' }] } } },
@@ -68,14 +69,14 @@ test('Invalid FormFields Error (error.errors.{property}.{property}.{index}.{prop
},
message: 'Invalid Form Body',
},
50035,
50_035,
400,
'POST',
'https://discord.com/api/v10/channels/:id',
{},
);
expect(error.code).toEqual(50035);
expect(error.code).toEqual(50_035);
expect(error.message).toEqual(
['Invalid Form Body', 'embed.fields[0].value[BASE_TYPE_REQUIRED]: This field is required'].join('\n'),
);
@@ -88,7 +89,7 @@ test('Invalid FormFields Error (error.errors.{property}.{property}.{index}.{prop
test('Invalid FormFields Error (error.errors.{property}.{property}._errors.{index}._errors)', () => {
const error = new DiscordAPIError(
{
code: 50035,
code: 50_035,
errors: {
form_fields: {
label: { _errors: [{ _errors: [{ code: 'BASE_TYPE_REQUIRED', message: 'This field is required' }] }] },
@@ -96,14 +97,14 @@ test('Invalid FormFields Error (error.errors.{property}.{property}._errors.{inde
},
message: 'Invalid Form Body',
},
50035,
50_035,
400,
'PATCH',
'https://discord.com/api/v10/guilds/:id',
{},
);
expect(error.code).toEqual(50035);
expect(error.code).toEqual(50_035);
expect(error.message).toEqual(
['Invalid Form Body', 'form_fields.label[0][BASE_TYPE_REQUIRED]: This field is required'].join('\n'),
);

View File

@@ -1,10 +1,14 @@
import { Buffer } from 'node:buffer';
import { URLSearchParams } from 'node:url';
import { DiscordSnowflake } from '@sapphire/snowflake';
import { Routes, Snowflake } from 'discord-api-types/v10';
import { File, FormData, MockAgent, setGlobalDispatcher } from 'undici';
import type { Snowflake } from 'discord-api-types/v10';
import { Routes } from 'discord-api-types/v10';
import type { FormData } from 'undici';
import { File, MockAgent, setGlobalDispatcher } from 'undici';
import type { Interceptable, MockInterceptor } from 'undici/types/mock-interceptor';
import { beforeEach, afterEach, test, expect } from 'vitest';
import { genPath } from './util';
import { REST } from '../src';
import { REST } from '../src/index.js';
import { genPath } from './util.js';
const newSnowflake: Snowflake = DiscordSnowflake.generate().toString();
@@ -142,7 +146,7 @@ test('getQuery', async () => {
expect(
await api.get('/getQuery', {
query: query,
query,
}),
).toStrictEqual({ test: true });
});
@@ -153,8 +157,8 @@ test('getAuth', async () => {
path: genPath('/getAuth'),
method: 'GET',
})
.reply((t) => ({
data: { auth: (t.headers as unknown as Record<string, string | undefined>)['Authorization'] ?? null },
.reply((from) => ({
data: { auth: (from.headers as unknown as Record<string, string | undefined>).Authorization ?? null },
statusCode: 200,
responseOptions,
}))
@@ -184,8 +188,8 @@ test('getReason', async () => {
path: genPath('/getReason'),
method: 'GET',
})
.reply((t) => ({
data: { reason: (t.headers as unknown as Record<string, string | undefined>)['X-Audit-Log-Reason'] ?? null },
.reply((from) => ({
data: { reason: (from.headers as unknown as Record<string, string | undefined>)['X-Audit-Log-Reason'] ?? null },
statusCode: 200,
responseOptions,
}))
@@ -215,8 +219,8 @@ test('urlEncoded', async () => {
path: genPath('/urlEncoded'),
method: 'POST',
})
.reply((t) => ({
data: t.body!,
.reply((from) => ({
data: from.body!,
statusCode: 200,
}));
@@ -245,8 +249,8 @@ test('postEcho', async () => {
path: genPath('/postEcho'),
method: 'POST',
})
.reply((t) => ({
data: t.body!,
.reply((from) => ({
data: from.body!,
statusCode: 200,
responseOptions,
}));
@@ -260,8 +264,8 @@ test('201 status code', async () => {
path: genPath('/postNon200StatusCode'),
method: 'POST',
})
.reply((t) => ({
data: t.body!,
.reply((from) => ({
data: from.body!,
statusCode: 201,
responseOptions,
}));

View File

@@ -1,15 +1,18 @@
/* eslint-disable id-length */
/* eslint-disable promise/prefer-await-to-then */
import { performance } from 'node:perf_hooks';
import { setInterval, clearInterval } from 'node:timers';
import { MockAgent, setGlobalDispatcher } from 'undici';
import type { Interceptable, MockInterceptor } from 'undici/types/mock-interceptor';
import { beforeEach, afterEach, test, expect, vitest } from 'vitest';
import { genPath } from './util';
import { DiscordAPIError, HTTPError, RateLimitError, REST, RESTEvents } from '../src';
import { DiscordAPIError, HTTPError, RateLimitError, REST, RESTEvents } from '../src/index.js';
import { genPath } from './util.js';
let mockAgent: MockAgent;
let mockPool: Interceptable;
const api = new REST({ timeout: 2000, offset: 5 }).setToken('A-Very-Fake-Token');
const invalidAuthApi = new REST({ timeout: 2000 }).setToken('Definitely-Not-A-Fake-Token');
const api = new REST({ timeout: 2_000, offset: 5 }).setToken('A-Very-Fake-Token');
const invalidAuthApi = new REST({ timeout: 2_000 }).setToken('Definitely-Not-A-Fake-Token');
const rateLimitErrorApi = new REST({ rejectOnRateLimit: ['/channels'] }).setToken('Obviously-Not-A-Fake-Token');
beforeEach(() => {
@@ -52,7 +55,7 @@ const sublimitIntervals: {
};
const sublimit = { body: { name: 'newname' } };
const noSublimit = { body: { bitrate: 40000 } };
const noSublimit = { body: { bitrate: 40_000 } };
function startSublimitIntervals() {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
@@ -63,13 +66,14 @@ function startSublimitIntervals() {
sublimitResetAfter = Date.now() + 250;
}, 250);
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!sublimitIntervals.retry) {
retryAfter = Date.now() + 1000;
retryAfter = Date.now() + 1_000;
sublimitIntervals.retry = setInterval(() => {
sublimitHits = 0;
retryAfter = Date.now() + 1000;
}, 1000);
retryAfter = Date.now() + 1_000;
}, 1_000);
}
}
@@ -80,7 +84,7 @@ test('Significant Invalid Requests', async () => {
path: genPath('/badRequest'),
method: 'GET',
})
.reply(403, { message: 'Missing Permissions', code: 50013 }, responseOptions)
.reply(403, { message: 'Missing Permissions', code: 50_013 }, responseOptions)
.times(10);
const invalidListener = vitest.fn();
@@ -89,6 +93,7 @@ test('Significant Invalid Requests', async () => {
// Ensure listeners on REST do not get double added
api.on(RESTEvents.InvalidRequestWarning, invalidListener2);
api.off(RESTEvents.InvalidRequestWarning, invalidListener2);
const [a, b, c, d, e] = [
api.get('/badRequest'),
api.get('/badRequest'),
@@ -102,7 +107,9 @@ test('Significant Invalid Requests', async () => {
await expect(d).rejects.toThrowError('Missing Permissions');
await expect(e).rejects.toThrowError('Missing Permissions');
expect(invalidListener).toHaveBeenCalledTimes(0);
// eslint-disable-next-line require-atomic-updates
api.requestManager.options.invalidRequestWarningInterval = 2;
const [f, g, h, i, j] = [
api.get('/badRequest'),
api.get('/badRequest'),
@@ -137,7 +144,7 @@ test('Handle standard rate limits', async () => {
headers: {
'x-ratelimit-limit': '1',
'x-ratelimit-remaining': '0',
'x-ratelimit-reset-after': ((resetAfter - Date.now()) / 1000).toString(),
'x-ratelimit-reset-after': ((resetAfter - Date.now()) / 1_000).toString(),
'x-ratelimit-bucket': '80c17d2f203122d936070c88c8d10f33',
via: '1.1 google',
},
@@ -150,7 +157,7 @@ test('Handle standard rate limits', async () => {
data: {
limit: '1',
remaining: '0',
resetAfter: (resetAfter / 1000).toString(),
resetAfter: (resetAfter / 1_000).toString(),
bucket: '80c17d2f203122d936070c88c8d10f33',
retryAfter: (resetAfter - Date.now()).toString(),
},
@@ -158,7 +165,7 @@ test('Handle standard rate limits', async () => {
headers: {
'x-ratelimit-limit': '1',
'x-ratelimit-remaining': '0',
'x-ratelimit-reset-after': ((resetAfter - Date.now()) / 1000).toString(),
'x-ratelimit-reset-after': ((resetAfter - Date.now()) / 1_000).toString(),
'x-ratelimit-bucket': '80c17d2f203122d936070c88c8d10f33',
'retry-after': (resetAfter - Date.now()).toString(),
via: '1.1 google',
@@ -187,8 +194,8 @@ test('Handle sublimits', async () => {
path: genPath('/channels/:id'),
method: 'PATCH',
})
.reply((t) => {
const body = JSON.parse(t.body as string) as Record<string, unknown>;
.reply((from) => {
const body = JSON.parse(from.body as string) as Record<string, unknown>;
if ('name' in body || 'topic' in body) {
sublimitHits += 1;
@@ -204,7 +211,7 @@ test('Handle sublimits', async () => {
headers: {
'x-ratelimit-limit': '10',
'x-ratelimit-remaining': `${10 - sublimitRequests}`,
'x-ratelimit-reset-after': ((sublimitResetAfter - Date.now()) / 1000).toString(),
'x-ratelimit-reset-after': ((sublimitResetAfter - Date.now()) / 1_000).toString(),
via: '1.1 google',
},
},
@@ -216,15 +223,15 @@ test('Handle sublimits', async () => {
data: {
limit: '10',
remaining: `${10 - sublimitRequests}`,
resetAfter: (sublimitResetAfter / 1000).toString(),
retryAfter: ((retryAfter - Date.now()) / 1000).toString(),
resetAfter: (sublimitResetAfter / 1_000).toString(),
retryAfter: ((retryAfter - Date.now()) / 1_000).toString(),
},
responseOptions: {
headers: {
'x-ratelimit-limit': '10',
'x-ratelimit-remaining': `${10 - sublimitRequests}`,
'x-ratelimit-reset-after': ((sublimitResetAfter - Date.now()) / 1000).toString(),
'retry-after': ((retryAfter - Date.now()) / 1000).toString(),
'x-ratelimit-reset-after': ((sublimitResetAfter - Date.now()) / 1_000).toString(),
'retry-after': ((retryAfter - Date.now()) / 1_000).toString(),
via: '1.1 google',
...responseOptions.headers,
},
@@ -243,7 +250,7 @@ test('Handle sublimits', async () => {
headers: {
'x-ratelimit-limit': '10',
'x-ratelimit-remaining': `${10 - sublimitRequests}`,
'x-ratelimit-reset-after': ((sublimitResetAfter - Date.now()) / 1000).toString(),
'x-ratelimit-reset-after': ((sublimitResetAfter - Date.now()) / 1_000).toString(),
via: '1.1 google',
},
},
@@ -255,15 +262,15 @@ test('Handle sublimits', async () => {
data: {
limit: '10',
remaining: `${10 - sublimitRequests}`,
resetAfter: (sublimitResetAfter / 1000).toString(),
retryAfter: ((sublimitResetAfter - Date.now()) / 1000).toString(),
resetAfter: (sublimitResetAfter / 1_000).toString(),
retryAfter: ((sublimitResetAfter - Date.now()) / 1_000).toString(),
},
responseOptions: {
headers: {
'x-ratelimit-limit': '10',
'x-ratelimit-remaining': `${10 - sublimitRequests}`,
'x-ratelimit-reset-after': ((sublimitResetAfter - Date.now()) / 1000).toString(),
'retry-after': ((sublimitResetAfter - Date.now()) / 1000).toString(),
'x-ratelimit-reset-after': ((sublimitResetAfter - Date.now()) / 1_000).toString(),
'retry-after': ((sublimitResetAfter - Date.now()) / 1_000).toString(),
via: '1.1 google',
...responseOptions.headers,
},
@@ -294,6 +301,7 @@ test('Handle sublimits', async () => {
api.patch('/channels/:id', sublimit).then(() => Date.now()),
api.patch('/channels/:id', noSublimit).then(() => Date.now()),
]); // For additional sublimited checks
const e = await eP;
expect(a).toBeLessThanOrEqual(b);
@@ -314,6 +322,7 @@ test('Handle sublimits', async () => {
rateLimitErrorApi.patch('/channels/:id', sublimit),
rateLimitErrorApi.patch('/channels/:id', sublimit),
];
// eslint-disable-next-line @typescript-eslint/await-thenable
await expect(aP2).resolves;
await expect(bP2).rejects.toThrowError();
await expect(bP2).rejects.toBeInstanceOf(RateLimitError);
@@ -364,8 +373,8 @@ test('Handle unexpected 429', async () => {
expect(await unexepectedSublimit).toStrictEqual({ test: true });
expect(await queuedSublimit).toStrictEqual({ test: true });
expect(performance.now()).toBeGreaterThanOrEqual(previous + 1000);
// @ts-expect-error
expect(performance.now()).toBeGreaterThanOrEqual(previous + 1_000);
// @ts-expect-error: This is intentional
expect(secondResolvedTime).toBeGreaterThan(firstResolvedTime);
});
@@ -400,7 +409,7 @@ test('Handle unexpected 429 cloudflare', async () => {
const previous = Date.now();
expect(await api.get('/unexpected-cf')).toStrictEqual({ test: true });
expect(Date.now()).toBeGreaterThanOrEqual(previous + 1000);
expect(Date.now()).toBeGreaterThanOrEqual(previous + 1_000);
});
test('Handle global rate limits', async () => {
@@ -486,7 +495,7 @@ test('server responding too slow', async () => {
const promise = api2.get('/slow');
await expect(promise).rejects.toThrowError('Request aborted');
}, 1000);
}, 1_000);
test('Unauthorized', async () => {
mockPool
@@ -518,7 +527,7 @@ test('Bad Request', async () => {
path: genPath('/badRequest'),
method: 'GET',
})
.reply(403, { message: 'Missing Permissions', code: 50013 }, responseOptions);
.reply(403, { message: 'Missing Permissions', code: 50_013 }, responseOptions);
const promise = api.get('/badRequest');
await expect(promise).rejects.toThrowError('Missing Permissions');

View File

@@ -1,8 +1,7 @@
import { MockAgent, setGlobalDispatcher } from 'undici';
import type { Interceptable } from 'undici/types/mock-interceptor';
import { MockAgent, setGlobalDispatcher, type Interceptable } from 'undici';
import { beforeEach, afterEach, test, expect } from 'vitest';
import { genPath } from './util';
import { REST } from '../src';
import { REST } from '../src/index.js';
import { genPath } from './util.js';
const api = new REST();
@@ -35,7 +34,7 @@ test('no token', async () => {
});
test('negative offset', () => {
const badREST = new REST({ offset: -5000 });
const badREST = new REST({ offset: -5_000 });
expect(badREST.requestManager.options.offset).toEqual(0);
});

View File

@@ -1,6 +1,7 @@
import { Blob } from 'node:buffer';
import { Blob, Buffer } from 'node:buffer';
import { URLSearchParams } from 'node:url';
import { test, expect } from 'vitest';
import { resolveBody, parseHeader } from '../src/lib/utils/utils';
import { resolveBody, parseHeader } from '../src/lib/utils/utils.js';
test('GIVEN string parseHeader returns string', () => {
const header = 'application/json';
@@ -37,7 +38,7 @@ test('resolveBody', async () => {
const iterable: Iterable<Uint8Array> = {
*[Symbol.iterator]() {
for (let i = 0; i < 3; i++) {
for (let index = 0; index < 3; index++) {
yield new Uint8Array([1, 2, 3]);
}
},
@@ -46,15 +47,15 @@ test('resolveBody', async () => {
const asyncIterable: AsyncIterable<Uint8Array> = {
[Symbol.asyncIterator]() {
let i = 0;
let index = 0;
return {
next() {
if (i < 3) {
i++;
return Promise.resolve({ value: new Uint8Array([1, 2, 3]), done: false });
async next() {
if (index < 3) {
index++;
return { value: new Uint8Array([1, 2, 3]), done: false };
}
return Promise.resolve({ value: undefined, done: true });
return { value: undefined, done: true };
},
};
},

View File

@@ -1,4 +1,4 @@
import { DefaultRestOptions } from '../src';
import { DefaultRestOptions } from '../src/index.js';
export function genPath(path: `/${string}`) {
return `/api/v${DefaultRestOptions.version}${path}` as const;

View File

@@ -1,5 +1,5 @@
import { describe, test, expect } from 'vitest';
import { makeURLSearchParams } from '../src';
import { makeURLSearchParams } from '../src/index.js';
describe('makeURLSearchParams', () => {
test('GIVEN undefined THEN returns empty URLSearchParams', () => {
@@ -41,7 +41,7 @@ describe('makeURLSearchParams', () => {
describe('objects', () => {
test('GIVEN a record of date values THEN URLSearchParams with ISO string values', () => {
const params = makeURLSearchParams({ before: new Date('2022-04-04T15:43:05.108Z'), after: new Date(NaN) });
const params = makeURLSearchParams({ before: new Date('2022-04-04T15:43:05.108Z'), after: new Date(Number.NaN) });
expect([...params.entries()]).toEqual([['before', '2022-04-04T15:43:05.108Z']]);
});