import type { SyncMessage } from './sync-types'; // Sync messages are JSON-encoded and then Noise NK encrypted. The encrypted // binary is base64-encoded for transmission over the text-only WS server. // This layer only handles the JSON ↔ SyncMessage boundary; the caller // is responsible for the encrypt/decrypt step around it. export function encodeSyncMessage(msg: SyncMessage): Uint8Array { return new TextEncoder().encode(JSON.stringify(msg)); } export function decodeSyncMessage(data: Uint8Array): SyncMessage { const parsed = JSON.parse(new TextDecoder().decode(data)); if (typeof parsed?.type !== 'string') throw new Error('invalid sync message'); return parsed as SyncMessage; } // Base64 helpers for the WS text-frame transport layer. export function bytesToBase64(bytes: Uint8Array): string { let binary = ''; for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]); return btoa(binary); } export function base64ToBytes(b64: string): Uint8Array { const binary = atob(b64); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); return bytes; }