feat(launcher): add Mods page, per-client presets, custom repo folder, and launch integration
This commit is contained in:
1 parent
aa7a6e7d02
commit
dbc21182a2
21 files changed
+1961
-21
No files matched your search
@@ -17,6 +17,19 @@ import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesSta
|
||||
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
|
||||
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
|
||||
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
|
||||
import {
|
||||
applyModPreset,
|
||||
autoSortMods,
|
||||
deleteModPreset,
|
||||
exportModPreset,
|
||||
getModsState,
|
||||
importModPreset,
|
||||
openModsFolder,
|
||||
saveModPreset,
|
||||
setModEnabled,
|
||||
setModsFolder,
|
||||
setModsOrder,
|
||||
} from '../services/mods/mods-service.ts';
|
||||
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
||||
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
||||
import { broadcast, handle } from './register.ts';
|
||||
@@ -175,6 +188,48 @@ export function registerIpcHandlers(): void {
|
||||
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
|
||||
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
|
||||
|
||||
const requireModsWritable = (): void => {
|
||||
if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only');
|
||||
};
|
||||
handle('mods:getState', ({ copyId }) => getModsState(copyId));
|
||||
handle('mods:setEnabled', ({ copyId, modId, enabled }) => {
|
||||
requireModsWritable();
|
||||
return setModEnabled(copyId, modId, enabled);
|
||||
});
|
||||
handle('mods:setOrder', ({ copyId, order }) => {
|
||||
requireModsWritable();
|
||||
return setModsOrder(copyId, order);
|
||||
});
|
||||
handle('mods:autoSort', ({ copyId }) => {
|
||||
requireModsWritable();
|
||||
return autoSortMods(copyId);
|
||||
});
|
||||
handle('mods:savePreset', ({ copyId, name, overwriteId }) => {
|
||||
requireModsWritable();
|
||||
return saveModPreset(copyId, name, overwriteId);
|
||||
});
|
||||
handle('mods:applyPreset', ({ copyId, presetId }) => {
|
||||
requireModsWritable();
|
||||
return applyModPreset(copyId, presetId);
|
||||
});
|
||||
handle('mods:deletePreset', ({ copyId, presetId }) => {
|
||||
requireModsWritable();
|
||||
return deleteModPreset(copyId, presetId);
|
||||
});
|
||||
handle('mods:exportPreset', ({ copyId, presetId }, sender) =>
|
||||
exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender)));
|
||||
handle('mods:importPreset', ({ copyId }, sender) => {
|
||||
requireModsWritable();
|
||||
return importModPreset(copyId, BrowserWindow.fromWebContents(sender));
|
||||
});
|
||||
handle('mods:openFolder', () => openModsFolder());
|
||||
handle('mods:setFolder', async ({ copyId, path }) => {
|
||||
requireModsWritable();
|
||||
const state = await setModsFolder(copyId, path);
|
||||
broadcast('event:settings-changed', await getSettings());
|
||||
return state;
|
||||
});
|
||||
|
||||
handle('launch:getState', () => getLaunchState());
|
||||
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
|
||||
handle('launch:start', () => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { Settings } from '@shared/schemas/settings.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { decalCachePath } from '../install/decals.ts';
|
||||
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
|
||||
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
|
||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||
import { saveBackup } from '../saves/save-archive.ts';
|
||||
import { buildCopy } from './build-copy.ts';
|
||||
@@ -108,7 +109,7 @@ async function launch(job: LaunchJob): Promise<void> {
|
||||
job.copyId = record.id;
|
||||
const plan = await planLaunch(job, record, settings);
|
||||
if (plan === null) return;
|
||||
const { lab, copyPath, stockPath, dataPath, port } = plan;
|
||||
const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan;
|
||||
await buildForLaunch(job, record, plan, settings);
|
||||
|
||||
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
|
||||
@@ -123,7 +124,15 @@ async function launch(job: LaunchJob): Promise<void> {
|
||||
update(job, { phase: 'ready' });
|
||||
return;
|
||||
}
|
||||
const gameExit = await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish);
|
||||
const gameExit = await runOrdinaryLaunch(
|
||||
copyPath,
|
||||
dataPath,
|
||||
port,
|
||||
settings,
|
||||
signal,
|
||||
publish,
|
||||
{ modsDir, enabledModIds },
|
||||
);
|
||||
update(job, { phase: 'game-exited', gameExit });
|
||||
}
|
||||
|
||||
@@ -134,6 +143,8 @@ interface LaunchPlan {
|
||||
readonly dataPath: string;
|
||||
readonly steamLibraryConfirmed: boolean;
|
||||
readonly port: number;
|
||||
readonly modsDir: string;
|
||||
readonly enabledModIds: readonly string[];
|
||||
}
|
||||
|
||||
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
|
||||
@@ -183,13 +194,15 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
|
||||
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
|
||||
}
|
||||
if (games) throw new AppError('launch_game_running');
|
||||
const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion);
|
||||
const enabledModIds = enabledMods.map((mod) => mod.manifest.id);
|
||||
const port = await selectPort(requestedPort);
|
||||
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port };
|
||||
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds };
|
||||
}
|
||||
|
||||
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
|
||||
const signal = job.stop.signal;
|
||||
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan;
|
||||
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan;
|
||||
if (settings.autoSaveBackups) {
|
||||
for (const { userId } of new AccountStore(dataPath).all()) {
|
||||
signal.throwIfAborted();
|
||||
@@ -211,6 +224,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
|
||||
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
||||
hookLogging: settings.loggingEnabled,
|
||||
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
||||
modsDir,
|
||||
enabledModIds,
|
||||
}, signal, (filesWritten, filesTotal, file) => {
|
||||
writtenFiles = filesWritten;
|
||||
if (!signal.aborted) update(job, {
|
||||
|
||||
@@ -33,13 +33,22 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor
|
||||
}
|
||||
}
|
||||
|
||||
export interface StartLocalServerOptions extends Omit<ServerOptions, 'report' | 'mods'> {
|
||||
readonly modsDir?: string;
|
||||
readonly enabledModIds?: readonly string[];
|
||||
}
|
||||
|
||||
export async function startLocalServer(
|
||||
{ gameFolder, dataFolder, port, loggingEnabled = true }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
|
||||
{ gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal,
|
||||
): Promise<LocalServer> {
|
||||
signal.throwIfAborted();
|
||||
const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'];
|
||||
if (modsDir && enabledModIds && enabledModIds.length > 0) {
|
||||
workerArgs.push(modsDir, JSON.stringify(enabledModIds));
|
||||
}
|
||||
const worker = utilityProcess.fork(
|
||||
join(import.meta.dirname, 'server-worker.js'),
|
||||
[gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'],
|
||||
workerArgs,
|
||||
{
|
||||
serviceName: 'WTOffline local server',
|
||||
stdio: 'pipe',
|
||||
|
||||
@@ -45,12 +45,19 @@ type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-r
|
||||
export async function runOrdinaryLaunch(
|
||||
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
|
||||
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
|
||||
mods?: { readonly modsDir: string; readonly enabledModIds: readonly string[] },
|
||||
): Promise<GameExit> {
|
||||
const args = parseLaunchArguments(settings.launchArguments);
|
||||
if (!args) throw new AppError('launch_game_failed');
|
||||
publish('starting-server');
|
||||
const server = await startLocalServer(
|
||||
{ gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled },
|
||||
{
|
||||
gameFolder: copyPath,
|
||||
dataFolder: dataPath,
|
||||
port,
|
||||
loggingEnabled: settings.loggingEnabled,
|
||||
...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}),
|
||||
},
|
||||
signal,
|
||||
);
|
||||
const stop = new AbortController();
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdir, 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';
|
||||
|
||||
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
|
||||
|
||||
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 });
|
||||
return { modsDir, defaultModsDir, isCustomModsDir };
|
||||
}
|
||||
|
||||
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 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');
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ export interface BuildRequest {
|
||||
readonly decalCache?: string;
|
||||
readonly hookLogging: boolean;
|
||||
readonly acceptedUnavailable: readonly string[];
|
||||
readonly modsDir?: string;
|
||||
readonly enabledModIds?: readonly string[];
|
||||
}
|
||||
|
||||
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
import { readFileSync, realpathSync } from 'node:fs';
|
||||
import { relative } from 'node:path';
|
||||
import type { MessageEvent } from 'electron';
|
||||
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
|
||||
import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
|
||||
import {
|
||||
assertWritableCopy,
|
||||
buildGameCopy,
|
||||
computeModsBuildFingerprint,
|
||||
copyPlayerDecalCache,
|
||||
CORE_BUILD_PACKS,
|
||||
playerDecalCacheProblem,
|
||||
prepareOptionalStockPacks,
|
||||
readStockGameFiles,
|
||||
syncExternalModFiles,
|
||||
writeGameCopy,
|
||||
type GameCopyFile,
|
||||
} from '@wto/patcher';
|
||||
import { multiVehiclePackIds } from '@wto/server';
|
||||
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
|
||||
|
||||
@@ -9,6 +22,9 @@ let prepared: {
|
||||
readonly request: BuildRequest;
|
||||
readonly files: readonly GameCopyFile[];
|
||||
readonly decalCache: string | undefined;
|
||||
readonly enabledMods: readonly DiscoveredMod[];
|
||||
readonly optionalPacksInBuild: readonly ModdableClientPack[];
|
||||
readonly fingerprint: string;
|
||||
} | null = null;
|
||||
|
||||
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
|
||||
@@ -31,17 +47,39 @@ function importedDecals(path: string | undefined): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
|
||||
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
|
||||
const discovered = discoverMods(modsDir);
|
||||
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||
const ordered: DiscoveredMod[] = [];
|
||||
for (const id of enabledModIds) {
|
||||
const mod = byId.get(id);
|
||||
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
|
||||
ordered.push(mod);
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function build(request: BuildRequest): void {
|
||||
checkBuildLocation(request);
|
||||
const decalCache = importedDecals(request.decalCache);
|
||||
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
|
||||
const touchedPacks = touchedClientPacks(enabledMods);
|
||||
const optionalPacksInBuild = touchedPacks.filter((pack) => !CORE_BUILD_PACKS.has(pack));
|
||||
const extraStockPacks = optionalPacksInBuild.length > 0
|
||||
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
|
||||
: undefined;
|
||||
|
||||
const result = buildGameCopy({
|
||||
stock: readStockGameFiles(request.stockPath),
|
||||
patches: request.patches,
|
||||
networkHookLibrary: readFileSync(request.networkHookLibrary),
|
||||
port: request.port,
|
||||
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
|
||||
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
|
||||
placeholderDecals: decalCache === undefined,
|
||||
hookLogging: request.hookLogging,
|
||||
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
|
||||
...(extraStockPacks ? { extraStockPacks } : {}),
|
||||
});
|
||||
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
|
||||
const accepted = new Set(request.acceptedUnavailable);
|
||||
@@ -50,7 +88,19 @@ function build(request: BuildRequest): void {
|
||||
send({ kind: 'failed', error: 'launch_build_unavailable' });
|
||||
return;
|
||||
}
|
||||
prepared = { request, files: result.files, decalCache };
|
||||
if (result.mods.enabledModIds.length > 0) {
|
||||
console.info(
|
||||
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
|
||||
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
|
||||
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
|
||||
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
|
||||
);
|
||||
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
|
||||
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
|
||||
}
|
||||
}
|
||||
const fingerprint = computeModsBuildFingerprint(enabledMods, request.port, request.patches);
|
||||
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
|
||||
send({ kind: 'prepared', total: prepared.files.length });
|
||||
}
|
||||
|
||||
@@ -62,15 +112,22 @@ process.parentPort.on('message', (event: MessageEvent) => {
|
||||
return;
|
||||
}
|
||||
if (!prepared) throw new Error('No build is ready to write.');
|
||||
const { request, files, decalCache } = prepared;
|
||||
const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared;
|
||||
prepared = null;
|
||||
checkBuildLocation(request);
|
||||
const { copyPath } = request;
|
||||
const { copyPath, stockPath } = request;
|
||||
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
|
||||
for (const [index, file] of files.entries()) {
|
||||
writeGameCopy(copyPath, [file]);
|
||||
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
|
||||
}
|
||||
const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint);
|
||||
for (const warning of deployResult.warnings) {
|
||||
console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`);
|
||||
}
|
||||
if (deployResult.restoredOptionalPacks.length > 0) {
|
||||
console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`);
|
||||
}
|
||||
send({ kind: 'written' });
|
||||
} catch (error) {
|
||||
console.error('[build] preparing the game copy failed:', error);
|
||||
|
||||
@@ -1,16 +1,42 @@
|
||||
import { discoverMods, type DiscoveredMod } from '@wto/mods';
|
||||
import { startServer } from '@wto/server';
|
||||
|
||||
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
|
||||
|
||||
function loadOrderedMods(modsDir: string | undefined, enabledJson: string | undefined): DiscoveredMod[] {
|
||||
if (!modsDir || !enabledJson) return [];
|
||||
const ids = JSON.parse(enabledJson) as unknown;
|
||||
if (!Array.isArray(ids) || ids.length === 0) return [];
|
||||
const discovered = discoverMods(modsDir);
|
||||
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||
const mods: DiscoveredMod[] = [];
|
||||
for (const id of ids) {
|
||||
if (typeof id !== 'string') continue;
|
||||
const mod = byId.get(id);
|
||||
if (!mod) throw new Error(`Enabled mod "${id}" not found in ${modsDir}`);
|
||||
mods.push(mod);
|
||||
}
|
||||
return mods;
|
||||
}
|
||||
|
||||
async function serve(): Promise<void> {
|
||||
const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2);
|
||||
const [gameFolder, dataFolder, portText, loggingFlag, modsDir, enabledModIdsJson] = process.argv.slice(2);
|
||||
const port = Number(portText);
|
||||
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error('Invalid local server arguments.');
|
||||
}
|
||||
const loggingEnabled = loggingFlag !== '0';
|
||||
const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info });
|
||||
const mods = loadOrderedMods(modsDir, enabledModIdsJson);
|
||||
const server = await startServer({
|
||||
gameFolder,
|
||||
dataFolder,
|
||||
port,
|
||||
loggingEnabled,
|
||||
...(mods.length > 0 ? { mods } : {}),
|
||||
report: console.info,
|
||||
});
|
||||
if (server.logFolder) console.info('Traffic log:', server.logFolder);
|
||||
if (server.loadedModIds.length > 0) console.info('Loaded server script mods:', server.loadedModIds.join(', '));
|
||||
process.parentPort.once('message', () => {
|
||||
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
|
||||
console.error('Could not close the local server:', error);
|
||||
|
||||
Reference in new issue
Block a user