const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const { merge } = require('./media/document-sync'); // Compare the editor's base with disk at save time, not with a watcher cache. // A temp file prevents readers from observing a truncated intermediate file. function saveDocument(file, base, local, io = fs) { if (typeof base !== 'string' || typeof local !== 'string') throw new Error('Save protocol mismatch. Restart the Overleaf Studio extension host.'); const target = io.realpathSync(file); // Keep symbolic links intact; never recreate a deleted file. for (let attempt = 0; attempt < 3; attempt++) { const disk = io.readFileSync(target, 'utf8'); const text = merge(base, local, disk); if (text === null) return { conflict: true, text: disk }; if (text === disk) return { text }; const st = io.statSync(target); const temp = path.join(path.dirname(target), `.overleaf-save-${crypto.randomBytes(12).toString('hex')}`); try { io.writeFileSync(temp, text, { flag: 'wx', mode: st.mode & 0o777 }); const tmp = io.statSync(temp); if (tmp.uid !== st.uid || tmp.gid !== st.gid) io.chownSync(temp, st.uid, st.gid); io.chmodSync(temp, st.mode & 0o7777); // Recheck after preparing the write, in case an external edit arrived meanwhile. if (io.readFileSync(target, 'utf8') !== disk) continue; io.renameSync(temp, target); return { text }; } finally { try { io.unlinkSync(temp); } catch (e) { if (e.code !== 'ENOENT') throw e; } } } throw new Error('The file keeps changing outside Overleaf Studio. Your edit has not overwritten it.'); } module.exports = { saveDocument };