Compare commits

..

1 commit

Author SHA1 Message Date
05629a00a0
Add type-safe message decoding 2026-01-27 18:01:59 -05:00
3 changed files with 31 additions and 4 deletions

View file

@ -8,7 +8,10 @@ start:
bun run start
check:
bun run lint && bun run typecheck && bun run test
bun run check
fix:
bun run fix
build:
docker build -t collabd .

View file

@ -3,11 +3,11 @@
"version": "0.1.0",
"type": "module",
"scripts": {
"lint": "bunx biome check --write .",
"dev": "bun run --watch src/index.ts",
"start": "bun run src/index.ts",
"test": "bun test",
"typecheck": "bunx tsc"
"check": "biome check .",
"fix": "biome check --write ."
},
"dependencies": {
"lib0": "^0.2.117",

View file

@ -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<string, unknown>;
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;
}