import * as Y from 'yjs';
/**
 * Create a `DocumentPersistence` backed by a `DocumentCRDT` Prisma table.
 *
 * The returned object satisfies the realtime package's contract so it can
 * be passed straight to `bindPersistence(room, persistence)`.
 */
export function createPrismaDocumentPersistence(db, options = {}) {
    return {
        async load(documentId) {
            const row = await db.documentCRDT.findUnique({
                where: { documentId },
                select: { state: true },
            });
            if (!row)
                return null;
            // Defensive copy: callers may mutate the buffer once we return it
            // (Prisma typically gives back a fresh Uint8Array, but we don't want
            // to rely on internal guarantees here).
            return copyBytes(row.state);
        },
        async save(documentId, state) {
            // Compute the new state vector from the encoded state. Cheap — Yjs
            // decodes the update structure but skips construction of clients.
            const doc = new Y.Doc();
            Y.applyUpdate(doc, state);
            const stateVector = Y.encodeStateVector(doc);
            doc.destroy();
            await db.documentCRDT.upsert({
                where: { documentId },
                create: {
                    documentId,
                    state: copyBytes(state),
                    stateVector,
                    version: 1,
                    lastUpdatedById: options.lastUpdatedById ?? null,
                },
                update: {
                    state: copyBytes(state),
                    stateVector,
                    version: { increment: 1 },
                    lastUpdatedById: options.lastUpdatedById ?? null,
                },
            });
        },
    };
}
function copyBytes(src) {
    const dst = new Uint8Array(src.length);
    dst.set(src);
    return dst;
}
//# sourceMappingURL=persistence.js.map