feat(launcher): add the launcher application skeleton

The installer and launcher is an Electron app in apps/launcher: main
process, a sandboxed preload that only forwards allowed channels, and a
React window translated into Chinese and English.

Every renderer -> main call is declared once in the IPC contract
(shared/ipc/contract.ts) with zod schemas for its input and output; the
main side validates both when it registers a handler. The main process
throws error codes only, and the window translates them. The launcher's
own settings (for now the window language) are kept in the user data
folder and written through a temporary file and a rename. Development
runs can point the user data folder elsewhere with
WTO_LAUNCHER_USER_DATA.

The workspace packages (@wto/patcher, @wto/server) stay external to the
bundle: they ship as TypeScript sources and will run in utility
processes, where Electron's Node strips the types and they find their
web pages, tuning and keys next to their sources as they do today.

The root typecheck leaves out the launcher, which has its own tsconfig
files for the main process and the window.

Checked with the launcher typecheck, electron-vite build, the root
typecheck, and a start on a scratch user data folder.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 03:22:38 +08:00
1 parent 930ea07630
commit 70d59d7bf7
30 files changed
+3484 -1

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
import { app } from 'electron';
import { registerIpcHandlers } from './ipc/handlers.ts';
import { createMainWindow, showMainWindow } from './services/main-window.ts';
/**
* Main process entry. Order:
* 1. the user data folder (a scratch folder for development runs) and the single-instance lock;
* 2. IPC handlers;
* 3. the window.
*/
// Development runs point this at a scratch folder so they never touch a real installation's
// settings (it also gives them their own single-instance lock).
const userDataOverride = process.env['WTO_LAUNCHER_USER_DATA'];
if (userDataOverride) app.setPath('userData', userDataOverride);
if (process.platform === 'win32') app.setAppUserModelId('com.wtoffline.launcher');
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
app.on('second-instance', () => showMainWindow());
app.on('window-all-closed', () => app.quit());
// A top-level await on whenReady deadlocks an ESM main entry on Windows.
void app.whenReady().then(() => {
registerIpcHandlers();
createMainWindow();
});
}
+20
View File
@@ -0,0 +1,20 @@
import { app } from 'electron';
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
import { broadcast, handle } from './register.ts';
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
export function registerIpcHandlers(): void {
handle('app:getInfo', () => ({
version: app.getVersion(),
electron: process.versions.electron,
systemLocale: app.getLocale(),
userDataPath: app.getPath('userData'),
}));
handle('settings:get', () => getSettings());
handle('settings:update', async (patch) => {
const settings = await updateSettings(patch);
broadcast('event:settings-changed', settings);
return settings;
});
}
+42
View File
@@ -0,0 +1,42 @@
import { BrowserWindow, ipcMain, type WebContents } from 'electron';
import { AppError } from '@shared/errors.ts';
import {
ipcContract,
ipcEvents,
type IpcChannel,
type IpcEventChannel,
type IpcEventPayload,
type IpcOutput,
type IpcParsedInput,
} from '@shared/ipc/contract.ts';
/**
* Typed IPC on the main side.
* handle(): registers the handler of a contract channel; its input and its output are validated
* against the contract.
* broadcast(): sends a contract event to every window, validated the same way.
*/
export function handle<C extends IpcChannel>(
channel: C,
handler: (input: IpcParsedInput<C>, sender: WebContents) => Promise<IpcOutput<C>> | IpcOutput<C>,
): void {
ipcMain.handle(channel, async (event, rawInput: unknown) => {
const schema = ipcContract[channel];
const input = schema.input.parse(rawInput) as IpcParsedInput<C>;
const result = await handler(input, event.sender);
// An output that breaks the contract is our bug. Keep the details in the log and give the
// window a code it can show.
const checked = schema.output.safeParse(result);
if (!checked.success) {
console.error(`[ipc] ${channel} returned an unexpected shape:`, checked.error.issues);
throw new AppError('internal_error', { detail: channel });
}
return checked.data;
});
}
export function broadcast<C extends IpcEventChannel>(channel: C, payload: IpcEventPayload<C>): void {
const checked = ipcEvents[channel].parse(payload);
for (const window of BrowserWindow.getAllWindows()) window.webContents.send(channel, checked);
}
@@ -0,0 +1,54 @@
import { rename } from 'node:fs/promises';
import { join } from 'node:path';
import { app } from 'electron';
import { AppError } from '@shared/errors.ts';
import { defaultSettings, SettingsSchema, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
/**
* The launcher's settings file, `<user data>/settings.json`. Read once and cached; every change is
* validated as a whole and written before it is reported back.
*/
let cached: Settings | null = null;
function settingsPath(): string {
return join(app.getPath('userData'), 'settings.json');
}
export async function getSettings(): Promise<Settings> {
if (cached) return cached;
const path = settingsPath();
let raw: unknown = {};
try {
raw = await readJsonOr(path, {});
} catch (error) {
console.warn('[settings] settings.json is unreadable:', error);
}
const parsed = SettingsSchema.safeParse(raw);
if (!parsed.success) {
console.warn('[settings] settings.json did not validate; starting from defaults:', parsed.error.issues);
// Keep the player's file beside the new one instead of overwriting it on the next save.
await rename(path, `${path}.unreadable-${Date.now()}`).catch(() => undefined);
}
cached = parsed.success ? parsed.data : defaultSettings();
return cached;
}
export async function updateSettings(patch: SettingsPatch): Promise<Settings> {
const current = await getSettings();
const merged = SettingsSchema.parse({ ...current, ...definedFields(patch) });
try {
await writeJsonAtomic(settingsPath(), merged);
} catch (error) {
console.error('[settings] write failed:', error);
throw new AppError('settings_write_failed');
}
cached = merged;
return merged;
}
/** The patch without the fields it leaves out, so they do not overwrite current values. */
function definedFields(patch: SettingsPatch): Partial<Settings> {
return Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined)) as Partial<Settings>;
}
@@ -0,0 +1,46 @@
import { join } from 'node:path';
import { BrowserWindow, shell } from 'electron';
/** The launcher's single window. */
let mainWindow: BrowserWindow | null = null;
export function createMainWindow(): BrowserWindow {
const window = new BrowserWindow({
width: 960,
height: 640,
minWidth: 720,
minHeight: 480,
show: false,
autoHideMenuBar: true,
webPreferences: {
preload: join(import.meta.dirname, '../preload/index.cjs'),
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
},
});
window.once('ready-to-show', () => window.show());
// Links leave the launcher for the player's browser; the window itself never navigates away.
window.webContents.setWindowOpenHandler(({ url }) => {
if (/^https?:\/\//.test(url)) void shell.openExternal(url);
return { action: 'deny' };
});
window.webContents.on('will-navigate', (event) => event.preventDefault());
window.on('closed', () => {
if (mainWindow === window) mainWindow = null;
});
const devServer = process.env['ELECTRON_RENDERER_URL'];
if (devServer) void window.loadURL(devServer);
else void window.loadFile(join(import.meta.dirname, '../renderer/index.html'));
mainWindow = window;
return window;
}
/** Brings the window forward, building it again if it was closed. */
export function showMainWindow(): void {
const window = mainWindow ?? createMainWindow();
if (window.isMinimized()) window.restore();
window.focus();
}
@@ -0,0 +1,51 @@
import { randomBytes } from 'node:crypto';
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
/**
* JSON files the launcher keeps: written to a temporary file and renamed over the target, so a
* crash or power loss mid-write never leaves a truncated file.
*/
/** The parsed file, or `fallback` when it does not exist. Any other read error is thrown. */
export async function readJsonOr(path: string, fallback: unknown): Promise<unknown> {
let text: string;
try {
text = await readFile(path, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return fallback;
throw error;
}
return JSON.parse(text) as unknown;
}
export async function writeJsonAtomic(path: string, value: unknown): Promise<void> {
await mkdir(dirname(path), { recursive: true });
// A random suffix keeps two writes of the same file from renaming each other's halves.
const temporary = `${path}.${randomBytes(4).toString('hex')}.tmp`;
await writeFile(temporary, JSON.stringify(value, null, 2) + '\n', 'utf8');
try {
await renameWithRetry(temporary, path);
} catch (error) {
await unlink(temporary).catch(() => undefined);
throw error;
}
}
/**
* A virus scanner or the search indexer can hold a just-written file open for a moment, and the
* rename over it then fails with EPERM, EACCES or EBUSY. Retry those briefly.
*/
async function renameWithRetry(from: string, to: string, attempts = 6): Promise<void> {
for (let attempt = 1; ; attempt++) {
try {
await rename(from, to);
return;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
const transient = code === 'EPERM' || code === 'EACCES' || code === 'EBUSY';
if (!transient || attempt >= attempts) throw error;
await new Promise((resolve) => setTimeout(resolve, 20 * attempt));
}
}
}