const altObjects = {
    sockets: [],
    parties: [],
    altId: 0,
    mousePosition: { x: 0, y: 0 },
    mouseMove: true,
    keyboard: true,
    states: {
        controlled: true,
        locked: false
    },
    sendPacketToAll: (opcode, packetData = {}) => {
        altObjects.sockets.forEach((ws) => {
            if (!altObjects.states.controlled) return;
            ws.network.sendPacket(opcode, packetData, ws);
        });
    },
    forEachSocket: (callback) => {
        altObjects.sockets.forEach((ws) => {
            callback(ws);
        })
    },
    getDistanceSquared(point1, point2) {
        const dx = point2.x - point1.x;
        const dy = point2.y - point1.y;
        return dx * dx + dy * dy;
    },
    getPlayerData(sockets) {
        return Object.values(sockets)
            .filter(socket => socket.myPlayer.entityClass === "PlayerEntity")
            .map(socket => ({
                x: socket.myPlayer.position.x,
                y: socket.myPlayer.position.y,
                uid: socket.myPlayer.uid
            }));
    },
    findClosestPlayer(playerData, mousePosition) {
        return playerData.reduce((closest, player) => {
            const distanceSquared = this.getDistanceSquared(mousePosition, player);
            if (!closest || distanceSquared < closest.distanceSquared) {
                return { ...player, distanceSquared };
            }
            return closest;
        }, null);
    },
    getClosestPlayerToMouse() {
        const mousePosition = altObjects.mousePosition;
        const players = this.getPlayerData(this.sockets);
        const closestPlayer = this.findClosestPlayer(players, mousePosition);

        return closestPlayer ? {
            x: closestPlayer.x,
            y: closestPlayer.y,
            uid: closestPlayer.uid
        } : null;
    },
    createParty(raidType) {
        // TODO: This only works for 1by1 atm, need to make it work for xkey
        if (this.sockets.length === 0) {
            console.log("No connections available to form a party.");
            return;
        }
    
        let numSocketsToAdd;
        if (raidType === "1by1") {
            numSocketsToAdd = 1;
        } else if (raidType === "xkey") {
            numSocketsToAdd = 3;
        } else {
            console.error("Invalid raid type.");
            return;
        }
    
        let index = 0; // Keep track of the current index in the sockets array
        let cloneIdSet = new Set(); // Set to track unique cloneIds
    
        while (index < this.sockets.length) {
            let party = [];
            let socketsProcessed = 0;
    
            while (socketsProcessed < numSocketsToAdd && index < this.sockets.length) {
                const socket = this.sockets[index];
                if (!cloneIdSet.has(socket.cloneId)) {
                    cloneIdSet.add(socket.cloneId);
                    party.push({ socket, psk: socket.psk, hasStash: false });
                    socketsProcessed++;
                }
                index++; // Move to the next socket in the array
            }
    
            if (party.length > 0) {
                console.log(`Party ${this.parties.length + 1} created with ${party.length} connections.`);
                this.parties.push(party);
            } else {
                // All remaining sockets have duplicate cloneIds, stop creating parties
                break;
            }
    
            cloneIdSet.clear(); // Clear the set for the next party
        }
    }    
};

class WebSocketHandler {
    constructor(name = "", sid = "") {
        this.name = name;
        this.sid = sid;
        this.enterworld2data = null;
        this.worker = new Worker("worker.js");
        // this.workerSever = new WebSocket('ws://localhost:3000');
        this.createWebSocket();
        this.setupWorker();
    }

    createWebSocket() {
        const serverId = this.sid || game.options.serverId;
        const server = game.options.servers[serverId];
        this.ws = new WebSocket(`wss://${server.hostname}:443/`);
        this.ws.binaryType = "arraybuffer";

        this.ws.onopen = () => this.handleOpen();
        this.ws.onmessage = (msg) => this.handleMessage(msg);
        this.ws.onclose = (e) => this.handleClose(e);
        this.ws.onRpc = () => this.handleRpc();
    }

    setupWorker() {
        this.worker.onmessage = (event) => {
            const {
                status,
                result,
                extra,
                enterworld2
            } = event.data;

            if (status === "finalizeOpcode10") {
                this.ws.send(result);
            } else if (status === "opcode5Complete") {
                this.ws.network.sendPacket(4, {
                    displayName: this.name,
                    extra: extra
                });
                this.enterworld2data = enterworld2;
            }
        };
    }

