import { readFile } from 'node:fs/promises'; import { createServer } from 'node:net'; import { isAbsolute, join } from 'node:path'; import { app, BrowserWindow, shell } from 'electron'; import { AccountStore, LOOPBACK } from '@wto/server'; import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { InstallRecord } from '@shared/schemas/install.ts'; import type { GameExit, LaunchState } from '@shared/schemas/launch.ts'; 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 { resourcePaths } from '../resources/resource-paths.ts'; import { saveBackup } from '../saves/save-archive.ts'; import { buildCopy } from './build-copy.ts'; import { gameProcessRunning } from './game-process.ts'; import { readInstalledLab, runLab, type Lab } from './lab-handoff.ts'; import { localServerStatusUrl } from './local-server.ts'; import { ordinaryLaunchPaths, runOrdinaryLaunch } from './ordinary-launch.ts'; export { gameProcessRunning } from './game-process.ts'; interface LaunchJob { readonly stop: AbortController; readonly report: (state: LaunchState) => void; done: Promise; copyId?: string; } let active: LaunchJob | null = null; let state: LaunchState = { phase: 'ready' }; export function launchInProgress(): boolean { return active !== null; } export function getLaunchState(): LaunchState { return state; } export function startLaunch(report: LaunchJob['report']): LaunchState { const previous = active; if (previous && state.phase !== 'server-running') throw new AppError('launch_busy'); const job: LaunchJob = { stop: new AbortController(), report, done: Promise.resolve() }; active = job; previous?.stop.abort(); update(job, { phase: 'checking' }); job.done = (async () => { // A new build may only write after the server from the previous session has stopped. await previous?.done; job.stop.signal.throwIfAborted(); await launch(job); })().catch((error: unknown) => { if (job.stop.signal.aborted) { update(job, { phase: 'ready' }); return; } const { port } = state; const context = port === undefined ? {} : { port }; console.error('[launch] launch failed:', error); const code = error instanceof AppError ? error.code : 'launch_failed'; switch (code) { case 'launch_port_busy': update(job, { phase: 'port-busy', ...context }); break; case 'launch_server_exited': update(job, { phase: 'server-exited', ...context }); break; default: update(job, { phase: 'failed', error: code, ...context }); break; } }).finally(() => { if (active === job) active = null; }); return state; } export function stopLaunch(): Promise | null { const job = active; if (!job) return null; if (!job.stop.signal.aborted) { update(job, { ...state, phase: 'stopping' }); job.stop.abort(); } return job.done; } export async function openServerStatus(): Promise { if ((state.phase !== 'running' && state.phase !== 'server-running') || state.port === undefined) { throw new AppError('launch_server_exited'); } await shell.openExternal(localServerStatusUrl(state.port)); } function update(job: LaunchJob, next: LaunchState): void { if (active !== job) return; state = job.copyId ? { ...next, copyId: job.copyId } : next; job.report(state); } async function launch(job: LaunchJob): Promise { if (process.platform !== 'win32') throw new AppError('launch_platform_unsupported'); const signal = job.stop.signal; const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); if (!record) throw new AppError('launch_no_copy'); job.copyId = record.id; const plan = await planLaunch(job, record, settings); if (plan === null) return; const { lab, copyPath, stockPath, dataPath, port } = plan; await buildForLaunch(job, record, plan, settings.autoSaveBackups); const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => { if (signal.aborted) return; update(job, { phase, port, gameExit }); if (phase === 'running' && settings.afterGameStarts === 'minimize') { for (const window of BrowserWindow.getAllWindows()) window.minimize(); } }; if (lab) { await runLab(lab, stockPath, dataPath, signal, publish); update(job, { phase: 'ready' }); return; } const gameExit = await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish); update(job, { phase: 'game-exited', gameExit }); } interface LaunchPlan { readonly lab: Lab | null; readonly copyPath: string; readonly stockPath: string; readonly dataPath: string; readonly steamLibraryConfirmed: boolean; readonly port: number; } async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise { const signal = job.stop.signal; const useLab = !app.isPackaged && settings.developerMode; if (useLab && (isInSteamLibrary(record.copyPath) || isInSteamLibrary(await canonicalCopyPath(record.copyPath)))) { throw new AppError('launch_copy_in_steam'); } const currentVersion = await readVersion(record.copyPath, signal); if (!currentVersion || currentVersion !== record.gameVersion) { update(job, { phase: 'version-changed', actualVersion: currentVersion }); return null; } const lab = useLab ? await readInstalledLab() : null; const { copyPath, stockPath, dataPath, steamLibraryConfirmed } = lab ? { copyPath: lab.copyPath, stockPath: settings.labStockPath ?? record.stockBackupPath, dataPath: settings.labDataPath ?? record.dataPath, steamLibraryConfirmed: false, } : await ordinaryLaunchPaths(record); if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) { throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath }); } if (lab && (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath) || isInSteamLibrary(await canonicalCopyPath(dataPath)))) { throw new AppError('launch_copy_in_steam'); } if (copyPathContains(stockPath, dataPath)) throw new AppError('launch_location'); const requestedPort = lab?.port ?? (settings.launchPortMode === 'fixed' ? settings.launchPort : 0); if (requestedPort) update(job, { phase: 'checking', port: requestedPort }); const [copyVersion, stockVersion, games] = await Promise.all([ lab ? readVersion(copyPath, signal) : currentVersion, readVersion(stockPath, signal), gameProcessRunning(signal), ]); signal.throwIfAborted(); if (!copyVersion || copyVersion !== stockVersion) { throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version'); } if (games) throw new AppError('launch_game_running'); const port = await selectPort(requestedPort); return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port }; } async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, autoSaveBackups: boolean): Promise { const signal = job.stop.signal; const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan; if (autoSaveBackups) { for (const { userId } of new AccountStore(dataPath).all()) { signal.throwIfAborted(); await saveBackup({ ...record, dataPath }, userId, 'launch'); } } signal.throwIfAborted(); update(job, { phase: 'building', port }); const buildStart = Date.now(); let writtenFiles = 0; await buildCopy({ kind: 'build', stockPath, copyPath, dataPath, port, steamLibraryConfirmed, ...resourcePaths(), ...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}), acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), }, signal, (filesWritten, filesTotal, file) => { writtenFiles = filesWritten; if (!signal.aborted) update(job, { phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }), }); }); console.info(`[launch] prepared ${writtenFiles} game files for port ${port} in ${Date.now() - buildStart} ms`); } async function readVersion(folder: string, signal: AbortSignal): Promise { try { return executableVersion(await readFile(join(folder, GAME_FILES.executable), { signal })); } catch (error) { signal.throwIfAborted(); console.warn('[launch] reading the game version failed:', folder, error); return null; } } async function selectPort(port: number): Promise { return new Promise((resolve, reject) => { const listener = createServer(); listener.once('error', (error: NodeJS.ErrnoException) => reject( error.code === 'EADDRINUSE' ? new AppError('launch_port_busy') : error, )); listener.listen(port, LOOPBACK, () => { const address = listener.address(); listener.close((error) => { if (error) reject(error); else if (address && typeof address === 'object') resolve(address.port); else reject(new AppError('launch_server_failed')); }); }); }); }