Files
WT-Offline/apps/server/src/server.ts
T
N0VAN0M4LY 27fc535301 Split the repository into apps, packages and patches
Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.
2026-11-29 03:20:54 +08:00

193 lines
9.5 KiB
TypeScript

/**
* Assemble the local server: data layer, save layer, rules,
* protocol-layer services, and the single loopback listening port.
*/
import type { Server } from 'node:net';
import { AccountStore } from './accounts/account-store.ts';
import { BattleEconomy } from './battle/battle-economy.ts';
import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
import { BattleSessionStore } from './battle/battle-session-store.ts';
import { actionTable } from './char/actions/action-table.ts';
import { CharService } from './char/char-service.ts';
import { ClanStore } from './clans/clan-store.ts';
import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts';
import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts';
import { DecorShop } from './decor/decor-purchase.ts';
import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts';
import { battleEconomy } from './game-data/datasets/battle-economy.ts';
import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts';
import { researchEfficiency } from './game-data/datasets/research-efficiency.ts';
import { ResearchEfficiency } from './research/research-efficiency.ts';
import { battleStreaks } from './game-data/datasets/battle-streaks.ts';
import { BattleStreaks } from './battle/battle-streaks.ts';
import { BattleLiveLogs } from './battle/battle-live-log.ts';
import { supportPlaneUnits } from './battle/battle-support-planes.ts';
import { clanEconomy } from './game-data/datasets/clan-economy.ts';
import { crewSkillData } from './game-data/datasets/crew-skills.ts';
import { DatasetCache } from './game-data/datasets/dataset-cache.ts';
import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts';
import { externalItemSources } from './game-data/datasets/external-item-sources.ts';
import { itemCatalogue } from './game-data/datasets/item-catalogue.ts';
import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts';
import { shopCountries } from './game-data/datasets/shop-countries.ts';
import { storeBundles } from './game-data/datasets/store-bundles.ts';
import { uiLabels, type UiLabels } from './game-data/datasets/ui-labels.ts';
import { unitNames } from './game-data/datasets/unit-names.ts';
import { unlockPrices } from './game-data/datasets/unlock-prices.ts';
import { vehicleCatalogue, type CatalogueVehicle } from './game-data/datasets/vehicle-catalogue.ts';
import { webIcons } from './game-data/datasets/web-icons.ts';
import { GameFiles } from './game-data/game-files.ts';
import { GameModes } from './game-modes/game-modes.ts';
import { InventoryService } from './inventory/inventory-service.ts';
import { InventoryCatalogue } from './inventory/itemdef-catalogue.ts';
import { MarketplaceService } from './inventory/marketplace-service.ts';
import { TrophyCatalogue } from './inventory/trophy-catalogue.ts';
import { ItemCatalogue } from './items/item-catalogue.ts';
import { LoginService } from './login/login-service.ts';
import { matchingRequests } from './matching/matching-requests.ts';
import type { MatchingService } from './matching/matching-service.ts';
import { setUpProfiles } from './profiles-setup.ts';
import { createPortListener } from './transport/port-listener.ts';
import { Router } from './transport/router.ts';
import { loadOrCreateCredentials } from './transport/tls/tls-certificate.ts';
import { StoreCatalogue } from './store/store-catalogue.ts';
import { StoreService } from './store/store-service.ts';
import { TrafficLog } from './traffic-log/traffic-log.ts';
import { loadTuning, type Tuning } from './tuning/tuning.ts';
import { UnlockShop } from './unlocks/unlock-purchase.ts';
import { GameArtwork } from './web-ui/game-artwork.ts';
import { WebUiService } from './web-ui/web-ui-service.ts';
export interface ServerOptions {
/** The player's game folder; its data packs are read, never written. */
readonly gameFolder: string;
/** Accounts, saves and logs. */
readonly dataFolder: string;
readonly port: number;
/** Start-up progress lines (static data extraction, game modes). */
readonly report?: (line: string) => void;
}
export const LOOPBACK = '127.0.0.1';
export interface RunningServer {
readonly logFolder: string;
close(): Promise<void>;
}
export async function startServer(options: ServerOptions): Promise<RunningServer> {
const report = options.report ?? (() => {});
const gameFiles = new GameFiles(options.gameFolder);
// Static data and stores first, before the port opens.
const datasets = new DatasetCache(options.dataFolder, gameFiles, report);
const gameModes = new GameModes(datasets.load(multiplayerMissions), datasets.load(shopCountries), report);
const accounts = new AccountStore(options.dataFolder);
const tuning = loadTuning(options.dataFolder, report);
const clans = new ClanStore(options.dataFolder, tuning.clans);
const cloudSettings = new CloudSettingsStore(options.dataFolder);
const vehicles = datasets.load(vehicleCatalogue);
const spawnRules = datasets.load(battleSpawnRules);
const economyData = datasets.load(battleEconomy);
const efficiencyData = datasets.load(researchEfficiency);
const streakDefinitions = datasets.load(battleStreaks);
const labels = datasets.load(uiLabels);
const { profiles, research, equipment, repair } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels);
const storeProducts = catalogues.store.allProducts();
const artwork = new GameArtwork(options.gameFolder, {
vehicles: storeProducts.flatMap((product) => product.vehicles?.map((vehicle) => vehicle.name) ?? []),
groups: storeProducts.flatMap((product) => product.artworkGroup ? [product.artworkGroup] : []),
listings: catalogues.inventory.marketplaceListings(),
}, report);
const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder, artwork);
gameFiles.releasePacks();
let matching: MatchingService | undefined;
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules);
const economy = new BattleEconomy(
economyData,
tuning.battleEconomy,
{ silverLions: tuning.battle.rewardMultiplierSilverLions, researchPoints: tuning.battle.rewardMultiplierResearchPoints },
new Set(vehicles.filter((vehicle) => vehicle.goldenEagles > 0 || vehicle.premiumPack).map((vehicle) => vehicle.name)),
);
const streaks = new BattleStreaks(streakDefinitions, vehicles, economy);
const supportPlanes = supportPlaneUnits(spawnRules);
const router = new Router([
webUi,
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace),
new InventoryService(accounts, profiles, catalogues.inventory),
new LoginService(accounts),
new CharService(actionTable({
profiles,
accounts,
research,
equipment,
repair,
...catalogues,
clans: { store: clans, economy: squadronEconomy },
cloudSettings,
battle: { sessions: battleSessions, economy, efficiency: new ResearchEfficiency(efficiencyData, research.techTree), streaks, supportPlanes },
notifyInventoryChanged,
})),
new DownloadableContentService(),
]);
const log = new TrafficLog(options.dataFolder);
const listener = createPortListener(
router,
matchingRequests({
gameModes,
accounts,
battle: {
gameModes,
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
economy,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
},
battleLive: { sessions: battleSessions, liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept), streaks, supportPlanes },
}),
log,
loadOrCreateCredentials(options.dataFolder),
);
matching = listener.matching;
await listen(listener.server, options.port);
return {
logFolder: log.folder,
close: () => new Promise((resolve) => {
listener.server.close(() => resolve());
listener.destroyConnections();
}),
};
}
function loadDomainCatalogues(datasets: DatasetCache, tuning: Tuning, vehicles: readonly CatalogueVehicle[], labels: UiLabels) {
const classicItemDefs = datasets.load(itemCatalogue);
const localizedUnitNames = datasets.load(unitNames);
return {
crew: new CrewSkillCatalogue(datasets.load(crewSkillData)),
decor: new DecorShop(datasets.load(decorCatalogue)),
unlocks: new UnlockShop(datasets.load(unlockPrices)),
items: new ItemCatalogue(classicItemDefs, tuning.limits.itemPiecesPerPurchase),
store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store),
inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning),
trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies),
clanEconomy: datasets.load(clanEconomy),
};
}
function listen(server: Server, port: number): Promise<void> {
return new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, LOOPBACK, () => {
server.off('error', reject);
resolve();
});
});
}