443 lines
17 KiB
TypeScript
443 lines
17 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
import { isAbsolute, join } from 'node:path';
|
|
import { app, BrowserWindow, dialog, shell } from 'electron';
|
|
import {
|
|
computeAutoSortOrder,
|
|
discoverMods,
|
|
emptyClientModsConfig,
|
|
MOD_API_VERSION,
|
|
normalizeClientModsConfig,
|
|
resolveModLoadOrder,
|
|
type ClientModsConfig,
|
|
type DiscoveredMod,
|
|
type ModPreset,
|
|
} from '@wto/mods';
|
|
import { AppError } from '@shared/errors.ts';
|
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
|
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
|
|
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
|
import { getSettings, updateSettings } from '../config/settings-store.ts';
|
|
import { listCopies } from '../install/install-record.ts';
|
|
import { resourcePaths } from '../resources/resource-paths.ts';
|
|
|
|
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
|
|
const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded';
|
|
const inFlightSeeds = new Map<string, Promise<void>>();
|
|
|
|
export function defaultModsFolder(): string {
|
|
return join(app.getPath('userData'), 'mods');
|
|
}
|
|
|
|
export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> {
|
|
const settings = await getSettings();
|
|
const defaultModsDir = defaultModsFolder();
|
|
const isCustomModsDir = settings.modsFolder !== null;
|
|
const modsDir = settings.modsFolder ?? defaultModsDir;
|
|
await mkdir(modsDir, { recursive: true });
|
|
await seedBundledExampleModsOnce(modsDir);
|
|
return { modsDir, defaultModsDir, isCustomModsDir };
|
|
}
|
|
|
|
/**
|
|
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
|
|
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
|
|
* deleting a bundled template never restores it, while newly added official templates still
|
|
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
|
|
*/
|
|
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
|
|
const key = modsDir.toLowerCase();
|
|
const pending = inFlightSeeds.get(key);
|
|
if (pending) {
|
|
await pending;
|
|
return;
|
|
}
|
|
const task = (async () => {
|
|
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
|
|
try {
|
|
const templatesRoot = resourcePaths().modTemplates;
|
|
if (!(await pathExists(templatesRoot))) return;
|
|
const seeded = await readSeededTemplateNames(markerPath, modsDir);
|
|
const templates = await readdir(templatesRoot, { withFileTypes: true });
|
|
let changed = false;
|
|
for (const entry of templates) {
|
|
if (!entry.isDirectory()) continue;
|
|
if (seeded.has(entry.name)) continue;
|
|
const dest = join(modsDir, entry.name);
|
|
if (!(await pathExists(dest))) {
|
|
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
|
|
}
|
|
seeded.add(entry.name);
|
|
changed = true;
|
|
}
|
|
if (changed || !(await pathExists(markerPath))) {
|
|
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
|
|
}
|
|
} catch (error) {
|
|
console.warn('[mods] seeding bundled example mods skipped:', error);
|
|
}
|
|
})().finally(() => {
|
|
inFlightSeeds.delete(key);
|
|
});
|
|
inFlightSeeds.set(key, task);
|
|
await task;
|
|
}
|
|
|
|
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
|
|
if (!(await pathExists(markerPath))) return new Set();
|
|
try {
|
|
const raw = (await readFile(markerPath, 'utf8')).trim();
|
|
if (raw === '1') {
|
|
// Legacy marker from initial 2-template version: mark existing folders as already seeded
|
|
// so newly added official templates (e.g. official-map-selector) are still delivered once.
|
|
const existing = await readdir(modsDir);
|
|
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
|
|
for (const name of existing) set.add(name);
|
|
return set;
|
|
}
|
|
const parsed = JSON.parse(raw) as { seeded?: unknown };
|
|
if (Array.isArray(parsed.seeded)) {
|
|
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
|
|
}
|
|
} catch { /* ignore */ }
|
|
return new Set();
|
|
}
|
|
|
|
async function pathExists(path: string): Promise<boolean> {
|
|
try {
|
|
await access(path);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function openModsFolder(): Promise<void> {
|
|
const { modsDir } = await resolveModsFolder();
|
|
const failure = await shell.openPath(modsDir);
|
|
if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure);
|
|
}
|
|
|
|
export async function openModDocs(language?: string): Promise<void> {
|
|
const docsRoot = resourcePaths().modDocs;
|
|
const preferred = language && language.toLowerCase().startsWith('zh') ? 'zh-CN.html' : 'en.html';
|
|
const fallback = preferred === 'zh-CN.html' ? 'en.html' : 'zh-CN.html';
|
|
const target = (await pathExists(join(docsRoot, preferred)))
|
|
? join(docsRoot, preferred)
|
|
: join(docsRoot, fallback);
|
|
if (!(await pathExists(target))) {
|
|
throw new AppError('folder_unreadable', { path: docsRoot });
|
|
}
|
|
const failure = await shell.openPath(target);
|
|
if (failure) console.warn('[mods] opening the mod docs failed:', target, failure);
|
|
}
|
|
|
|
export async function getModsState(copyId: string): Promise<ModsStateView> {
|
|
const copy = await requireCopy(copyId);
|
|
return buildModsStateView(copy);
|
|
}
|
|
|
|
export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise<ModsStateView> {
|
|
const copy = await requireCopy(copyId);
|
|
const { modsDir } = await resolveModsFolder();
|
|
const discovered = discoverMods(modsDir);
|
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
|
const next: ClientModsConfig = {
|
|
...current,
|
|
activePresetId: null,
|
|
enabled: { ...current.enabled, [modId]: enabled },
|
|
};
|
|
await writeClientModsConfig(copy.dataPath, next);
|
|
return buildModsStateView(copy, next);
|
|
}
|
|
|
|
export async function setModsOrder(copyId: string, order: readonly string[]): Promise<ModsStateView> {
|
|
const copy = await requireCopy(copyId);
|
|
const { modsDir } = await resolveModsFolder();
|
|
const discovered = discoverMods(modsDir);
|
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
|
const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods);
|
|
await writeClientModsConfig(copy.dataPath, next);
|
|
return buildModsStateView(copy, next);
|
|
}
|
|
|
|
export async function autoSortMods(copyId: string): Promise<ModsStateView> {
|
|
const copy = await requireCopy(copyId);
|
|
const { modsDir } = await resolveModsFolder();
|
|
const discovered = discoverMods(modsDir);
|
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
|
const sortedOrder = computeAutoSortOrder(discovered.mods, current.order);
|
|
const next: ClientModsConfig = {
|
|
...current,
|
|
activePresetId: null,
|
|
order: sortedOrder,
|
|
};
|
|
await writeClientModsConfig(copy.dataPath, next);
|
|
return buildModsStateView(copy, next);
|
|
}
|
|
|
|
export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise<ModsStateView> {
|
|
const copy = await requireCopy(copyId);
|
|
const { modsDir } = await resolveModsFolder();
|
|
const discovered = discoverMods(modsDir);
|
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
|
const now = new Date().toISOString();
|
|
|
|
let presets: ModPreset[];
|
|
let presetId: string;
|
|
if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) {
|
|
presetId = overwriteId;
|
|
presets = current.presets.map((preset) => (
|
|
preset.id === overwriteId
|
|
? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }
|
|
: preset
|
|
));
|
|
} else {
|
|
presetId = randomUUID();
|
|
presets = [
|
|
...current.presets,
|
|
{ id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now },
|
|
];
|
|
}
|
|
|
|
const next: ClientModsConfig = {
|
|
...current,
|
|
activePresetId: presetId,
|
|
presets,
|
|
};
|
|
await writeClientModsConfig(copy.dataPath, next);
|
|
return buildModsStateView(copy, next);
|
|
}
|
|
|
|
export async function applyModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
|
|
const copy = await requireCopy(copyId);
|
|
const { modsDir } = await resolveModsFolder();
|
|
const discovered = discoverMods(modsDir);
|
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
|
const preset = current.presets.find((item) => item.id === presetId);
|
|
if (!preset) throw new AppError('mods_preset_invalid');
|
|
|
|
const next = normalizeClientModsConfig({
|
|
...current,
|
|
order: preset.order,
|
|
enabled: preset.enabled,
|
|
activePresetId: preset.id,
|
|
}, discovered.mods);
|
|
await writeClientModsConfig(copy.dataPath, next);
|
|
return buildModsStateView(copy, next);
|
|
}
|
|
|
|
export async function deleteModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
|
|
const copy = await requireCopy(copyId);
|
|
const current = await readClientModsConfig(copy.dataPath);
|
|
const next: ClientModsConfig = {
|
|
...current,
|
|
activePresetId: current.activePresetId === presetId ? null : current.activePresetId,
|
|
presets: current.presets.filter((preset) => preset.id !== presetId),
|
|
};
|
|
await writeClientModsConfig(copy.dataPath, next);
|
|
return buildModsStateView(copy, next);
|
|
}
|
|
|
|
export async function exportModPreset(
|
|
copyId: string,
|
|
presetId: string,
|
|
window: BrowserWindow | null,
|
|
): Promise<{ readonly path: string | null }> {
|
|
const copy = await requireCopy(copyId);
|
|
const current = await readClientModsConfig(copy.dataPath);
|
|
const preset = current.presets.find((item) => item.id === presetId);
|
|
if (!preset) throw new AppError('mods_preset_invalid');
|
|
|
|
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
|
|
const dialogOptions = {
|
|
defaultPath: `${safeName}.wto-mods-preset.json`,
|
|
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
|
};
|
|
const choice = window
|
|
? await dialog.showSaveDialog(window, dialogOptions)
|
|
: await dialog.showSaveDialog(dialogOptions);
|
|
if (choice.canceled || !choice.filePath) return { path: null };
|
|
|
|
const payload = {
|
|
format: 1 as const,
|
|
name: preset.name,
|
|
order: [...preset.order],
|
|
enabled: { ...preset.enabled },
|
|
};
|
|
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
|
|
return { path: choice.filePath };
|
|
}
|
|
|
|
export async function importModPreset(
|
|
copyId: string,
|
|
window: BrowserWindow | null,
|
|
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
|
|
const copy = await requireCopy(copyId);
|
|
const dialogOptions = {
|
|
properties: ['openFile'] as Array<'openFile'>,
|
|
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
|
};
|
|
const choice = window
|
|
? await dialog.showOpenDialog(window, dialogOptions)
|
|
: await dialog.showOpenDialog(dialogOptions);
|
|
if (choice.canceled || !choice.filePaths[0]) {
|
|
return { imported: false, state: await buildModsStateView(copy) };
|
|
}
|
|
|
|
let parsedRaw: unknown;
|
|
try {
|
|
parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown;
|
|
} catch {
|
|
throw new AppError('mods_preset_invalid');
|
|
}
|
|
const validated = ModPresetTransferSchema.safeParse(parsedRaw);
|
|
if (!validated.success) throw new AppError('mods_preset_invalid');
|
|
|
|
const current = await readClientModsConfig(copy.dataPath);
|
|
const newPreset: ModPreset = {
|
|
id: randomUUID(),
|
|
name: validated.data.name,
|
|
order: validated.data.order,
|
|
enabled: validated.data.enabled,
|
|
updatedAt: new Date().toISOString(),
|
|
};
|
|
const next: ClientModsConfig = {
|
|
...current,
|
|
presets: [...current.presets, newPreset],
|
|
};
|
|
await writeClientModsConfig(copy.dataPath, next);
|
|
return { imported: true, state: await buildModsStateView(copy, next) };
|
|
}
|
|
|
|
export async function setModsFolder(copyId: string, folderPath: string | null): Promise<ModsStateView> {
|
|
if (folderPath !== null) {
|
|
if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid');
|
|
try {
|
|
await mkdir(folderPath, { recursive: true });
|
|
const info = await stat(folderPath);
|
|
if (!info.isDirectory()) throw new AppError('mods_folder_invalid');
|
|
} catch (error) {
|
|
if (error instanceof AppError) throw error;
|
|
throw new AppError('mods_folder_invalid');
|
|
}
|
|
}
|
|
await updateSettings({ modsFolder: folderPath });
|
|
const copy = await requireCopy(copyId);
|
|
return buildModsStateView(copy);
|
|
}
|
|
|
|
/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */
|
|
export async function resolveEnabledModsForLaunch(
|
|
dataPath: string,
|
|
gameVersion: string | null,
|
|
): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> {
|
|
const { modsDir } = await resolveModsFolder();
|
|
const discovered = discoverMods(modsDir);
|
|
const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods);
|
|
const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion);
|
|
if (resolved.hasBlockingErrors) {
|
|
console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error'));
|
|
throw new AppError('mods_blocking_issues');
|
|
}
|
|
return { modsDir, enabledMods: resolved.enabledMods };
|
|
}
|
|
|
|
async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise<ModsStateView> {
|
|
const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder();
|
|
const discovered = discoverMods(modsDir);
|
|
const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath);
|
|
const config = normalizeClientModsConfig(rawConfig, discovered.mods);
|
|
const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion);
|
|
|
|
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
|
const orderedMods: ModListItem[] = config.order
|
|
.map((id) => byId.get(id))
|
|
.filter((mod): mod is DiscoveredMod => mod !== undefined)
|
|
.map(toModListItem);
|
|
|
|
return {
|
|
modsDir,
|
|
defaultModsDir,
|
|
isCustomModsDir,
|
|
apiVersion: MOD_API_VERSION,
|
|
mods: orderedMods,
|
|
discoveryErrors: [...discovered.errors],
|
|
order: [...config.order],
|
|
enabled: { ...config.enabled },
|
|
activePresetId: config.activePresetId,
|
|
presets: config.presets.map((preset) => ({
|
|
id: preset.id,
|
|
name: preset.name,
|
|
order: [...preset.order],
|
|
enabled: { ...preset.enabled },
|
|
updatedAt: preset.updatedAt,
|
|
})),
|
|
issues: [...resolved.issues],
|
|
hasBlockingErrors: resolved.hasBlockingErrors,
|
|
};
|
|
}
|
|
|
|
function toModListItem(mod: DiscoveredMod): ModListItem {
|
|
return {
|
|
id: mod.manifest.id,
|
|
folderName: mod.folderName,
|
|
rootDir: mod.rootDir,
|
|
name: mod.manifest.name,
|
|
...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}),
|
|
version: mod.manifest.version,
|
|
author: mod.manifest.author,
|
|
apiVersion: mod.manifest.apiVersion,
|
|
gameVersions: [...mod.manifest.gameVersions],
|
|
requires: [...mod.manifest.requires],
|
|
conflicts: [...mod.manifest.conflicts],
|
|
loadAfter: [...mod.manifest.loadAfter],
|
|
loadBefore: [...mod.manifest.loadBefore],
|
|
badges: [...mod.content.badges],
|
|
hasServerScript: mod.content.serverEntry !== undefined,
|
|
serverTuningFiles: [...mod.content.serverTuningFiles],
|
|
packOperations: [...mod.content.packOperations],
|
|
guiPatchCount: mod.content.guiPatchDirs.length,
|
|
exePatchCount: mod.content.exePatchDirs.length,
|
|
hasClientAddon: mod.content.hasClientAddon,
|
|
addonFileCount: mod.content.addonRelativeFiles.length,
|
|
clientFileCount: mod.content.clientFiles.length,
|
|
hasConfigBlkPatch: mod.content.configBlkPatch !== undefined,
|
|
};
|
|
}
|
|
|
|
async function requireCopy(copyId: string): Promise<InstallRecord> {
|
|
const copies = await listCopies();
|
|
const copy = copies.copies.find((entry) => entry.id === copyId);
|
|
if (!copy) throw new AppError('copy_not_found');
|
|
return copy;
|
|
}
|
|
|
|
async function readClientModsConfig(dataPath: string): Promise<ClientModsConfig> {
|
|
const path = join(dataPath, CLIENT_MODS_CONFIG_FILE);
|
|
try {
|
|
const raw = await readJsonOr(path, null);
|
|
if (!raw || typeof raw !== 'object') return emptyClientModsConfig();
|
|
const obj = raw as Partial<ClientModsConfig>;
|
|
return {
|
|
format: 1,
|
|
order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [],
|
|
enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {},
|
|
activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null,
|
|
presets: Array.isArray(obj.presets) ? obj.presets : [],
|
|
};
|
|
} catch (error) {
|
|
console.warn('[mods] unreadable client mods config, using defaults:', path, error);
|
|
return emptyClientModsConfig();
|
|
}
|
|
}
|
|
|
|
async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise<void> {
|
|
try {
|
|
await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config);
|
|
} catch (error) {
|
|
console.error('[mods] writing client mods config failed:', error);
|
|
throw new AppError('mods_write_failed');
|
|
}
|
|
}
|