/** * Write the built files into the game copy folder atomically so transient antivirus locks or * interrupted writes never leave a missing or truncated game file. */ import { randomBytes } from 'node:crypto'; import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import type { GameCopyFile } from './build-game-copy.ts'; const TRANSIENT_REPLACE_ERRORS = new Set(['EPERM', 'EBUSY', 'EACCES']); const MAX_REPLACE_ATTEMPTS = 8; const WAIT_BUFFER = new Int32Array(new SharedArrayBuffer(4)); /** Writes every file and returns the full paths written, in order. */ export function writeGameCopy(copyFolder: string, files: readonly GameCopyFile[]): string[] { return files.map((file) => { const path = join(copyFolder, file.path); writeFileAtomically(path, file.content); return path; }); } function writeFileAtomically(path: string, content: Uint8Array): void { mkdirSync(dirname(path), { recursive: true }); // Replacing via rename keeps hard-linked stock files untouched by giving the copy its own inode, // and avoids deleting the target before the replacement is fully flushed to disk. const temporary = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`; const fd = openSync(temporary, 'w'); try { writeFileSync(fd, content); fsyncSync(fd); } catch (error) { try { closeSync(fd); } catch { /* ignore */ } try { rmSync(temporary, { force: true }); } catch { /* ignore */ } throw error; } closeSync(fd); try { renameWithRetry(temporary, path); } catch (error) { try { rmSync(temporary, { force: true }); } catch { /* ignore */ } throw error; } } function renameWithRetry(source: string, target: string): void { for (let attempt = 1; ; attempt += 1) { try { renameSync(source, target); return; } catch (error) { const code = (error as NodeJS.ErrnoException).code; if (attempt >= MAX_REPLACE_ATTEMPTS || !code || !TRANSIENT_REPLACE_ERRORS.has(code)) throw error; // A read-only target fails rename with EPERM/EACCES on Windows; clear the attribute before retrying. if (code === 'EPERM' || code === 'EACCES') { try { chmodSync(target, 0o666); } catch { /* ignore */ } } Atomics.wait(WAIT_BUFFER, 0, 0, attempt * 30); } } }