/**
* SafeWriter - Atomic writes with backup and System.json versionId update
*/
import { FileHandler } from "./fileHandler.js";
import type { RPGSystem } from "./types.js";
export class SafeWriter {
constructor(private fileHandler: FileHandler) { }
/**
* Write to database file with backup and versionId refresh
*/
async writeToDatabase<T>(filename: string, data: T): Promise<void> {
const filePath = `data/${filename}`;
// 1. Create backup if file exists
if (await this.fileHandler.exists(filePath)) {
await this.fileHandler.backup(filePath);
}
// 2. Write new data
await this.fileHandler.writeJson(filePath, data);
// 3. Update System.json versionId
await this.refreshVersionId();
}
/**
* Update System.json versionId to force editor refresh
*/
async refreshVersionId(): Promise<void> {
const systemPath = "data/System.json";
if (await this.fileHandler.exists(systemPath)) {
const system = await this.fileHandler.readJson<RPGSystem>(systemPath);
system.versionId = Math.floor(Math.random() * 1000000000);
await this.fileHandler.writeJson(systemPath, system);
}
}
/**
* Write to js/plugins folder without versionId update
*/
async writePlugin(filename: string, code: string): Promise<void> {
const filePath = `js/plugins/${filename}.js`;
await this.fileHandler.writeText(filePath, code);
}
/**
* Update plugins.js registry
*/
async updatePluginsRegistry(plugins: unknown[]): Promise<void> {
const content = `// Generated by RPG Maker MZ MCP Server
var $plugins = ${JSON.stringify(plugins, null, 2)};
`;
await this.fileHandler.writeText("js/plugins.js", content);
}
/**
* Write map file and update MapInfos.json
*/
async writeMap(mapId: number, mapData: unknown, mapInfo: unknown): Promise<void> {
const mapFilename = `Map${String(mapId).padStart(3, "0")}.json`;
// Write map file
await this.fileHandler.writeJson(`data/${mapFilename}`, mapData);
// Update MapInfos.json
const mapInfos = await this.fileHandler.readJson<(unknown | null)[]>("data/MapInfos.json");
// Ensure array is large enough
while (mapInfos.length <= mapId) {
mapInfos.push(null);
}
mapInfos[mapId] = mapInfo;
await this.fileHandler.writeJson("data/MapInfos.json", mapInfos);
// Refresh versionId
await this.refreshVersionId();
}
}