54 lines
1.8 KiB
TypeScript
54 lines
1.8 KiB
TypeScript
import { app } from "electron";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import type { AppSettings } from "../shared/types";
|
|
|
|
export const DEFAULT_APP_SETTINGS: AppSettings = {
|
|
browserElementWaitMs: 5000,
|
|
aiConfig: { baseUrl: "", apiKey: "", model: "", visionModel: "" }
|
|
};
|
|
|
|
let cache: AppSettings | null = null;
|
|
|
|
function settingsPath(): string {
|
|
return path.join(app.getPath("userData"), "settings.json");
|
|
}
|
|
|
|
function normalizeSettings(value: unknown): AppSettings {
|
|
const source = (value && typeof value === "object" ? value : {}) as Partial<AppSettings>;
|
|
const wait = Number(source.browserElementWaitMs);
|
|
const ai = (source.aiConfig && typeof source.aiConfig === "object" ? source.aiConfig : {}) as Partial<AppSettings["aiConfig"]>;
|
|
return {
|
|
browserElementWaitMs: Number.isFinite(wait)
|
|
? Math.min(600000, Math.max(0, Math.round(wait)))
|
|
: DEFAULT_APP_SETTINGS.browserElementWaitMs,
|
|
aiConfig: {
|
|
baseUrl: String(ai.baseUrl ?? ""),
|
|
apiKey: String(ai.apiKey ?? ""),
|
|
model: String(ai.model ?? ""),
|
|
visionModel: String(ai.visionModel ?? "")
|
|
}
|
|
};
|
|
}
|
|
|
|
export function loadSettings(): AppSettings {
|
|
try {
|
|
cache = normalizeSettings(JSON.parse(fs.readFileSync(settingsPath(), "utf8")));
|
|
} catch {
|
|
cache = { ...DEFAULT_APP_SETTINGS };
|
|
}
|
|
return cache;
|
|
}
|
|
|
|
export function saveSettings(settings: AppSettings): AppSettings {
|
|
const normalized = normalizeSettings(settings);
|
|
fs.mkdirSync(app.getPath("userData"), { recursive: true });
|
|
fs.writeFileSync(settingsPath(), JSON.stringify(normalized, null, 2), "utf8");
|
|
cache = normalized;
|
|
return normalized;
|
|
}
|
|
|
|
export function updateSettings(patch: Partial<AppSettings> = {}): AppSettings {
|
|
return saveSettings({ ...(cache || loadSettings()), ...patch });
|
|
}
|