import { fromUint8Array, toUint8Array } from 'js-base64'; import * as Y from 'yjs'; export function decodeAttributes(encoded: string): T { const doc = new Y.Doc(); Y.applyUpdate(doc, toUint8Array(encoded)); return doc.getMap('object').toJSON() as T; } export function encodeAttributes(attributes: Record): string { const doc = new Y.Doc(); const updates: Uint8Array[] = []; doc.on('update', (update) => updates.push(update)); doc.transact(() => applyObject(doc.getMap('object'), attributes)); if (updates.length !== 1) throw new Error('Expected one Yjs update'); return fromUint8Array(Y.encodeStateAsUpdate(doc)); } function applyObject(map: Y.Map, object: Record): void { for (const [key, value] of Object.entries(object)) { if (value === null || value === undefined) continue; if (Array.isArray(value)) { const arr = new Y.Array(); arr.insert(0, value.map(convertValue)); map.set(key, arr); } else if (isRecord(value)) { const child = new Y.Map(); applyObject(child, value); map.set(key, child); } else { map.set(key, value); } } } function convertValue(value: unknown): unknown { if (Array.isArray(value)) { const arr = new Y.Array(); arr.insert(0, value.map(convertValue)); return arr; } if (isRecord(value)) { const map = new Y.Map(); applyObject(map, value); return map; } return value; } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); }