linter pass + export types

This commit is contained in:
Erik 2023-07-16 00:37:52 +03:00
parent a7ce02cf33
commit b55cea1de8
Signed by: Navy.gif
GPG Key ID: 2532FBBB61C65A68
8 changed files with 289 additions and 171 deletions

View File

@ -15,17 +15,38 @@
"sourceType": "module" "sourceType": "module"
}, },
"rules": { "rules": {
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-non-null-assertion":"off",
"accessor-pairs": "warn", "accessor-pairs": "warn",
"array-callback-return": "warn", "array-callback-return": "warn",
"array-bracket-newline": [ "warn", "consistent" ], "array-bracket-newline": [
"array-bracket-spacing": [ "warn", "always", { "objectsInArrays": false, "arraysInArrays": false }], "warn",
"consistent"
],
"array-bracket-spacing": [
"warn",
"always",
{
"objectsInArrays": false,
"arraysInArrays": false
}
],
"arrow-spacing": "warn", "arrow-spacing": "warn",
"block-scoped-var": "warn", "block-scoped-var": "warn",
"block-spacing": [ "warn", "always" ], "block-spacing": [
"brace-style": [ "warn", "1tbs" ], "warn",
"always"
],
"brace-style": [
"warn",
"allman"
],
"callback-return": "warn", "callback-return": "warn",
"camelcase": "warn", "camelcase": "warn",
"comma-dangle": [ "warn", "only-multiline" ], "comma-dangle": [
"warn",
"only-multiline"
],
"comma-spacing": [ "comma-spacing": [
"warn", "warn",
{ {
@ -68,9 +89,25 @@
"implicit-arrow-linebreak": "warn", "implicit-arrow-linebreak": "warn",
"indent": "warn", "indent": "warn",
"init-declarations": "warn", "init-declarations": "warn",
"jsx-quotes": [ "warn", "prefer-single" ], "quotes": ["error" , "single"],
"key-spacing": [ "warn", { "beforeColon": false, "afterColon": true }], "jsx-quotes": [
"keyword-spacing": [ "warn", { "after": true, "before": true }], "warn",
"prefer-single"
],
"key-spacing": [
"warn",
{
"beforeColon": false,
"afterColon": true
}
],
"keyword-spacing": [
"warn",
{
"after": true,
"before": true
}
],
"linebreak-style": [ "linebreak-style": [
"error", "error",
"unix" "unix"
@ -79,6 +116,24 @@
"lines-around-directive": "warn", "lines-around-directive": "warn",
"max-classes-per-file": "warn", "max-classes-per-file": "warn",
"max-nested-callbacks": "warn", "max-nested-callbacks": "warn",
"max-len": [
"warn",
{
"code": 140,
"ignoreComments": true,
"ignoreStrings": true,
"ignoreTemplateLiterals": true,
"ignoreRegExpLiterals": true
}
],
"max-lines-per-function": [
"warn",
100
],
"max-depth": [
"warn",
3
],
"new-parens": "warn", "new-parens": "warn",
"no-alert": "warn", "no-alert": "warn",
"no-array-constructor": "warn", "no-array-constructor": "warn",
@ -96,7 +151,6 @@
"no-extend-native": "warn", "no-extend-native": "warn",
"no-extra-bind": "warn", "no-extra-bind": "warn",
"no-extra-label": "warn", "no-extra-label": "warn",
"no-extra-parens": "warn",
"no-floating-decimal": "warn", "no-floating-decimal": "warn",
"no-implicit-coercion": "warn", "no-implicit-coercion": "warn",
"no-implicit-globals": "warn", "no-implicit-globals": "warn",
@ -147,7 +201,7 @@
"no-unmodified-loop-condition": "warn", "no-unmodified-loop-condition": "warn",
"no-unneeded-ternary": "error", "no-unneeded-ternary": "error",
"no-unused-expressions": "warn", "no-unused-expressions": "warn",
"no-use-before-define": "error", "@typescript-eslint/no-use-before-define": "error",
"no-useless-call": "warn", "no-useless-call": "warn",
"no-useless-computed-key": "warn", "no-useless-computed-key": "warn",
"no-useless-concat": "warn", "no-useless-concat": "warn",
@ -155,20 +209,39 @@
"no-useless-rename": "warn", "no-useless-rename": "warn",
"no-useless-return": "warn", "no-useless-return": "warn",
"no-var": "warn", "no-var": "warn",
"no-void": "warn", // "no-void": "warn",
"no-whitespace-before-property": "error", "no-whitespace-before-property": "error",
"nonblock-statement-body-position": [ "warn", "below" ], "nonblock-statement-body-position": [
"warn",
"below"
],
"object-curly-spacing": [ "object-curly-spacing": [
"warn", "warn",
"always" "always"
], ],
"object-property-newline": [ "warn", { "allowAllPropertiesOnSameLine": true }], "object-property-newline": [
"warn",
{
"allowAllPropertiesOnSameLine": true
}
],
"object-shorthand": "warn", "object-shorthand": "warn",
"one-var-declaration-per-line": "warn", "one-var-declaration-per-line": "warn",
"operator-assignment": "warn", "operator-assignment": "warn",
"operator-linebreak": [ "warn", "before" ], "operator-linebreak": [
"warn",
"before"
],
"padding-line-between-statements": "warn", "padding-line-between-statements": "warn",
"padded-blocks": [ "warn", { "switches": "never" }, { "allowSingleLineBlocks": true }], "padded-blocks": [
"warn",
{
"switches": "never"
},
{
"allowSingleLineBlocks": true
}
],
"prefer-arrow-callback": "warn", "prefer-arrow-callback": "warn",
"prefer-const": "warn", "prefer-const": "warn",
"prefer-destructuring": "warn", "prefer-destructuring": "warn",
@ -189,12 +262,18 @@
"last" "last"
], ],
"space-before-blocks": "warn", "space-before-blocks": "warn",
"space-before-function-paren": [ "error", "always" ], "space-before-function-paren": [
"error",
"always"
],
"space-in-parens": [ "space-in-parens": [
"warn", "warn",
"never" "never"
], ],
"spaced-comment": [ "warn", "always" ], "spaced-comment": [
"warn",
"always"
],
"strict": "warn", "strict": "warn",
"switch-colon-spacing": "warn", "switch-colon-spacing": "warn",
"symbol-description": "warn", "symbol-description": "warn",

View File

@ -1,3 +1,4 @@
import { WebhookClient } from "./src/WebhookClient.js"; import { WebhookClient } from './src/WebhookClient.js';
export { Payload, WebhookClientOptions } from './src/types/Webhook.js';
export { WebhookClient }; export { WebhookClient };
export default WebhookClient; export default WebhookClient;

View File

@ -1,7 +1,8 @@
import fetch from 'node-fetch';
import RequestError from './util/RequestError.js'; import RequestError from './util/RequestError.js';
import { ApiErrorData } from './types/Api.js'; import { ApiErrorData } from './types/Api.js';
import EventEmitter from 'events'; import EventEmitter from 'events';
import fetch from 'node-fetch';
type RequestOptions = { type RequestOptions = {
body?: string, body?: string,
@ -21,7 +22,8 @@ type QueuedRequest = {
reject: (err: RequestError) => void reject: (err: RequestError) => void
} }
class HttpClient extends EventEmitter { class HttpClient extends EventEmitter
{
userAgent: string; userAgent: string;
baseUrl: string | null; baseUrl: string | null;
@ -32,7 +34,8 @@ class HttpClient extends EventEmitter {
} = { remaining: 5 }; } = { remaining: 5 };
#queue: QueuedRequest[]; #queue: QueuedRequest[];
constructor ({ userAgent, baseUrl }: HttpClientOptions = {}) { constructor ({ userAgent, baseUrl }: HttpClientOptions = {})
{
super(); super();
@ -45,7 +48,8 @@ class HttpClient extends EventEmitter {
} }
#parseRateLimit (limits: {[key: string]: string}) { #parseRateLimit (limits: {[key: string]: string})
{
// const bucket = limits['x-ratelimit-bucket']; // const bucket = limits['x-ratelimit-bucket'];
const limit = parseInt(limits['x-ratelimit-limit']); const limit = parseInt(limits['x-ratelimit-limit']);
if (isNaN(limit)) // if this doesn't exist the headers weren't returned if (isNaN(limit)) // if this doesn't exist the headers weren't returned
@ -55,7 +59,8 @@ class HttpClient extends EventEmitter {
const resetAfter = parseInt(limits['x-ratelimit-reset-after']) * 1000; const resetAfter = parseInt(limits['x-ratelimit-reset-after']) * 1000;
this.#limit.remaining = remaining; this.#limit.remaining = remaining;
if (this.#queue.length && !this.#limit.timeout) if (this.#queue.length && !this.#limit.timeout)
this.#limit.timeout = setTimeout(async () => { this.#limit.timeout = setTimeout(async () =>
{
this.#processQueue(); this.#processQueue();
delete this.#limit.timeout; delete this.#limit.timeout;
}, resetAfter); }, resetAfter);
@ -63,12 +68,15 @@ class HttpClient extends EventEmitter {
} }
async #processQueue () { async #processQueue ()
{
const queue = [ ...this.#queue ]; const queue = [ ...this.#queue ];
this.#queue = []; this.#queue = [];
for (const req of queue) { for (const req of queue)
{
const { path, options, resolve, reject } = req; const { path, options, resolve, reject } = req;
if (!this.#limit.remaining) { if (!this.#limit.remaining)
{
this.#queue.push(req); this.#queue.push(req);
continue; continue;
} }
@ -78,7 +86,8 @@ class HttpClient extends EventEmitter {
} }
} }
async #_request (path: string, options: RequestOptions): Promise<object | string | null> { async #_request (path: string, options: RequestOptions): Promise<object | string | null>
{
let { headers } = options; let { headers } = options;
const { body, method } = options; const { body, method } = options;
@ -99,21 +108,25 @@ class HttpClient extends EventEmitter {
const response = await fetch(url, request); const response = await fetch(url, request);
const contentType = response.headers.get('Content-Type'); const contentType = response.headers.get('Content-Type');
const ratelimit = [ ...response.headers.entries() ].filter(([ key ]) => key.includes('x-ratelimit')).reduce((prev: {[key: string]: string}, [ key, val ]) => { const ratelimit = [ ...response.headers.entries() ].filter(([ key ]) => key.includes('x-ratelimit')).reduce((prev: {[key: string]: string}, [ key, val ]) =>
{
prev[key] = val; prev[key] = val;
return prev; return prev;
}, {}); }, {});
this.#parseRateLimit(ratelimit); this.#parseRateLimit(ratelimit);
if (response.status === 429) { if (response.status === 429)
{
this.emit('rateLimited'); this.emit('rateLimited');
return new Promise((resolve, reject) => { return new Promise((resolve, reject) =>
{
this.#queue.push({ path, options, resolve, reject }); this.#queue.push({ path, options, resolve, reject });
}); });
} }
if (!response.ok) { if (!response.ok)
{
let message: ApiErrorData | null = null; let message: ApiErrorData | null = null;
if (contentType === 'application/json') if (contentType === 'application/json')
message = await response.json() as ApiErrorData; message = await response.json() as ApiErrorData;
@ -134,9 +147,12 @@ class HttpClient extends EventEmitter {
} }
async request (path: string, options: RequestOptions): Promise<object | string | null> { async request (path: string, options: RequestOptions): Promise<object | string | null>
if (!this.#limit.remaining) { {
return new Promise((resolve, reject) => { if (!this.#limit.remaining)
{
return new Promise((resolve, reject) =>
{
this.#queue.push({ path, options, resolve, reject }); this.#queue.push({ path, options, resolve, reject });
}); });
} }
@ -144,11 +160,13 @@ class HttpClient extends EventEmitter {
return this.#_request(path, options); return this.#_request(path, options);
} }
get (url: string) { get (url: string)
{
return this.request(url, { method: 'GET' }); return this.request(url, { method: 'GET' });
} }
post (url: string, body: object) { post (url: string, body: object)
{
const headers = { const headers = {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}; };

View File

@ -7,7 +7,8 @@ import { RequestError, WebhookError } from './util/index.js';
const WebhookDestroyed = new WebhookError('Webhook does not exist'); const WebhookDestroyed = new WebhookError('Webhook does not exist');
class WebhookClient extends EventEmitter { class WebhookClient extends EventEmitter
{
// Discord credentials // Discord credentials
#url: string; #url: string;
@ -24,14 +25,16 @@ class WebhookClient extends EventEmitter {
#http: HttpClient; #http: HttpClient;
#destroyed = false; #destroyed = false;
constructor ({ url, token, id }: WebhookClientOptions) { constructor ({ url, token, id }: WebhookClientOptions)
{
super(); super();
if (!url && (!token || !id)) if (!url && (!token || !id))
throw new Error('Missing webhook credentials, either pass a url or token and id'); throw new Error('Missing webhook credentials, either pass a url or token and id');
if (url && (!id || !token)) { if (url && (!id || !token))
{
const parts = url.split('/'); const parts = url.split('/');
id = parts[parts.length - 2]; id = parts[parts.length - 2];
token = parts[parts.length - 1]; token = parts[parts.length - 1];
@ -51,7 +54,8 @@ class WebhookClient extends EventEmitter {
} }
#patch (data: WebhookData) { #patch (data: WebhookData)
{
if (data.id) if (data.id)
this.#id = data.id; this.#id = data.id;
@ -69,14 +73,18 @@ class WebhookClient extends EventEmitter {
return this; return this;
} }
async fetch () { async fetch ()
{
if (this.#destroyed) if (this.#destroyed)
throw WebhookDestroyed; throw WebhookDestroyed;
let result = null; let result = null;
try { try
{
result = await this.#http.get(this.#url); result = await this.#http.get(this.#url);
} catch (err) { }
catch (err)
{
if (err instanceof RequestError && err.httpCode === 404) if (err instanceof RequestError && err.httpCode === 404)
this.#destroyed = true; this.#destroyed = true;
throw err; throw err;
@ -84,7 +92,8 @@ class WebhookClient extends EventEmitter {
return this.#patch(result as WebhookData); return this.#patch(result as WebhookData);
} }
async send (content: string | Payload) { async send (content: string | Payload)
{
if (this.#destroyed) if (this.#destroyed)
throw WebhookDestroyed; throw WebhookDestroyed;
@ -100,39 +109,48 @@ class WebhookClient extends EventEmitter {
return response; return response;
} }
get url () { get url ()
{
return this.#url; return this.#url;
} }
get id () { get id ()
{
return this.#id; return this.#id;
} }
get name () { get name ()
{
return this.#name; return this.#name;
} }
get type () { get type ()
{
return this.#type; return this.#type;
} }
get channelId () { get channelId ()
{
return this.#channelId; return this.#channelId;
} }
get guildId () { get guildId ()
{
return this.#guildId; return this.#guildId;
} }
get avatar () { get avatar ()
{
return this.#avatar; return this.#avatar;
} }
get token () { get token ()
{
return this.#token; return this.#token;
} }
get [Symbol.toStringTag] () { get [Symbol.toStringTag] ()
{
return `{ return `{
name: ${this.name}, name: ${this.name},
type: ${this.type}, type: ${this.type},

View File

@ -1,9 +1,11 @@
import { ApiErrorData } from "../types/Api.js"; import { ApiErrorData } from '../types/Api.js';
class RequestError extends Error { class RequestError extends Error
{
code?: number; code?: number;
httpCode: number; httpCode: number;
constructor (response: ApiErrorData) { constructor (response: ApiErrorData)
{
super(`[${response.code ?? response.httpCode}] ${response.message}`); super(`[${response.code ?? response.httpCode}] ${response.message}`);
this.code = response.code; this.code = response.code;

View File

@ -1,4 +1,4 @@
import RequestError from "./RequestError.js"; import RequestError from './RequestError.js';
import WebhookError from "./WebhookError.js"; import WebhookError from './WebhookError.js';
export { RequestError, WebhookError }; export { RequestError, WebhookError };

View File

@ -1,5 +1,5 @@
import WebhookClient from '../build/esm/index.js'; import WebhookClient from '../build/esm/index.js';
import EventEmitter from "events"; import EventEmitter from 'events';
const webhook = new WebhookClient({ url: 'https://discord.com/api/webhooks/1093874668886294548/uDMRD6g1lmq_2EZynsbKytzWoMM-0N4te0m61r_cv1BsSnDKDxG3fvI6sxSoG5t5b_xn' }); const webhook = new WebhookClient({ url: 'https://discord.com/api/webhooks/1093874668886294548/uDMRD6g1lmq_2EZynsbKytzWoMM-0N4te0m61r_cv1BsSnDKDxG3fvI6sxSoG5t5b_xn' });
// new WebhookClient({ token: 'uDMRD6g1lmq_2EZynsbKytzWoMM-0N4te0m61r_cv1BsSnDKDxG3fvI6sxSoG5t5b_xn', id: '1093874668886294548' }); // new WebhookClient({ token: 'uDMRD6g1lmq_2EZynsbKytzWoMM-0N4te0m61r_cv1BsSnDKDxG3fvI6sxSoG5t5b_xn', id: '1093874668886294548' });