From 05629a00a033bbf4d1444af29ce852b886d91daf Mon Sep 17 00:00:00 2001 From: Jared Miller Date: Tue, 27 Jan 2026 18:01:59 -0500 Subject: [PATCH] Add type-safe message decoding --- src/protocol.ts | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/protocol.ts b/src/protocol.ts index 9809a4b..24320f0 100644 --- a/src/protocol.ts +++ b/src/protocol.ts @@ -25,9 +25,33 @@ export function encode(msg: ServerMessage): string { return JSON.stringify(msg); } +function isClientMessage(obj: unknown): obj is ClientMessage { + if (typeof obj !== "object" || obj === null) return false; + const msg = obj as Record; + + switch (msg.type) { + case "join": + return typeof msg.room === "string"; + case "leave": + return true; + case "update": + return ( + Array.isArray(msg.data) && msg.data.every((n) => typeof n === "number") + ); + case "awareness": + return ( + Array.isArray(msg.data) && msg.data.every((n) => typeof n === "number") + ); + default: + return false; + } +} + export function decode(raw: string): ClientMessage | null { try { - return JSON.parse(raw) as ClientMessage; + const parsed = JSON.parse(raw); + if (!isClientMessage(parsed)) return null; + return parsed; } catch { return null; }