Skip to content

Commit

Permalink
lint: apply new eslint rules
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasgloning committed Aug 8, 2023
1 parent aba2f91 commit 3f81eb0
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 39 deletions.
9 changes: 5 additions & 4 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
"parser": "@typescript-eslint/parser",
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
"plugin:@typescript-eslint/recommended-type-checked",
"plugin:@typescript-eslint/strict-type-checked",
"plugin:@typescript-eslint/stylistic-type-checked"
],
"ignorePatterns": ["coverage", "jest.config.js", "dist", "__test__"],
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
"project": true
}
}
2 changes: 1 addition & 1 deletion __test__/models/messageQueue.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, expect, it } from "@jest/globals";

import { MessageQueue } from "../../src/models/messageQueue.ts";
import { MessageType } from "../../src/enums.ts";
import type { IMessage } from "../../src/models/message.ts";
import type { IMessage } from "../../src/index.js";
import { wait } from "../utils.ts";

describe("MessageQueue", () => {
Expand Down
2 changes: 1 addition & 1 deletion __test__/services/messagesExpire/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, expect, it } from "@jest/globals";

import { Client } from "../../../src/models/client.ts";
import { Realm } from "../../../src/models/realm.ts";
import type { IMessage } from "../../../src/models/message.ts";
import type { IMessage } from "../../../src/index.js";
import { MessagesExpire } from "../../../src/services/messagesExpire/index.ts";
import { MessageHandler } from "../../../src/messageHandler/index.ts";
import { MessageType } from "../../../src/enums.ts";
Expand Down
4 changes: 2 additions & 2 deletions __test__/services/webSocketServer/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,11 @@ describe("WebSocketServer", () => {
ws.destroy = async (): Promise<void> => {
ws.close();

wait(10);
await wait(10);

webSocketServer.destroy?.();

wait(10);
await wait(10);

ws.destroy = undefined;
};
Expand Down
12 changes: 7 additions & 5 deletions bin/peerjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import fs from "node:fs";
const optimistUsageLength = 98;
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import { PeerServer } from "../src";
import { PeerServer } from "../src/index.js";
import type { AddressInfo } from "node:net";
import type { CorsOptions } from "cors";

Expand Down Expand Up @@ -66,7 +66,7 @@ const opts = y
type: "string",
demandOption: false,
describe: "custom path",
default: process.env["PEERSERVER_PATH"] || "/",
default: process.env["PEERSERVER_PATH"] ?? "/",
},
allow_discovery: {
type: "boolean",
Expand All @@ -89,18 +89,20 @@ const opts = y
.parseSync();

if (!opts.port) {
opts.port = parseInt(process.env["PORT"] as string);
// .port is only not set if the PORT env var is set
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
opts.port = parseInt(process.env["PORT"]!);
}
if (opts.cors) {
opts["corsOptions"] = {
origin: opts.cors,
} satisfies CorsOptions;
}
process.on("uncaughtException", function (e) {
console.error("Error: " + e);
console.error("Error: " + e.toString());
});

if (opts.sslkey || opts.sslcert) {
if (opts.sslkey ?? opts.sslcert) {
if (opts.sslkey && opts.sslcert) {
opts["ssl"] = {
key: fs.readFileSync(path.resolve(opts.sslkey)),
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ function ExpressPeerServer(
}

app.on("mount", () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!server) {
throw new Error(
"Server is not passed to constructor - " + "can't start PeerServer",
Expand Down
1 change: 1 addition & 0 deletions src/instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface PeerServerEvents {
event: "message",
listener: (client: IClient, message: IMessage) => void,
): this;
// eslint-disable-next-line @typescript-eslint/unified-signatures
on(event: "disconnect", listener: (client: IClient) => void): this;
on(event: "error", listener: (client: Error) => void): this;
}
Expand Down
2 changes: 1 addition & 1 deletion src/messageHandler/handlersRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export interface IHandlersRegistry {
}

export class HandlersRegistry implements IHandlersRegistry {
private readonly handlers: Map<MessageType, Handler> = new Map();
private readonly handlers = new Map<MessageType, Handler>();

public registerHandler(messageType: MessageType, handler: Handler): void {
if (this.handlers.has(messageType)) return;
Expand Down
4 changes: 2 additions & 2 deletions src/models/realm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ export interface IRealm {
}

export class Realm implements IRealm {
private readonly clients: Map<string, IClient> = new Map();
private readonly messageQueues: Map<string, IMessageQueue> = new Map();
private readonly clients = new Map<string, IClient>();
private readonly messageQueues = new Map<string, IMessageQueue>();

public getClientsIds(): string[] {
return [...this.clients.keys()];
Expand Down
51 changes: 30 additions & 21 deletions src/services/webSocketServer/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { EventEmitter } from "node:events";
import type { IncomingMessage } from "node:http";
import url from "node:url";
import type WebSocket from "ws";
import { Errors, MessageType } from "../../enums.ts";
import type { IClient } from "../../models/client.ts";
Expand All @@ -10,17 +9,12 @@ import type { IRealm } from "../../models/realm.ts";
import { WebSocketServer as Server } from "ws";
import type { Server as HttpServer } from "node:http";
import type { Server as HttpsServer } from "node:https";
import { IMessage } from "../../models/message.js";

export interface IWebSocketServer extends EventEmitter {
readonly path: string;
}

interface IAuthParams {
id?: string;
token?: string;
key?: string;
}

type CustomConfig = Pick<
IConfig,
"path" | "key" | "concurrent_limit" | "createWebSocketServer"
Expand Down Expand Up @@ -62,26 +56,33 @@ export class WebSocketServer extends EventEmitter implements IWebSocketServer {
? config.createWebSocketServer(options)
: new Server(options);

this.socketServer.on("connection", (socket, req) =>
this._onSocketConnection(socket, req),
);
this.socketServer.on("error", (error: Error) => this._onSocketError(error));
this.socketServer.on("connection", (socket, req) => {
this._onSocketConnection(socket, req);
});
this.socketServer.on("error", (error: Error) => {
this._onSocketError(error);
});
}

private _onSocketConnection(socket: WebSocket, req: IncomingMessage): void {
// An unhandled socket error might crash the server. Handle it first.
socket.on("error", (error) => this._onSocketError(error));

const { query = {} } = url.parse(req.url ?? "", true);
socket.on("error", (error) => {
this._onSocketError(error);
});

const { id, token, key }: IAuthParams = query;
const { searchParams } = new URL(req.url ?? "");
const id = searchParams.get("id");
const token = searchParams.get("token");
const key = searchParams.get("key");

if (!id || !token || !key) {
return this._sendErrorAndClose(socket, Errors.INVALID_WS_PARAMETERS);
this._sendErrorAndClose(socket, Errors.INVALID_WS_PARAMETERS);
return;
}

if (key !== this.config.key) {
return this._sendErrorAndClose(socket, Errors.INVALID_KEY);
this._sendErrorAndClose(socket, Errors.INVALID_KEY);
return;
}

const client = this.realm.getClientById(id);
Expand All @@ -96,10 +97,12 @@ export class WebSocketServer extends EventEmitter implements IWebSocketServer {
}),
);

return socket.close();
socket.close();
return;
}

return this._configureWS(socket, client);
this._configureWS(socket, client);
return;
}

this._registerClient({ socket, id, token });
Expand All @@ -123,7 +126,8 @@ export class WebSocketServer extends EventEmitter implements IWebSocketServer {
const clientsCount = this.realm.getClientsIds().length;

if (clientsCount >= this.config.concurrent_limit) {
return this._sendErrorAndClose(socket, Errors.CONNECTION_LIMIT_EXCEED);
this._sendErrorAndClose(socket, Errors.CONNECTION_LIMIT_EXCEED);
return;
}

const newClient: IClient = new Client({ id, token });
Expand All @@ -147,7 +151,8 @@ export class WebSocketServer extends EventEmitter implements IWebSocketServer {
// Handle messages from peers.
socket.on("message", (data) => {
try {
const message = JSON.parse(data.toString());
// eslint-disable-next-line @typescript-eslint/no-base-to-string
const message = JSON.parse(data.toString()) as Writable<IMessage>;

message.src = client.getId();

Expand All @@ -171,3 +176,7 @@ export class WebSocketServer extends EventEmitter implements IWebSocketServer {
socket.close();
}
}

type Writable<T> = {
-readonly [K in keyof T]: T[K];
};
3 changes: 1 addition & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,5 @@
"exactOptionalPropertyTypes": false,
"allowImportingTsExtensions": true
},
"include": ["./src/**/*", "__test__/**/*"],
"exclude": ["test", "bin"]
"include": ["./src/**/*", "__test__/**/*", "bin/**/*"]
}

0 comments on commit 3f81eb0

Please sign in to comment.