1import type { File } from "expo-file-system";
2
3let tempFileSequence = 0;
4
5/**
6 * Replaces a file's contents through a sibling temp file and an overwriting
7 * rename, so an interrupted write (app restart, process death) never leaves a
8 * truncated document at the final path. Each write stages through its own
9 * temp file so concurrent writers to the same destination cannot move or
10 * clobber each other's staging file mid-flight.
11 */
12export async function writeFileAtomically(file: File, contents: string): Promise<void> {
13 const { File: FileConstructor } = await import("expo-file-system");
14 tempFileSequence += 1;
15 const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
16 temp.create({ intermediates: true, overwrite: true });
17 await temp.write(contents);
18 temp.moveSync(file, { overwrite: true });
19}