diff --git a/src/Indomitable.ts b/src/Indomitable.ts index 8313a95..3b1dd39 100644 --- a/src/Indomitable.ts +++ b/src/Indomitable.ts @@ -214,7 +214,7 @@ export class Indomitable extends EventEmitter { super(); this.clusterCount = options.clusterCount || 'auto'; this.shardCount = options.shardCount || 'auto'; - this.clientOptions = options.clientOptions || {intents: [1 << 0]}; + this.clientOptions = options.clientOptions || { intents: [ 1 << 0 ] }; this.clusterSettings = options.clusterSettings || {}; this.ipcTimeout = options.ipcTimeout ?? 30000; this.spawnTimeout = options.spawnTimeout ?? 60000; @@ -277,7 +277,7 @@ export class Indomitable extends EventEmitter { const sessions = await this.fetchSessions(); this.concurrencyServer = new ConcurrencyServer(this, sessions.session_start_limit.max_concurrency); const info = await this.concurrencyServer.start(); - this.emit(LibraryEvents.DEBUG, `Handle concurrency is currently enabled! =>\n Server is currently bound to:\n Address: ${info.address}:${info.port}\n Concurrency: ${sessions.session_start_limit.max_concurrency}`); + this.emit(LibraryEvents.DEBUG, `Handle concurrency is currently enabled! =>\n Server is currently bound to:\n Address: ${ info.address }:${ info.port }\n Concurrency: ${ sessions.session_start_limit.max_concurrency }`); } if (typeof this.clusterCount !== 'number') @@ -290,15 +290,15 @@ export class Indomitable extends EventEmitter { if (this.shardCount < this.clusterCount) this.clusterCount = this.shardCount; - this.emit(LibraryEvents.DEBUG, `Starting ${this.shardCount} websocket shards across ${this.clusterCount} clusters`); - const shards = [...Array(this.shardCount).keys()]; + this.emit(LibraryEvents.DEBUG, `Starting ${ this.shardCount } websocket shards across ${ this.clusterCount } clusters`); + const shards = [ ...Array(this.shardCount).keys() ]; const chunks = Chunk(shards, Math.round(this.shardCount / this.clusterCount)); - Cluster.setupPrimary({...{serialization: 'json'}, ...this.clusterSettings}); + Cluster.setupPrimary({ ...{ serialization: 'json' }, ...this.clusterSettings }); for (let id = 0; id < this.clusterCount; id++) { const chunk = chunks.shift()!; - const cluster = new ClusterManager({id, shards: chunk, manager: this}); + const cluster = new ClusterManager({ id, shards: chunk, manager: this }); this.clusters.set(id, cluster); } @@ -313,7 +313,7 @@ export class Indomitable extends EventEmitter { public async restart(clusterId: number): Promise { if (!Cluster.isPrimary) return; const cluster = this.clusters.get(clusterId); - if (!cluster) throw new Error(`Invalid clusterId, or a cluster with this id doesn\'t exist, received id ${clusterId}`); + if (!cluster) throw new Error(`Invalid clusterId, or a cluster with this id doesn\'t exist, received id ${ clusterId }`); await this.addToSpawnQueue(cluster); } @@ -362,7 +362,7 @@ export class Indomitable extends EventEmitter { * @returns An array of promise that resolves to undefined or an unknown value depending on how you reply to it */ public broadcast(sendable: Sendable): Promise { - const clusters = [...this.clusters.keys()]; + const clusters = [ ...this.clusters.keys() ]; return Promise.all(clusters.map(id => this.send(id, sendable))); } @@ -377,20 +377,20 @@ export class Indomitable extends EventEmitter { const sessions = await this.fetchSessions(); this.shardCount = sessions.shards; } - this.emit(LibraryEvents.DEBUG, `Reconfigured Indomitable to use ${this.shardCount} shard(s)`); + this.emit(LibraryEvents.DEBUG, `Reconfigured Indomitable to use ${ this.shardCount } shard(s)`); const oldClusterCount = Number(this.clusters.size); this.clusterCount = options.clusters || this.clusters.size; - const shards = [...Array(this.shardCount).keys()]; + const shards = [ ...Array(this.shardCount).keys() ]; const chunks = Chunk(shards, Math.round(this.shardCount as number / this.clusterCount)); if (oldClusterCount < this.clusterCount) { const count = this.clusterCount - oldClusterCount; for (let id = this.clusterCount - 1; id < count; id++) { - const cluster = new ClusterManager({id, shards: [], manager: this}); + const cluster = new ClusterManager({ id, shards: [], manager: this }); this.clusters.set(id, cluster); } } if (oldClusterCount > this.clusterCount) { - const keys = [...this.clusters.keys()].reverse(); + const keys = [ ...this.clusters.keys() ].reverse(); const range = keys.slice(0, oldClusterCount - this.clusterCount); for (const key of range) { const cluster = this.clusters.get(key); @@ -398,7 +398,7 @@ export class Indomitable extends EventEmitter { this.clusters.delete(key); } } - this.emit(LibraryEvents.DEBUG, `Reconfigured Indomitable to use ${this.clusterCount} cluster(s) from ${oldClusterCount} cluster(s)`); + this.emit(LibraryEvents.DEBUG, `Reconfigured Indomitable to use ${ this.clusterCount } cluster(s) from ${ oldClusterCount } cluster(s)`); for (const cluster of this.clusters.values()) { cluster.shards = chunks.shift()!; } @@ -429,7 +429,7 @@ export class Indomitable extends EventEmitter { data: {}, internal: true }; - await this.send(id, {content, reply: true}); + await this.send(id, { content, reply: true }); } /** @@ -439,7 +439,7 @@ export class Indomitable extends EventEmitter { private async processQueue(): Promise { if (this.isBusy || !this.spawnQueue.length) return; this.busy = true; - this.emit(LibraryEvents.DEBUG, `Processing spawn queue with ${this.spawnQueue.length} clusters waiting to be spawned....`); + this.emit(LibraryEvents.DEBUG, `Processing spawn queue with ${ this.spawnQueue.length } clusters waiting to be spawned....`); let cluster: ClusterManager; while (this.spawnQueue.length > 0) { try { @@ -453,7 +453,7 @@ export class Indomitable extends EventEmitter { } catch (error: unknown) { this.emit(LibraryEvents.ERROR, error as Error); if (cluster! && this.autoRestart) { - this.emit(LibraryEvents.DEBUG, `Failed to spawn Cluster ${cluster.id} containing [ ${cluster.shards.join(', ')} ] shard(s). Re-queuing if not in spawn queue`); + this.emit(LibraryEvents.DEBUG, `Failed to spawn Cluster ${ cluster.id } containing [ ${ cluster.shards.join(', ') } ] shard(s). Re-queuing if not in spawn queue`); this.spawnQueue.push(cluster); } } diff --git a/src/Util.ts b/src/Util.ts index ef0030c..fcb9eaf 100644 --- a/src/Util.ts +++ b/src/Util.ts @@ -243,7 +243,7 @@ export function Fetch(url: string, options: RequestOptions): Promise { const code = response.statusCode ?? 500; const body = chunks.join(''); - resolve({code, body, message: response.statusMessage ?? ''}); + resolve({ code, body, message: response.statusMessage ?? '' }); }); }); @@ -261,12 +261,12 @@ export async function FetchSessions(token: string): Promise { const url = new URL('https://discord.com/api/v10/gateway/bot'); const response = await Fetch(url.toString(), { method: 'GET', - headers: {authorization: `Bot ${token}`} + headers: { authorization: `Bot ${ token }` } }); if (response.code >= 200 && response.code <= 299) return JSON.parse(response.body); else - throw new Error(`Response received is not ok, code: ${response.code}`) + throw new Error(`Response received is not ok, code: ${ response.code }`) } /** @@ -300,8 +300,8 @@ export function MakeAbortableRequest(delay: number): AbortableData { const controller = new AbortController(); const seconds = Math.round(delay / 1000); const timeout = setTimeout( - () => controller.abort(new Error(`The request has been aborted in ${seconds} second(s)`)), + () => controller.abort(new Error(`The request has been aborted in ${ seconds } second(s)`)), delay ); - return {controller, timeout}; + return { controller, timeout }; } diff --git a/src/client/ShardClient.ts b/src/client/ShardClient.ts index 1f918ef..8b9e397 100644 --- a/src/client/ShardClient.ts +++ b/src/client/ShardClient.ts @@ -59,26 +59,26 @@ export class ShardClient { // tests the server if it's accessible first before starting the client this.client.emit('debug', '[Indomitable]: Handle concurrency enabled! Testing the identify server before logging in...'); const date = await this.concurrency.checkServer(); - this.client.emit('debug', `[Indomitable]: Identify server responded and is working, Trip Latency: ${Math.round(Date.now() - date)}ms`); + this.client.emit('debug', `[Indomitable]: Identify server responded and is working, Trip Latency: ${ Math.round(Date.now() - date) }ms`); } // attach listeners - this.client.once('ready', () => this.send({op: ClientEvents.READY, data: {clusterId: this.clusterId}})); + this.client.once('ready', () => this.send({ op: ClientEvents.READY, data: { clusterId: this.clusterId } })); this.client.on('shardReady', (shardId: number) => this.send({ op: ClientEvents.SHARD_READY, - data: {clusterId: this.clusterId, shardId} + data: { clusterId: this.clusterId, shardId } })); this.client.on('shardReconnecting', (shardId: number) => this.send({ op: ClientEvents.SHARD_RECONNECT, - data: {clusterId: this.clusterId, shardId} + data: { clusterId: this.clusterId, shardId } })); this.client.on('shardResume', (shardId: number, replayed: number) => this.send({ op: ClientEvents.SHARD_RESUME, - data: {clusterId: this.clusterId, shardId, replayed} + data: { clusterId: this.clusterId, shardId, replayed } })); // @ts-ignore -- Discord.JS faulty typings? this.client.on('shardDisconnect', (event: CloseEvent, shardId: number) => this.send({ op: ClientEvents.SHARD_DISCONNECT, - data: {clusterId: this.clusterId, shardId, event} + data: { clusterId: this.clusterId, shardId, event } })); await this.client.login(token); } @@ -91,9 +91,9 @@ export class ShardClient { private send(partial: PartialInternalEvents): void { // @ts-ignore -- our own class const shardClientUtil = this.client.shard as ShardClientUtil; - const content: ClientEventData = {...partial, internal: true}; + const content: ClientEventData = { ...partial, internal: true }; shardClientUtil - .send({content, reply: false}) + .send({ content, reply: false }) .catch((error: unknown) => this.client.emit(ClientEvents.ERROR, error as Error)); } } diff --git a/src/client/ShardClientUtil.ts b/src/client/ShardClientUtil.ts index 028323e..8a68b2b 100644 --- a/src/client/ShardClientUtil.ts +++ b/src/client/ShardClientUtil.ts @@ -62,7 +62,7 @@ export class ShardClientUtil extends EventEmitter { internal: true }; const start = process.hrtime.bigint(); - const end = await this.send({content, reply: true}) as number; + const end = await this.send({ content, reply: true }) as number; return Number(BigInt(end) - start); } @@ -73,10 +73,10 @@ export class ShardClientUtil extends EventEmitter { public broadcastEval(script: Function, context: any = {}): Promise { const content: InternalOpsData = { op: InternalOps.EVAL, - data: `(${script.toString()})(this, ${JSON.stringify(context)})`, + data: `(${ script.toString() })(this, ${ JSON.stringify(context) })`, internal: true }; - return this.send({content, reply: true}) as Promise; + return this.send({ content, reply: true }) as Promise; } /** @@ -95,10 +95,10 @@ export class ShardClientUtil extends EventEmitter { public fetchSessions(update: boolean = false): Promise { const content: InternalOpsData = { op: InternalOps.SESSION_INFO, - data: {update}, + data: { update }, internal: true }; - return this.send({content, reply: true}) as Promise; + return this.send({ content, reply: true }) as Promise; } /** @@ -108,10 +108,10 @@ export class ShardClientUtil extends EventEmitter { public restart(clusterId: number): Promise { const content: InternalOpsData = { op: InternalOps.RESTART, - data: {clusterId}, + data: { clusterId }, internal: true }; - return this.send({content}) as Promise; + return this.send({ content }) as Promise; } /** @@ -124,7 +124,7 @@ export class ShardClientUtil extends EventEmitter { data: {}, internal: true }; - return this.send({content}) as Promise; + return this.send({ content }) as Promise; } /** diff --git a/src/concurrency/AsyncQueue.ts b/src/concurrency/AsyncQueue.ts index 8f22d8f..b77f63e 100644 --- a/src/concurrency/AsyncQueue.ts +++ b/src/concurrency/AsyncQueue.ts @@ -15,9 +15,9 @@ export class AsyncQueue { return this.queue.length; } - public wait({signal}: AsyncQueueWaitOptions): Promise { + public wait({ signal }: AsyncQueueWaitOptions): Promise { - const next = this.remaining ? once(this.queue[this.remaining - 1], 'resolve', {signal}) : Promise.resolve([]); + const next = this.remaining ? once(this.queue[this.remaining - 1], 'resolve', { signal }) : Promise.resolve([]); const emitter = new EventEmitter() as NodeJS.EventEmitter; diff --git a/src/concurrency/ConcurrencyClient.ts b/src/concurrency/ConcurrencyClient.ts index 49cb9b1..1fb9edc 100644 --- a/src/concurrency/ConcurrencyClient.ts +++ b/src/concurrency/ConcurrencyClient.ts @@ -20,17 +20,17 @@ export class ConcurrencyClient { * If it errors that isn't anything from websocket shard, this will have issues */ public async waitForIdentify(shardId: number, signal: AbortSignal): Promise { - const url = new URL(`http://${this.address}:${this.port}/concurrency/acquire`); + const url = new URL(`http://${ this.address }:${ this.port }/concurrency/acquire`); url.searchParams.append('shardId', shardId.toString()); const listener = () => { - const url = new URL(`http://${this.address}:${this.port}/concurrency/cancel`); + const url = new URL(`http://${ this.address }:${ this.port }/concurrency/cancel`); url.searchParams.append('shardId', shardId.toString()); Fetch(url.toString(), { method: 'DELETE', - headers: {authorization: this.password} + headers: { authorization: this.password } }).catch(() => null); } @@ -39,7 +39,7 @@ export class ConcurrencyClient { const response = await Fetch(url.toString(), { method: 'POST', - headers: {authorization: this.password} + headers: { authorization: this.password } }); if (response.code === 202 || response.code === 204) { @@ -61,11 +61,11 @@ export class ConcurrencyClient { } public async checkServer(): Promise { - const url = new URL(`http://${this.address}:${this.port}/concurrency/check`); + const url = new URL(`http://${ this.address }:${ this.port }/concurrency/check`); url.searchParams.append('shardId', '0'); const response = await Fetch(url.toString(), { method: 'POST', - headers: {authorization: this.password} + headers: { authorization: this.password } }); return Number(response.body); } diff --git a/src/concurrency/ConcurrencyManager.ts b/src/concurrency/ConcurrencyManager.ts index 10fb46a..d2ab920 100644 --- a/src/concurrency/ConcurrencyManager.ts +++ b/src/concurrency/ConcurrencyManager.ts @@ -34,7 +34,7 @@ export class ConcurrencyManager { }); try { - await state.queue.wait({signal: abort.signal}); + await state.queue.wait({ signal: abort.signal }); const difference = state.resets - Date.now(); @@ -57,6 +57,6 @@ export class ConcurrencyManager { */ public abortIdentify(shardId: number): void { const signal = this.signals.get(shardId); - signal?.abort(`Shard ${shardId} aborted the identify request`); + signal?.abort(`Shard ${ shardId } aborted the identify request`); } } diff --git a/src/concurrency/ConcurrencyServer.ts b/src/concurrency/ConcurrencyServer.ts index 31b9e0b..bb078c9 100644 --- a/src/concurrency/ConcurrencyServer.ts +++ b/src/concurrency/ConcurrencyServer.ts @@ -94,7 +94,7 @@ export class ConcurrencyServer { return void response.end('Expected shardId to be a number'); } - this.manager.emit(LibraryEvents.DEBUG, `Received a request in concurrency server! =>\n Url: ${request.url}\n Method: ${request.method}\n ShardId: ${shardId}`); + this.manager.emit(LibraryEvents.DEBUG, `Received a request in concurrency server! =>\n Url: ${ request.url }\n Method: ${ request.method }\n ShardId: ${ shardId }`); if (request.method === 'DELETE' && request.url.includes('/concurrency/cancel')) { this.concurrency.abortIdentify(shardId); diff --git a/src/ipc/BaseSocket.ts b/src/ipc/BaseSocket.ts index cc78991..7cb59d6 100644 --- a/src/ipc/BaseSocket.ts +++ b/src/ipc/BaseSocket.ts @@ -85,7 +85,7 @@ export abstract class BaseSocket { }; this.socket.write(JSON.stringify(data)); if (!data.reply) return resolve(undefined); - this.waitForPromise({nonce, resolve, reject, signal: transportable.signal}); + this.waitForPromise({ nonce, resolve, reject, signal: transportable.signal }); }); } diff --git a/src/ipc/ClientSocket.ts b/src/ipc/ClientSocket.ts index 666adf7..c7211f2 100644 --- a/src/ipc/ClientSocket.ts +++ b/src/ipc/ClientSocket.ts @@ -16,8 +16,8 @@ export class ClientSocket extends BaseSocket { } public connect(): void { - this.socket.connect({path: `./indomitable-${this.serverId}`}, () => { - this.identify({clusterId: this.shard.clusterId, serverId: this.serverId}) + this.socket.connect({ path: `./indomitable-${ this.serverId }` }, () => { + this.identify({ clusterId: this.shard.clusterId, serverId: this.serverId }) .catch(() => null); }); @@ -29,7 +29,7 @@ export class ClientSocket extends BaseSocket { internal: true, data }; - return this.send({content, reply: true}) as Promise; + return this.send({ content, reply: true }) as Promise; } protected handleClose(): void { diff --git a/src/ipc/IpcServer.ts b/src/ipc/IpcServer.ts index bba0a10..d1a4a98 100644 --- a/src/ipc/IpcServer.ts +++ b/src/ipc/IpcServer.ts @@ -29,7 +29,7 @@ export class IpcServer { this.server.once('error', listener); - this.server.listen(`./indomitable-${this.serverId}`, () => { + this.server.listen(`./indomitable-${ this.serverId }`, () => { // @ts-expect-error: why this errors? this.server.removeListener('error', listener); @@ -37,7 +37,7 @@ export class IpcServer { .on('connection', (socket) => { }) - .on('error', (code) => this.manager.emit(LibraryEvents.ERROR, new Error(`IPC server errored with code: ${code}`))); + .on('error', (code) => this.manager.emit(LibraryEvents.ERROR, new Error(`IPC server errored with code: ${ code }`))); resolve(); }); diff --git a/src/ipc/ServerSocket.ts b/src/ipc/ServerSocket.ts index b414a88..a6c7a4b 100644 --- a/src/ipc/ServerSocket.ts +++ b/src/ipc/ServerSocket.ts @@ -18,7 +18,7 @@ export class ServerSocket extends BaseSocket { } protected handleClose(): void { - this.manager.emit(LibraryEvents.DEBUG, `A socket closed with ${this.socket.bytesRead} byte(s) data written`); + this.manager.emit(LibraryEvents.DEBUG, `A socket closed with ${ this.socket.bytesRead } byte(s) data written`); } protected handleError(error: Error): void { diff --git a/src/manager/ClusterManager.ts b/src/manager/ClusterManager.ts index 06d3b4f..52c6861 100644 --- a/src/manager/ClusterManager.ts +++ b/src/manager/ClusterManager.ts @@ -59,7 +59,7 @@ export class ClusterManager { * @param delay Time to wait before restarting worker process */ public async respawn(delay: number = this.manager.spawnDelay) { - this.manager.emit(LibraryEvents.DEBUG, `Restarting Cluster ${this.id} containing [ ${this.shards.join(', ')} ] shard(s)...`); + this.manager.emit(LibraryEvents.DEBUG, `Restarting Cluster ${ this.id } containing [ ${ this.shards.join(', ') } ] shard(s)...`); this.destroy('SIGKILL'); await Delay(delay); await this.spawn(); @@ -69,7 +69,7 @@ export class ClusterManager { * Spawn a worker process */ public async spawn() { - this.manager.emit(LibraryEvents.DEBUG, `Spawning Cluster ${this.id} containing [ ${this.shards.join(', ')} ] shard(s)...`); + this.manager.emit(LibraryEvents.DEBUG, `Spawning Cluster ${ this.id } containing [ ${ this.shards.join(', ') } ] shard(s)...`); this.worker = Cluster.fork({ INDOMITABLE_SHARDS: this.shards.join(' '), INDOMITABLE_SHARDS_TOTAL: this.manager.shardCount.toString(), @@ -91,7 +91,7 @@ export class ClusterManager { if (!this.started) this.started = true; this.manager.emit(LibraryEvents.WORKER_FORK, this); if (this.manager.waitForReady) await this.wait(); - this.manager.emit(LibraryEvents.DEBUG, `Successfully spawned Cluster ${this.id} containing [ ${this.shards.join(', ')} ] shard(s)! | Waited for cluster ready? ${this.manager.waitForReady}`); + this.manager.emit(LibraryEvents.DEBUG, `Successfully spawned Cluster ${ this.id } containing [ ${ this.shards.join(', ') } ] shard(s)! | Waited for cluster ready? ${ this.manager.waitForReady }`); this.manager.emit(LibraryEvents.WORKER_READY, this); await Delay(this.manager.spawnDelay); } @@ -104,7 +104,7 @@ export class ClusterManager { this.worker = undefined; this.ready = false; this.readyAt = -1; - this.manager.emit(LibraryEvents.DEBUG, `Cluster ${this.id} exited with close code ${code || 'unknown'} signal ${signal || 'unknown'}`); + this.manager.emit(LibraryEvents.DEBUG, `Cluster ${ this.id } exited with close code ${ code || 'unknown' } signal ${ signal || 'unknown' }`); this.manager.emit(LibraryEvents.WORKER_EXIT, code, signal, this); } @@ -117,7 +117,7 @@ export class ClusterManager { return new Promise((resolve, reject) => { const ms = this.manager.spawnTimeout * this.shards.length; const seconds = Math.round(ms / 1000); - this.manager.emit(LibraryEvents.DEBUG, `Waiting for client ready event for ${seconds} second(s)`); + this.manager.emit(LibraryEvents.DEBUG, `Waiting for client ready event for ${ seconds } second(s)`); let timeout: NodeJS.Timeout; const listener = (data: ShardEventData) => { if (data.clusterId !== this.id) return; @@ -130,7 +130,7 @@ export class ClusterManager { timeout = setTimeout(() => { this.manager.off(LibraryEvents.CLIENT_READY, listener); this.destroy(); - reject(new Error(`Cluster ${this.id} did not get ready in ${seconds} second(s)`)); + reject(new Error(`Cluster ${ this.id } did not get ready in ${ seconds } second(s)`)); }, ms).unref(); this.manager.on(LibraryEvents.CLIENT_READY, listener); });