import type { BulkWriteRow, RxDocumentData, RxDocumentWriteData, RxStorageInstance, RxStorageInstanceReplicationState, RxStorageReplicationMeta, WithDeletedAndAttachments } from '../types/index.d.ts'; import { clone, createRevision, flatClone, getDefaultRevision, now } from '../plugins/utils/index.ts'; import { stripAttachmentsDataFromDocument } from '../rx-storage-helper.ts'; export function docStateToWriteDoc( databaseInstanceToken: string, hasAttachments: boolean, keepMeta: boolean, docState: WithDeletedAndAttachments, previous?: RxDocumentData ): RxDocumentWriteData { const docData: RxDocumentWriteData = Object.assign( {}, docState, { _attachments: hasAttachments && docState._attachments ? docState._attachments : {}, _meta: keepMeta ? (docState as any)._meta : Object.assign( {}, previous ? previous._meta : {}, { lwt: now() } ), _rev: keepMeta ? (docState as any)._rev : getDefaultRevision() } ); if (!docData._rev) { docData._rev = createRevision( databaseInstanceToken, previous ); } return docData; } export function writeDocToDocState( writeDoc: RxDocumentData, keepAttachments: boolean, keepMeta: boolean ): WithDeletedAndAttachments { const ret = flatClone(writeDoc); if (!keepAttachments) { delete (ret as any)._attachments; } if (!keepMeta) { delete (ret as any)._meta; delete (ret as any)._rev; } return ret; } export function stripAttachmentsDataFromMetaWriteRows( state: RxStorageInstanceReplicationState, rows: BulkWriteRow>[] ): BulkWriteRow>[] { if (!state.hasAttachments) { return rows; } return rows.map(row => { const document = clone(row.document); document.docData = stripAttachmentsDataFromDocument(document.docData); return { document, previous: row.previous }; }); } export function getUnderlyingPersistentStorage( instance: RxStorageInstance ): RxStorageInstance { while (true) { if (instance.underlyingPersistentStorage) { instance = instance.underlyingPersistentStorage; } else { return instance; } } }