docs(mods): fix schema errors and expand bilingual mod handbook to full parity

Fix store.jsonc vehiclePacks nesting and gjn field name, matchingApiFunc callback argument order, and DaGui CSS @import/lowercase rules; add stock archive inspection steps, BR-to-mrank table, cloned vehicle walkthrough, tuning field reference, and official-map-selector full-stack trace while bringing en/01..07.md to full 1:1 parity with zh-CN/.
This commit is contained in:
N0VAN0M4LY committed 2026-12-03 11:25:54 +08:00
1 parent e79866b96e
commit a2fdcc1f15
15 files changed
+2320 -468

No files matched your search

+250 -25
View File
@@ -1,40 +1,265 @@
# 06 · Server JS/TS Scripting API Reference
> **Experimental Warning (API `0.1-experimental`)**: All server script contracts, internal catalogue classes, and hook shapes are unstable and may change across releases without backwards compatibility.
> **Experimental Warning (API `0.1-experimental`)**
> All server scripting interfaces and internal catalogue objects documented here are in early active development and may change across WTOffline releases without backwards compatibility.
## 1. Runtime & TypeScript Rules
---
Server scripts run inside Electron 43's bundled **Node.js 24** with built-in TypeScript type stripping (`erasableSyntaxOnly` syntax: no `enum`, `namespace`, or parameter properties). Pre-bundled `.mjs` / `.js` files are also supported.
## 1. Runtime Environment, Node 24 Erasable TS Rules & VS Code Autocomplete
Default entry lookup order: `server/index.ts` → `server/index.mjs` → `server/index.js` (or explicit `server.entry` in `mod.jsonc`).
The local server runs inside the launcher's bundled **Electron 43 / Node.js 24** runtime with **native TypeScript type stripping enabled**—players do not need Node.js or TypeScript installed on their PCs to run your `.ts` scripts directly!
- **Default entry lookup order**: `server/index.ts` → `server/index.mjs` → `server/index.js` (or override via `server.entry` in `mod.jsonc`);
- **Third-party npm packages or non-erasable syntax**: if needed, bundle your code ahead of time into a single-file `server/index.mjs` with `esbuild` or `tsc`.
### 1.1 Raw `.ts` Syntax Rule (`erasableSyntaxOnly` Do vs Don't)
Node 24's built-in TypeScript stripper erases type annotations without emitting extra runtime JS code. All `interface`, `type`, generic, and `as` constructs work natively, **except `enum`, `namespace`, and constructor parameter properties (`constructor(private x: number)`)**:
```ts
// ❌ DON'T: Node 24 native TS stripping rejects `enum` at startup!
enum FilterMode { All = 'all', Include = 'include', Exclude = 'exclude' }
// ✅ DO: Use an `as const` object + union type (zero runtime overhead, 100% compatible!)
const FILTER_MODE = { All: 'all', Include: 'include', Exclude: 'exclude' } as const;
type FilterMode = (typeof FILTER_MODE)[keyof typeof FILTER_MODE];
```
### 1.2 How External Modders Get Full VS Code Autocomplete
Download `packages/mods/src/server-api.ts` (along with its sibling `types.ts`) from the WTOffline repository into your mod's `server/` folder and import types using **`import type`**:
```ts
// ✅ DO: `import type` is completely erased by Node 24 at runtime while giving full VS Code IntelliSense!
import type { WtoServerModContext } from './server-api.ts';
// ❌ Avoid value-importing `@wto/mods` at runtime (external mod folders do not have monorepo node_modules)
// import { something } from '@wto/mods';
export default {
async setup(ctx) {
async setup(ctx: WtoServerModContext) {
ctx.logger.info('mod initialized');
},
};
```
Full TypeScript definitions live in `packages/mods/src/server-api.ts`.
> Tip: Alongside `export default { setup(ctx) { ... } }`, the runtime also accepts `export default function (ctx) { ... }` or a named `export function setup(ctx) { ... }`. You can also declare lightweight structural `interface` views directly at the top of `server/index.ts` (just like `templates/official-map-selector/server/index.ts`) for a zero-dependency single file.
## 2. `WtoServerModContext`
---
- `apiVersion`, `manifest`, `modDir`, `gameFolder`, `dataFolder`, `port`
- `logger`: `{ info(msg), warn(msg), error(msg) }` (prefixed with `[mod:<id>]`)
- `storage`:
- `storage.forPlayer(userId)` → atomic JSON file under `<dataFolder>/saves/<userId>/mods/<modId>.json` (never mutate stock `profile.blk` with custom keys)
- `storage.shared()` → `<dataFolder>/mods-data/<modId>.json`
- `hooks`:
- `onDatasetsLoaded(datasets)` — inspect/mutate `vehicles`, `battleEconomy`, `battleSpawnRules`, `multiplayerMissions`, `uiLabels`, `unitNames`, or `get(id)` / `set(id, value)`
- `onCataloguesReady(catalogues)` — access `tuning`, `gameModes`, `profiles`, `accounts`, `research`, `equipment`, `repair`, `store`, `inventory`, `trophies`, `items`, `crew`, `decor`, `unlocks`, `clans`, `battleMatchmaker`, `battleEconomy`, `battleStreaks`, `notifyInventoryChanged()`, `notifyUser(userId, eventName, payload)`
- `onServerListening({ port })` / `onServerClosing()`
- `profile.onRefresh(profile, userId)`
- `battle.onBeforeMatchmake({ userId, eventName, request })`
- `battle.onFilterMissions({ userId, modeId, modeName, economicName, minMrank, maxMrank, missions })` — return a filtered/reordered subset of candidate missions (empty results safely fall back to the prior pool)
- `battle.onLiveFact({ userId, roomId, fact })`
- `battle.onAfterSettle({ userId, roomId, summary })`
- `routes`:
- `routes.char.register(action, handler)` / `routes.char.wrap(action, wrapper)`
- `routes.matching.register(method, handler)` / `routes.matching.wrap(method, wrapper)` (callable from client Quirrel via `matchingApiFunc`)
- `routes.http.register(subPath, handler)` — automatically namespaced under `/mods/<modId>/...` (supports exact paths and `/*` wildcards)
## 2. `WtoServerModContext` Property Reference
| Property | Type | Description |
| --- | --- | --- |
| `ctx.apiVersion` | `string` | Active experimental API tag (`"0.1-experimental"`) |
| `ctx.manifest` | `ModManifest` | Parsed `mod.jsonc` manifest of this mod |
| `ctx.modDir` | `string` | Absolute path to this mod's root directory (read static mod files via `node:fs`) |
| `ctx.gameFolder` | `string` | Active offline game copy root directory |
| `ctx.dataFolder` | `string` | Active client data folder (saves, caches, logs) |
| `ctx.port` | `number` | Bound local server port for the current session |
| `ctx.logger` | `{ info, warn, error }` | Logger prefixed with `[mod:<id>]`, written to `launcher.log` and diagnostic exports |
| `ctx.storage` | `ModStorageApi` | Atomic JSON storage scoped per player or shared across accounts (Section 3) |
| `ctx.hooks` | `ServerModHooksApi` | Lifecycle, profile, matchmaking, and battle settlement hooks (Section 4) |
| `ctx.routes` | `ServerModRoutesApi` | `matching`, `http`, and `char` route extensions (Section 5) |
---
## 3. Isolated Mod Storage (`ctx.storage`)
**Recommended practice**: Keep custom mod data out of the player's `profile.blk` (non-stock keys can interfere with client serialization and remain behind after a mod is removed). Store mod state, settings, and progression in `ctx.storage`:
```ts
// ① Scoped per local player account: <dataFolder>/saves/<userId>/mods/<modId>.json
const playerStore = ctx.storage.forPlayer(userId);
const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 };
playerStore.write({ wins: prev.wins + 1 }); // Atomic temp-file rename write
// playerStore.remove();
// ② Shared across all accounts for this mod: <dataFolder>/mods-data/<modId>.json
const sharedStore = ctx.storage.shared();
```
---
## 4. Lifecycle, Profile & Battle Hooks (`ctx.hooks`)
### 4.1 `ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })`
Fires after static datasets are extracted from the overlaid `.vromfs.bin` packs and before domain catalogues are constructed. Inspect or mutate:
- `datasets.vehicles`: vehicle array (`CatalogueVehicle[]` with prices, RP, BRs, tech-tree links)
- `datasets.battleEconomy`: battle action reward rates and per-vehicle multipliers
- `datasets.battleSpawnRules`: spawn costs, support planes, and spawn rules
- `datasets.multiplayerMissions`: `{ categories, missions }` mission metadata
- `datasets.uiLabels` / `datasets.unitNames`: localized UI strings and vehicle names
- `datasets.get(datasetId)` / `datasets.set(datasetId, value)`: read or replace any raw dataset by ID
### 4.2 `ctx.hooks.onCataloguesReady(async (catalogues) => { ... })`
Fires after all domain catalogues and services are assembled, right before the server starts listening:
- `catalogues.tuning`: merged read-only `Tuning`
- `catalogues.gameModes`: `GameModes` instance (`ids()`, `byId(id)`, `byName(name)`, `byEconomicName(name)`, `countries()`)
- `catalogues.profiles` / `accounts` / `research` / `equipment` / `repair`
- `catalogues.store` / `inventory` / `trophies` / `items` / `crew` / `decor` / `unlocks` / `clans`
- `catalogues.battleMatchmaker` / `battleEconomy` / `battleStreaks`
- `catalogues.notifyInventoryChanged()`: push live external-inventory refresh to connected clients
- `catalogues.notifyUser(userId, eventName, payload)`: send a live `mrpc.generic_notify` event to a logged-in player
### 4.3 `ctx.hooks.onServerListening(({ port }) => { ... })` / `onServerClosing(() => { ... })`
Fires once the HTTP/matching port is listening, and in reverse mod order right before shutdown (ideal for logging URLs or clearing timers).
### 4.4 Profile Hook: `ctx.hooks.profile.onRefresh((profile, userId) => { ... })`
Fires whenever a player profile is loaded or updated and finishes the native refresh pipeline (`profile` is an `@wto/blk` `BlkBlock`). Read profile facts here and persist derived mod state in `ctx.storage.forPlayer(userId)`.
### 4.5 Matchmaking & Battle Hooks (`ctx.hooks.battle`)
#### ① `ctx.hooks.battle.onBeforeMatchmake(({ userId, eventName, request }) => { ... })`
Fires when the player clicks **To Battle!** (`match.enqueue`) before `BattleMatchmaker` runs; `request` holds the raw client enqueue parameters.
#### ② `ctx.hooks.battle.onFilterMissions((ctx) => { ... })`
Fires after `BattleMatchmaker` narrows candidate two-sided missions for the chosen mode and BR window, right before random map selection:
- `ctx`: `{ userId, modeId, modeName, economicName, minMrank, maxMrank, missions }`;
- Each `mission` has `{ name, path, level?, type?, locName?, postfix? }`;
- **Return value**: return your filtered subset array (or `undefined` to leave unchanged). If an empty array `[]` is returned, the server logs a warning and safely falls back to the previous candidate pool so matchmaking never deadlocks.
```ts
// Example: restrict matches to maps whose level path or name matches poland or berlin
ctx.hooks.battle.onFilterMissions(({ missions }) => {
const picked = missions.filter((m) => /poland|berlin/i.test(m.level ?? m.name));
return picked.length > 0 ? picked : undefined;
});
```
#### ③ `ctx.hooks.battle.onLiveFact(({ userId, roomId, fact }) => { ... })`
Fires live during a running LocalMP battle whenever the client reports a `wto_battle.fact` event (`roomId` is the 16-character hex `sessionId`). `fact` always carries `{ sessionId, localPlayerId, localTeam, kind }` plus fields determined by `fact.kind`:
| `fact.kind` | When It Fires | Additional `fact` Fields |
| --- | --- | --- |
| `"event"` | Local player scores a kill, assist, capture, hit, or award event | `{ time, unit, code, expClass, victim, victimIsPlayer, friendly, modifier, damage }` |
| `"life"` | Local player spawn life segment updates or ends in death | `{ unit, start, end, died }` |
| `"kill"` | Any kill appears in the HUD killfeed (including AI-vs-AI kills) | `{ time, killer, killerTeam, victim, victimTeam }` (MPlayer IDs, `-1` if unit has no player) |
| `"strike"` | Local player's nuclear bomb detonates | `{ time }` |
#### ④ `ctx.hooks.battle.onAfterSettle(({ userId, roomId, summary }) => { ... })`
Fires at battle end right after native `settleBattle` applies SL/RP rewards and right before the updated profile is written to disk. `summary` has the exact shape `{ profile, report, session }`:
- `summary.profile`: the player's `BlkBlock` profile with post-battle rewards applied;
- `summary.report`: parsed `BattleReport` (`outcome: 'win' | 'lose' | 'running'`, `localTeam`, `teamAScore`, `teamBScore`, `sessionStart`, `sessionEnd`, `lives`, `events`, `feed`, `players` scoreboard rows, `nuclearStrikes`, `spares`);
- `summary.session`: `BattleSession` metadata (`sessionId`, `roomId`, `modeId`, `modeName`, `economicName`, `difficulty`, `requiredClass`, `missionName`, `country`, etc.).
> Reminder: Persist any custom mod achievements, streaks, or campaign progression in `ctx.storage.forPlayer(userId)` rather than mutating non-stock keys onto `summary.profile`!
---
## 5. Choosing Between the 3 Route Channels & Exact `matchingApiFunc` Signature (`ctx.routes`)
### 5.1 Which Route API Should I Use?
| Route API | Best For | Payload Format | How the Client Calls It |
| --- | --- | --- | --- |
| **`ctx.routes.matching`** *(Recommended)* | Native DaGui `.nut` modals exchanging JSON data with your server script (settings, map rules, custom state) | Plain JSON `params` in → JSON object out | Quirrel `matchingApiFunc("wto_mod.<method>", callback, params)` |
| **`ctx.routes.http`** | Rich HTML/CSS/JS web dashboards, external browser panels, or REST endpoints (auto-namespaced under `/mods/<modId>/...`) | Standard HTTP request / response | System browser or War Thunder's embedded browser at `http://{{LOCAL_ENDPOINT}}/mods/<modId>/...` |
| **`ctx.routes.char`** | Wrapping stock `cln_*` profile actions or adding low-level binary BLK actions | Raw binary/text `Buffer` | Low-level client `char` action requests |
### 5.2 Matching JSON RPC (`ctx.routes.matching`) — Mind the Client Argument Order!
Registering a custom matching RPC on the server takes just a few lines (`req` provides `{ method, params, userId }` and returns any JSON object; `wrap(method, (req, next) => ...)` is also available):
```ts
ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({
ok: true,
userId,
echo: params,
}));
```
> **P0 Gotcha: In Quirrel's `matchingApiFunc`, `callback` Is the 2nd Argument and `params` Is the 3rd Argument!**
> In stock `gui.vromfs.bin` `%scripts/matching/api.nut`, the signature is `function matchingApiFunc(name, cb, params = null)`. Passing `(name, params, callback)` in the wrong order sends empty params and skips your callback.
Correct Quirrel `.nut` call:
```squirrel
from "%scripts/matching/api.nut" import matchingApiFunc
// ✅ Arg 1: RPC method | Arg 2: Callback | Arg 3: Request params table
matchingApiFunc("wto_mod.my_mod.ping",
Callback(@(resp) this.onPingResponse(resp), this),
{
hello = "world"
})
```
### 5.3 Local HTTP & Embedded Browser Routes (`ctx.routes.http`)
Routes are automatically namespaced under **`/mods/<yourModId>/...`** and support both exact paths and `/*` wildcards:
```ts
ctx.routes.http.register('/panel', () => ({
status: 200,
contentType: 'text/html; charset=utf-8',
body: '<!doctype html><meta charset="utf-8"><h1>My Mod Control Panel</h1>',
}));
ctx.routes.http.register('/api/*', (req) => ({
status: 200,
contentType: 'application/json; charset=utf-8',
body: JSON.stringify({ method: req.method, path: req.path, query: req.query }),
}));
```
To open that page inside War Thunder's native embedded browser from a hangar button, use the `{{LOCAL_ENDPOINT}}` placeholder inside a `client/gui-patches/` replacement snippet:
```squirrel
from "%scripts/onlineShop/url.nut" import openUrl
openUrl("http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel", false, false)
```
### 5.4 Char Action Interception & Custom Actions (`ctx.routes.char`)
- `ctx.routes.char.register(action, handler)`: register a brand-new `cln_*` action;
- `ctx.routes.char.wrap(action, async (req, next) => { ... })`: wrap an existing `cln_*` action around `await next(req)`.
---
## 6. Full-Stack Case Study: How `official-map-selector` Connects End to End
Open `mods/official-map-selector/` (source in `mod-dev-docs/templates/official-map-selector/`): it is a complete reference implementation connecting native client UI, matching RPCs, isolated player storage, and server matchmaking hooks across **5 clean layers**:
```text
[1. Minimal Entry Hooks: client/gui-patches/]
├─ gui/gamemodeselect/gamemodeselect.tpl → Inserts the "Custom Map Pool" button into the footer bar
├─ scripts/gamemodes/gamemodeselect.nut → Wires button click to WtoMapSelectorModal.open({ gameMode })
└─ gui/css.css → Appends @import "missions\wtomapselector.css"
│
▼
[2. Standalone Native Modal: client/packs/gui.vromfs.bin/ + lang.vromfs.bin/]
├─ scripts/missions/wtomapselectormodal.nut → Subclasses BaseGuiHandlerWT; renders search, filter tabs & tactical map preview
├─ gui/missions/wtomapselectormodal.tpl → Modal layout & card grid template (wtomapselectorcards.tpl)
├─ gui/missions/wtomapselector.css → Selected card badge & border styling
└─ lang/menu.csv.patch.csv → Localized wto/mapSelector/* UI strings (EN / ZH)
│
▼ matchingApiFunc("wto_mod.map_selector.get" / ".set", Callback(...), { modeName, ... })
[3. Server Matching RPCs: server/index.ts -> ctx.routes.matching.register]
├─ Indexes playable two-sided map pools per PvP mode during onCataloguesReady(catalogues.gameModes)
├─ wto_mod.map_selector.get → Returns the mode's map list + the player's saved filter rule
└─ wto_mod.map_selector.set → Validates & saves the player's all / include / exclude selection
│
▼
[4. Per-Account Isolated Storage: ctx.storage.forPlayer(userId)]
└─ Atomically writes <dataFolder>/saves/<userId>/mods/official.map-selector.json (never touches profile.blk)
│
▼
[5. Matchmaking Map Filter: ctx.hooks.battle.onFilterMissions]
└─ Filters candidate missions by whitelist/blacklist on "To Battle!", falling back to the full pool with a log warning if 0 maps match at that BR
```
Reading `templates/official-map-selector` alongside this diagram gives you a production-tested blueprint for virtually any full-stack WTOffline mod!