import { validate as isUuid } from './uuid'; export interface ChatCursor { id: string; } export interface MessageCursor { chatId: string; id: string; } export function encodeChatCursor(cursor: ChatCursor): string { return encode(cursor); } export function decodeChatCursor(raw: string): ChatCursor | null { const decoded = decode(raw); return decoded && isUuidField(decoded.id) ? { id: decoded.id } : null; } export function encodeMessageCursor(cursor: MessageCursor): string { return encode(cursor); } export function decodeMessageCursor(raw: string): MessageCursor | null { const decoded = decode(raw); return decoded && isUuidField(decoded.chatId) && isUuidField(decoded.id) ? { chatId: decoded.chatId, id: decoded.id } : null; } function isUuidField(value: unknown): value is string { return typeof value === 'string' && isUuid(value); } function encode(value: object): string { return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url'); } function decode(raw: string): Record | null { try { const parsed = JSON.parse( Buffer.from(raw, 'base64url').toString('utf8'), ); return typeof parsed === 'object' && parsed !== null ? parsed : null; } catch { return null; } }