export class GameSocket { constructor(url, onMessage, { onClose, onError } = {}) { this.url = url; this.onMessage = onMessage; this.onClose = onClose; this.onError = onError; this.socket = null; } connect () { this.socket = new WebSocket(this.url); this.socket.addEventListener("message", (event) => { this.onMessage(JSON.parse(event.data)); }); this.socket.addEventListener("close", (event) => { this.onClose?.(event); }); this.socket.addEventListener("error", (event) => { this.onError?.(event); }); return new Promise((resolve, reject) => { this.socket.addEventListener("open", resolve, { once: true }); this.socket.addEventListener("error", () => reject(new Error("WebSocket failed")), { once: true }); }); } send (payload) { if (!this.socket || this.socket.readyState !== WebSocket.OPEN) { throw new Error("WebSocket is not connected."); } this.socket.send(JSON.stringify(payload)); } } export function defaultSocketUrl () { const protocol = location.protocol === "https:" ? "wss:" : "ws:"; return `${protocol}//${location.host}/ws`; }