    handleOpen() {
        this.ws.network = new game.networkType();
        this.ws.network.sendPacket = (e, t) => {
            this.ws.send(this.ws.network.codec.encode(e, t));
        };
        this.ws.player = {};
        this.ws.myPlayer = {uid: null, position: {x: 0, y: 0}, model: "GamePlayer"};
        this.ws.inventory = {};
        this.ws.buildings = {};
        this.ws.reversedYaw = false;
    }

    handleRpc() {
        switch (this.ws.data.name) {
            case "Dead":
                this.ws.network.sendPacket(3, { respawn: 1 });
                break;
            case "SetItem":
                this.ws.inventory[this.ws.data.response.itemName] = this.ws.data.response;
                !this.ws.inventory[this.ws.data.response.itemName].stacks ? delete this.ws.inventory[this.ws.data.response.itemName] : 0;
                break;
            case "PartyShareKey":
                this.ws.psk = this.ws.data.response.partyShareKey;
                break;
            case "DayCycle":
                this.ws.isDay = this.ws.data.response.isDay;
                break;
            case "LocalBuilding":
                for (let i in this.ws.data.response) {
                    this.ws.buildings[this.ws.data.response[i].uid] = this.ws.data.response[i];
                    this.ws.buildings[this.ws.data.response[i].uid].dead ? delete this.ws.buildings[this.ws.data.response[i].uid] : 0;
                }
                break;
        }
    }

    handleMessage(msg) {
        const opcode = new Uint8Array(msg.data)[0];
        if (opcode == 5) {
            this.worker.postMessage({
                action: "opcode5",
                data: new Uint8Array(msg.data),
                ipAddress: game.network.connectionOptions.ipAddress,
            });
            return;
        }

        if (opcode == 10) {
            this.worker.postMessage({
                action: "opcode10",
                data: msg.data
            });
            return;
        }

        this.ws.data = this.ws.network.codec.decode(msg.data);
        switch (this.ws.data.opcode) {
            case 0:
                if (!this.ws.isclosed) {
                    for (let uid in this.ws.data.entities[this.ws.myPlayer.uid]) {
                        uid !== "uid" ? this.ws.myPlayer[uid] = this.ws.data.entities[this.ws.myPlayer.uid][uid] : 0;
                    }
                }
                break;
            case 4:
                this.enterworld2data && this.ws.send(this.enterworld2data);
                this.ws.myPlayer.uid = this.ws.data.uid;
                this.ws.network.sendPacket(3, {
                    up: 1
                });

                if (game.world.inWorld) {
                    this.ws.network.sendPacket(9, {
                        name: "JoinPartyByShareKey",
                        partyShareKey: game.ui.playerPartyShareKey
                    });
                }

                // Load Leaderboard
                for (let i = 0; i < 26; i++) this.ws.send(new Uint8Array([3, 17, 123, 34, 117, 112, 34, 58, 49, 44, 34, 100, 111, 119, 110, 34, 58, 48, 125]));
                this.ws.send(new Uint8Array([7, 0]));
                this.ws.send(new Uint8Array([9, 6, 0, 0, 0, 126, 8, 0, 0, 108, 27, 0, 0, 146, 23, 0, 0, 82, 23, 0, 0, 8, 91, 11, 0, 8, 91, 11, 0, 0, 0, 0, 0, 32, 78, 0, 0, 76, 79, 0, 0, 172, 38, 0, 0, 120, 155, 0, 0, 166, 39, 0, 0, 140, 35, 0, 0, 36, 44, 0, 0, 213, 37, 0, 0, 100, 0, 0, 0, 120, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 134, 6, 0, 0]));
                this.ws.cloneId = ++altObjects.altId;

                this.ws.network.sendRpc({
                    name: "BuyItem",
                    itemName: "PetCARL",
                    tier: 1
                });
                this.ws.network.sendRpc({
                    name: "BuyItem",
                    itemName: "PetMiner",
                    tier: 1
                });

                this.ws.player = document.createElement("div");
                this.ws.player.classList.add("hud-map-player");
                this.ws.player.style.display = "block";
                this.ws.player.dataset.index = "4";
                document.getElementsByClassName("hud-map")[0].appendChild(this.ws.player);

                altObjects.sockets.push(this.ws)
                break;
            case 9:
                !this.ws.isclosed ? this.ws.onRpc(this.ws.data) : 0;
                break;
        }
    }

    handleClose() {
        this.ws.isclosed = true;
        this.ws.player.remove();
        this.worker.terminate();
    }
};

Optimize, improve, and compact this code as much as possible. Make sure its modulated and to add any additional features you feel contribute to the codebase.