/** Close codes that should not trigger auto-reconnect (auth / intentional server kicks). */ export const NO_AUTO_RECONNECT_CODES = new Set([ 1000, // normal closure (also used by intentional close()) 1001, // going away / server restart 4000, // logged in elsewhere 4401, // authentication required 1011 // authentication / session setup failed ]); /** * Exponential backoff delay for reconnect attempts. * @param {number} attempt zero-based attempt index * @param {{ baseMs?: number, maxMs?: number }} [options] */ export function nextReconnectDelayMs (attempt, { baseMs = 750, maxMs = 20_000 } = {}) { const n = Math.max(0, attempt | 0); return Math.min(maxMs, baseMs * (2 ** n)); } /** * @param {number} code WebSocket close code * @param {{ intentional?: boolean, autoReconnect?: boolean }} [options] */ export function shouldAutoReconnect (code, { intentional = false, autoReconnect = false } = {}) { if (!autoReconnect || intentional) { return false; } return !NO_AUTO_RECONNECT_CODES.has(code | 0); } export class GameSocket { /** * @param {string} url * @param {(message: object) => void} onMessage * @param {{ * onClose?: (event: CloseEvent) => void, * onError?: (event: Event) => void, * onOpen?: (event: Event) => void, * onReconnecting?: (info: { attempt: number, delayMs: number, code: number }) => void, * autoReconnect?: boolean, * reconnectBaseMs?: number, * reconnectMaxMs?: number * }} [options] */ constructor (url, onMessage, { onClose, onError, onOpen, onReconnecting, autoReconnect = false, reconnectBaseMs = 750, reconnectMaxMs = 20_000 } = {}) { this.url = url; this.onMessage = onMessage; this.onClose = onClose; this.onError = onError; this.onOpen = onOpen; this.onReconnecting = onReconnecting; this.autoReconnect = !!autoReconnect; this.reconnectBaseMs = reconnectBaseMs; this.reconnectMaxMs = reconnectMaxMs; this.socket = null; this._intentionalClose = false; this._reconnectAttempt = 0; this._reconnectTimer = null; this._boundMessage = (event) => { this.onMessage(JSON.parse(event.data)); }; this._boundClose = (event) => { this._handleClose(event); }; this._boundError = (event) => { this.onError?.(event); }; this._boundOpen = (event) => { this.onOpen?.(event); }; } connect () { this._intentionalClose = false; return this._openSocket(); } /** Graceful client-initiated close — does not auto-reconnect. */ close (code = 1000, reason = "Client closed") { this._intentionalClose = true; this._clearReconnectTimer(); this._reconnectAttempt = 0; const socket = this.socket; this._detach(socket); if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) { try { socket.close(code, reason); } catch { /* ignore */ } } this.socket = null; } /** Call when an application SESSION (or equivalent) is established so backoff resets. */ notifySessionEstablished () { this._reconnectAttempt = 0; this._clearReconnectTimer(); } send (payload) { if (!this.socket || this.socket.readyState !== WebSocket.OPEN) { throw new Error("WebSocket is not connected."); } this.socket.send(JSON.stringify(payload)); } get reconnecting () { return this._reconnectTimer != null; } _openSocket () { this._clearReconnectTimer(); this._detach(this.socket); const socket = new WebSocket(this.url); this.socket = socket; socket.addEventListener("message", this._boundMessage); socket.addEventListener("close", this._boundClose); socket.addEventListener("error", this._boundError); socket.addEventListener("open", this._boundOpen); return new Promise((resolve, reject) => { const onOpen = () => { cleanup(); resolve(); }; const onError = () => { cleanup(); reject(new Error("WebSocket failed")); }; const cleanup = () => { socket.removeEventListener("open", onOpen); socket.removeEventListener("error", onError); }; socket.addEventListener("open", onOpen, { once: true }); socket.addEventListener("error", onError, { once: true }); }); } _detach (socket) { if (!socket) { return; } socket.removeEventListener("message", this._boundMessage); socket.removeEventListener("close", this._boundClose); socket.removeEventListener("error", this._boundError); socket.removeEventListener("open", this._boundOpen); } _clearReconnectTimer () { if (this._reconnectTimer != null) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; } } _scheduleReconnect (code) { const attempt = this._reconnectAttempt; const delayMs = nextReconnectDelayMs(attempt, { baseMs: this.reconnectBaseMs, maxMs: this.reconnectMaxMs }); this._reconnectAttempt = attempt + 1; this.onReconnecting?.({ attempt: this._reconnectAttempt, delayMs, code: code | 0 }); this._reconnectTimer = setTimeout(() => { this._reconnectTimer = null; void this._openSocket().catch(() => { // open/error path usually also emits close; if not, retry from here if (this._intentionalClose || !this.autoReconnect || this.socket) { return; } this._scheduleReconnect(code); }); }, delayMs); } _handleClose (event) { this._detach(event?.target ?? this.socket); if (this.socket === event?.target) { this.socket = null; } this.onClose?.(event); const code = event?.code | 0; if (!shouldAutoReconnect(code, { intentional: this._intentionalClose, autoReconnect: this.autoReconnect })) { this._intentionalClose = false; return; } this._scheduleReconnect(code); } } export function defaultSocketUrl () { const protocol = location.protocol === "https:" ? "wss:" : "ws:"; return `${protocol}//${location.host}/ws`; }