363 lines
13 KiB
TypeScript
363 lines
13 KiB
TypeScript
/**
|
|
* Experimental server-side JS/TS mod runtime.
|
|
*
|
|
* Loads each enabled mod's server script entry (`.ts`, `.mjs`, or `.js` via Node 24's built-in
|
|
* TypeScript stripping and ESM dynamic import), injects an isolated `WtoServerModContext`, and
|
|
* coordinates lifecycle hooks, profile/battle hooks, char/matching wrappers, and `/mods/<id>/*`
|
|
* HTTP routes.
|
|
*/
|
|
import { join } from 'node:path';
|
|
import { pathToFileURL } from 'node:url';
|
|
import type { BlkBlock } from '@wto/blk';
|
|
import {
|
|
MOD_API_VERSION,
|
|
type BattleFilterMissionsContext,
|
|
type BattleLiveFactContext,
|
|
type BattleMatchmakeContext,
|
|
type BattleMissionCandidate,
|
|
type BattleSettlementContext,
|
|
type DiscoveredMod,
|
|
type ModCharHandler,
|
|
type ModCharRequest,
|
|
type ModCharResponse,
|
|
type ModCharWrapper,
|
|
type ModHttpHandler,
|
|
type ModMatchingHandler,
|
|
type ModMatchingRequest,
|
|
type ModMatchingWrapper,
|
|
type ServerModCataloguesView,
|
|
type ServerModDatasetsView,
|
|
type WtoServerMod,
|
|
type WtoServerModContext,
|
|
} from '@wto/mods';
|
|
import type { MatchingRequestHandler, MatchingRequestTable } from '../matching/matching-requests.ts';
|
|
import { buildModHttpRoute, ModHttpService, type RegisteredModHttpRoute } from './mod-http-service.ts';
|
|
import { createModStorage } from './mod-storage.ts';
|
|
|
|
interface RuntimeInitOptions {
|
|
readonly mods: readonly DiscoveredMod[];
|
|
readonly gameFolder: string;
|
|
readonly dataFolder: string;
|
|
readonly port: number;
|
|
readonly report: (line: string) => void;
|
|
}
|
|
|
|
interface ScopedHandler<T> {
|
|
readonly modId: string;
|
|
readonly fn: T;
|
|
}
|
|
|
|
export class ServerModRuntime {
|
|
readonly #report: (line: string) => void;
|
|
readonly #loadedModIds: string[] = [];
|
|
readonly #onDatasetsLoaded: ScopedHandler<(datasets: ServerModDatasetsView) => void | Promise<void>>[] = [];
|
|
readonly #onCataloguesReady: ScopedHandler<(catalogues: ServerModCataloguesView) => void | Promise<void>>[] = [];
|
|
readonly #onServerListening: ScopedHandler<(info: { readonly port: number }) => void | Promise<void>>[] = [];
|
|
readonly #onServerClosing: ScopedHandler<() => void | Promise<void>>[] = [];
|
|
readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = [];
|
|
readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = [];
|
|
readonly #onFilterMissions: ScopedHandler<(ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void>[] = [];
|
|
readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = [];
|
|
readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = [];
|
|
readonly #charHandlers = new Map<string, ScopedHandler<ModCharHandler>>();
|
|
readonly #charWrappers = new Map<string, ScopedHandler<ModCharWrapper>[]>();
|
|
readonly #matchingHandlers = new Map<string, ScopedHandler<ModMatchingHandler>>();
|
|
readonly #matchingWrappers = new Map<string, ScopedHandler<ModMatchingWrapper>[]>();
|
|
readonly #httpRoutes: RegisteredModHttpRoute[] = [];
|
|
|
|
private constructor(report: (line: string) => void) {
|
|
this.#report = report;
|
|
}
|
|
|
|
static async load(options: RuntimeInitOptions): Promise<ServerModRuntime> {
|
|
const runtime = new ServerModRuntime(options.report);
|
|
const scriptMods = options.mods.filter((mod) => mod.content.serverEntry !== undefined);
|
|
if (scriptMods.length === 0) return runtime;
|
|
|
|
const cacheBust = Date.now();
|
|
for (const mod of scriptMods) {
|
|
const entryRel = mod.content.serverEntry!;
|
|
const entryAbs = join(mod.rootDir, ...entryRel.split('/'));
|
|
const modId = mod.manifest.id;
|
|
const url = `${pathToFileURL(entryAbs).href}?wto_mod=${cacheBust}`;
|
|
|
|
let loadedModule: Record<string, unknown>;
|
|
try {
|
|
loadedModule = (await import(url)) as Record<string, unknown>;
|
|
} catch (error) {
|
|
throw new Error(
|
|
`Failed to load server mod "${modId}" (${entryRel}): ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
|
|
);
|
|
}
|
|
|
|
const modExport = resolveModExport(loadedModule);
|
|
if (!modExport) {
|
|
throw new Error(
|
|
`Server mod "${modId}" (${entryRel}) must export default { setup(ctx) { ... } } or named setup(ctx)`,
|
|
);
|
|
}
|
|
|
|
const ctx = runtime.#createContext(mod, options);
|
|
try {
|
|
await modExport.setup(ctx);
|
|
} catch (error) {
|
|
throw new Error(
|
|
`Server mod "${modId}" setup() failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
|
|
);
|
|
}
|
|
runtime.#loadedModIds.push(modId);
|
|
options.report(`mod ${modId}: server script loaded (${entryRel})`);
|
|
}
|
|
return runtime;
|
|
}
|
|
|
|
get loadedModIds(): readonly string[] {
|
|
return this.#loadedModIds;
|
|
}
|
|
|
|
async runDatasetsLoaded(view: ServerModDatasetsView): Promise<void> {
|
|
for (const { modId, fn } of this.#onDatasetsLoaded) {
|
|
try {
|
|
await fn(view);
|
|
} catch (error) {
|
|
throw new Error(`Server mod "${modId}" onDatasetsLoaded failed: ${formatError(error)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
async runCataloguesReady(view: ServerModCataloguesView): Promise<void> {
|
|
for (const { modId, fn } of this.#onCataloguesReady) {
|
|
try {
|
|
await fn(view);
|
|
} catch (error) {
|
|
throw new Error(`Server mod "${modId}" onCataloguesReady failed: ${formatError(error)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
async runServerListening(port: number): Promise<void> {
|
|
for (const { modId, fn } of this.#onServerListening) {
|
|
try {
|
|
await fn({ port });
|
|
} catch (error) {
|
|
this.#report(`[mod:${modId}] onServerListening error: ${formatError(error)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
async runServerClosing(): Promise<void> {
|
|
for (const { modId, fn } of [...this.#onServerClosing].reverse()) {
|
|
try {
|
|
await fn();
|
|
} catch (error) {
|
|
this.#report(`[mod:${modId}] onServerClosing error: ${formatError(error)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
runProfileRefresh(profile: BlkBlock, userId: string): void {
|
|
for (const { modId, fn } of this.#onProfileRefresh) {
|
|
try {
|
|
fn(profile, userId);
|
|
} catch (error) {
|
|
this.#report(`[mod:${modId}] profile.onRefresh error: ${formatError(error)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
runBattleBeforeMatchmake(ctx: BattleMatchmakeContext): void {
|
|
for (const { modId, fn } of this.#onBeforeMatchmake) {
|
|
try {
|
|
fn(ctx);
|
|
} catch (error) {
|
|
this.#report(`[mod:${modId}] battle.onBeforeMatchmake error: ${formatError(error)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
runBattleFilterMissions<T extends BattleMissionCandidate>(
|
|
ctx: Omit<BattleFilterMissionsContext, 'missions'> & { readonly missions: readonly T[] },
|
|
): readonly T[] {
|
|
if (this.#onFilterMissions.length === 0) return ctx.missions;
|
|
let current: readonly T[] = ctx.missions;
|
|
for (const { modId, fn } of this.#onFilterMissions) {
|
|
try {
|
|
const next = fn({ ...ctx, missions: current });
|
|
if (Array.isArray(next)) {
|
|
const allowed = new Set(next.map((item) => item.name));
|
|
const filtered = current.filter((item) => allowed.has(item.name));
|
|
if (filtered.length > 0) {
|
|
current = filtered;
|
|
} else {
|
|
this.#report(`[mod:${modId}] battle.onFilterMissions returned 0 matching candidates for ${ctx.modeName}; keeping previous pool`);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
this.#report(`[mod:${modId}] battle.onFilterMissions error: ${formatError(error)}`);
|
|
}
|
|
}
|
|
return current;
|
|
}
|
|
|
|
runBattleLiveFact(ctx: BattleLiveFactContext): void {
|
|
for (const { modId, fn } of this.#onLiveFact) {
|
|
try {
|
|
fn(ctx);
|
|
} catch (error) {
|
|
this.#report(`[mod:${modId}] battle.onLiveFact error: ${formatError(error)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
runBattleAfterSettle(ctx: BattleSettlementContext): void {
|
|
for (const { modId, fn } of this.#onAfterSettle) {
|
|
try {
|
|
fn(ctx);
|
|
} catch (error) {
|
|
this.#report(`[mod:${modId}] battle.onAfterSettle error: ${formatError(error)}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
hasCharOverride(action: string): boolean {
|
|
return this.#charHandlers.has(action) || this.#charWrappers.has(action);
|
|
}
|
|
|
|
async dispatchCharOverride(
|
|
action: string,
|
|
request: ModCharRequest,
|
|
baseDispatch: (req: ModCharRequest) => Promise<ModCharResponse>,
|
|
): Promise<ModCharResponse> {
|
|
const custom = this.#charHandlers.get(action);
|
|
const terminal: (req: ModCharRequest) => Promise<ModCharResponse> = custom
|
|
? async (req) => await custom.fn(req)
|
|
: baseDispatch;
|
|
|
|
const wrappers = this.#charWrappers.get(action);
|
|
if (!wrappers || wrappers.length === 0) return terminal(request);
|
|
|
|
let chain = terminal;
|
|
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
|
|
const wrapper = wrappers[i]!.fn;
|
|
const next = chain;
|
|
chain = async (req) => await wrapper(req, next);
|
|
}
|
|
return chain(request);
|
|
}
|
|
|
|
applyMatchingRoutes(baseTable: MatchingRequestTable): MatchingRequestTable {
|
|
if (this.#matchingHandlers.size === 0 && this.#matchingWrappers.size === 0) {
|
|
return baseTable;
|
|
}
|
|
const merged = new Map<string, MatchingRequestHandler>(baseTable);
|
|
|
|
for (const [method, custom] of this.#matchingHandlers) {
|
|
merged.set(method, (request, session) => custom.fn({
|
|
method,
|
|
params: request.params,
|
|
userId: session.authenticatedUserId(),
|
|
}));
|
|
}
|
|
|
|
for (const [method, wrappers] of this.#matchingWrappers) {
|
|
const original = merged.get(method);
|
|
merged.set(method, (request, session) => {
|
|
const baseFn = (req: ModMatchingRequest): Record<string, unknown> => (
|
|
original ? original({ ...request, params: req.params }, session) : {}
|
|
);
|
|
let chain = baseFn;
|
|
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
|
|
const wrap = wrappers[i]!.fn;
|
|
const next = chain;
|
|
chain = (req) => wrap(req, next);
|
|
}
|
|
return chain({
|
|
method,
|
|
params: request.params,
|
|
userId: session.authenticatedUserId(),
|
|
});
|
|
});
|
|
}
|
|
|
|
return merged;
|
|
}
|
|
|
|
httpService(): ModHttpService {
|
|
return new ModHttpService(this.#httpRoutes);
|
|
}
|
|
|
|
#createContext(mod: DiscoveredMod, options: RuntimeInitOptions): WtoServerModContext {
|
|
const modId = mod.manifest.id;
|
|
return {
|
|
apiVersion: MOD_API_VERSION,
|
|
manifest: mod.manifest,
|
|
modDir: mod.rootDir,
|
|
gameFolder: options.gameFolder,
|
|
dataFolder: options.dataFolder,
|
|
port: options.port,
|
|
logger: {
|
|
info: (message) => options.report(`[mod:${modId}] ${message}`),
|
|
warn: (message) => options.report(`[mod:${modId}] WARN: ${message}`),
|
|
error: (message) => options.report(`[mod:${modId}] ERROR: ${message}`),
|
|
},
|
|
storage: createModStorage(options.dataFolder, modId),
|
|
hooks: {
|
|
onDatasetsLoaded: (fn) => { this.#onDatasetsLoaded.push({ modId, fn }); },
|
|
onCataloguesReady: (fn) => { this.#onCataloguesReady.push({ modId, fn }); },
|
|
onServerListening: (fn) => { this.#onServerListening.push({ modId, fn }); },
|
|
onServerClosing: (fn) => { this.#onServerClosing.push({ modId, fn }); },
|
|
profile: {
|
|
onRefresh: (fn) => { this.#onProfileRefresh.push({ modId, fn }); },
|
|
},
|
|
battle: {
|
|
onBeforeMatchmake: (fn) => { this.#onBeforeMatchmake.push({ modId, fn }); },
|
|
onFilterMissions: (fn) => { this.#onFilterMissions.push({ modId, fn }); },
|
|
onLiveFact: (fn) => { this.#onLiveFact.push({ modId, fn }); },
|
|
onAfterSettle: (fn) => { this.#onAfterSettle.push({ modId, fn }); },
|
|
},
|
|
},
|
|
routes: {
|
|
char: {
|
|
register: (action, fn) => { this.#charHandlers.set(action, { modId, fn }); },
|
|
wrap: (action, fn) => {
|
|
const list = this.#charWrappers.get(action) ?? [];
|
|
list.push({ modId, fn });
|
|
this.#charWrappers.set(action, list);
|
|
},
|
|
},
|
|
matching: {
|
|
register: (method, fn) => { this.#matchingHandlers.set(method, { modId, fn }); },
|
|
wrap: (method, fn) => {
|
|
const list = this.#matchingWrappers.get(method) ?? [];
|
|
list.push({ modId, fn });
|
|
this.#matchingWrappers.set(method, list);
|
|
},
|
|
},
|
|
http: {
|
|
register: (subPath: string, handler: ModHttpHandler) => {
|
|
this.#httpRoutes.push(buildModHttpRoute(modId, subPath, handler));
|
|
},
|
|
},
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
function resolveModExport(mod: Record<string, unknown>): WtoServerMod | undefined {
|
|
const def = mod.default;
|
|
if (def && typeof def === 'object' && typeof (def as Record<string, unknown>).setup === 'function') {
|
|
return def as WtoServerMod;
|
|
}
|
|
if (typeof def === 'function') {
|
|
return { setup: def as WtoServerMod['setup'] };
|
|
}
|
|
if (typeof mod.setup === 'function') {
|
|
return { setup: mod.setup as WtoServerMod['setup'] };
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function formatError(error: unknown): string {
|
|
return error instanceof Error ? error.stack ?? error.message : String(error);
|
|
}
|