Files
WT-Offline/mod-dev-docs/zh-CN/06-server-scripting-api.md

158 lines
8.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 06 · 服务端 JS/TS 脚本完整接口手册
> **实验期警告(API `0.1-experimental`)**
> 本章描述的所有服务端脚本接口与内部对象均处于极初期开发阶段,随时可能随本体开发变动,不保证向后兼容。
---
## 1. 运行环境与语法规则
本地服务器运行在启动器内置的 **Electron 43 / Node.js 24** 上,**原生开启 TypeScript 类型剥离(`strip`)**,玩家电脑无需安装 Node 或 TypeScript。
- **入口探测顺序**:默认依次查找 `server/index.ts` → `server/index.mjs` → `server/index.js`(也可在 `mod.jsonc` 的 `server.entry` 中自定义相对路径);
- **直接写 `.ts` 的语法约定**:遵循 TypeScript 的 `erasableSyntaxOnly` 规则——支持全部类型注解、`interface`、`type`、泛型与 `as`,但**不要使用**需要代码生成的 `enum`、`namespace` 或构造函数参数属性(改用 `as const` 对象与联合类型即可);
- 如果你的项目想使用任意 TS 语法或第三方 npm 包,自行用 esbuild / tsc 打包成单文件 `.mjs` 分发即可。
### 标准导出写法
```ts
export default {
async setup(ctx) {
ctx.logger.info('mod initialized');
// 在此注册钩子、路由与初始化逻辑
},
};
```
(也支持直接导出默认函数 `export default function (ctx) { ... }` 或具名导出 `export function setup(ctx) { ... }`。)
---
## 2. `WtoServerModContext`(注入给 `setup(ctx)` 的上下文对象)
| 属性 | 类型 | 说明 |
| --- | --- | --- |
| `ctx.apiVersion` | `string` | 当前运行时的实验期 API 版本号(`"0.1-experimental"`) |
| `ctx.manifest` | `ModManifest` | 本模组解析后的 `mod.jsonc` 清单对象 |
| `ctx.modDir` | `string` | 本模组根目录的绝对路径(可用 `node:fs` 读取模组自带的配置文件) |
| `ctx.gameFolder` | `string` | 当前运行的离线游戏副本根目录 |
| `ctx.dataFolder` | `string` | 当前客户端的数据目录(含存档、缓存、日志) |
| `ctx.port` | `number` | 本次启动的本地服务器监听端口 |
| `ctx.logger` | `{ info, warn, error }` | 带 `[mod:<id>]` 前缀的日志输出器,自动进入启动器日志与诊断导出 |
| `ctx.storage` | `ModStorageApi` | 按账号隔离或全局共享的独立 JSON 存档区(见第 3 节) |
| `ctx.hooks` | `ServerModHooksApi` | 生命周期、档案、匹配与对局钩子(见第 4 节) |
| `ctx.routes` | `ServerModRoutesApi` | `char`、`matching` 与本地 HTTP 路由扩展(见第 5 节) |
完整 TypeScript 定义源码见仓库 `packages/mods/src/server-api.ts`。
---
## 3. 独立存档区(`ctx.storage`)
**硬性最佳实践**:请勿往原版 `profile.blk` 写入非标准字段(容易影响客户端序列化或卸载模组后污染存档)。统一使用 `ctx.storage`:
```ts
// ① 按本地玩家账号隔离:<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 }); // 原子写盘
// playerStore.remove();
// ② 模组全局共享存储:<dataFolder>/mods-data/<modId>.json
const sharedStore = ctx.storage.shared();
```
---
## 4. 全部生命周期与业务钩子(`ctx.hooks`)
### 4.1 `ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })`
在本地服务器从叠加后的 `.vromfs.bin` 提取完静态数据集、尚未组装业务目录前触发。可读取或原地修改:
- `datasets.vehicles`:载具目录数组(含价格、研发点、权重、科技树信息)
- `datasets.battleEconomy`:对局收益基数与每车系数表
- `datasets.battleSpawnRules`:出生点、支援机与规则数据
- `datasets.multiplayerMissions`:`{ categories, missions }` 联机任务数据
- `datasets.uiLabels` / `datasets.unitNames`:多语言标签与载具名映射
- `datasets.get(datasetId)` / `datasets.set(datasetId, value)`:按 ID 读取或替换任意数据集
### 4.2 `ctx.hooks.onCataloguesReady(async (catalogues) => { ... })`
在所有业务目录与核心服务装配完成后、开监听之前触发,可访问:
- `catalogues.tuning`:合并完成后的全部只读 `Tuning`
- `catalogues.gameModes`:`GameModes` 实例(提供 `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()`:向客户端推送外部库存变更实时刷新
- `catalogues.notifyUser(userId, eventName, payload)`:向指定登录玩家发送匹配服 `mrpc.generic_notify` 实时推送
### 4.3 `ctx.hooks.onServerListening(({ port }) => { ... })` / `onServerClosing(() => { ... })`
服务器开始监听端口后、以及关闭前触发(适合启动/清理定时器或打印日志)。
### 4.4 档案钩子:`ctx.hooks.profile.onRefresh((profile, userId) => { ... })`
每次读取或更新玩家档案并执行完原生刷新管线后调用(`profile` 是 `@wto/blk` 的 `BlkBlock`)。
### 4.5 对局与匹配钩子(`ctx.hooks.battle`)
#### ① `ctx.hooks.battle.onBeforeMatchmake((ctx) => { ... })`
玩家点击「加入战斗」进入匹配队列、尚未调用 `BattleMatchmaker` 之前触发:
- `ctx`:`{ userId, eventName, request }`(`request` 为客户端发来的原始 `match.enqueue` 参数对象)。
#### ② `ctx.hooks.battle.onFilterMissions((ctx) => { ... })`
`BattleMatchmaker` 已按模式与分房权重筛选出两队候选任务池、尚未随机抽图时触发。
- `ctx`:`{ userId, modeId, modeName, economicName, minMrank, maxMrank, missions }`;
- 每条 `mission` 包含 `{ name, path, level, type, locName, postfix }`;
- **返回值**:返回过滤/重排后的子集数组(返回 `undefined` 表示不干预)。若返回空数组,服务端会记录告警并自动回退到上一层候选池,避免卡死匹配。
```ts
// 示例:只允许匹配名称包含 poland 或 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((ctx) => { ... })`
对局进行中收到客户端上报的实时战斗事实(击杀、占点、生命段、核弹爆炸)时触发:
- `ctx`:`{ userId, roomId, fact }`。
#### ④ `ctx.hooks.battle.onAfterSettle((ctx) => { ... })`
对局结束并写入原生结算后、档案落盘前触发:
- `ctx`:`{ userId, roomId, summary }`(`summary` 含 `{ profile, report, session }`),可在此发放额外自定义奖励或累计模组统计。
---
## 5. 协议路由与本地网页扩展(`ctx.routes`)
### 5.1 Char 动作扩展(`ctx.routes.char`)
- `ctx.routes.char.register(action, handler)`:注册全新的自定义 `cln_*` 动作(如配合客户端 GUI 补丁发来的请求);
- `ctx.routes.char.wrap(action, async (req, next) => { ... })`:拦截并包装现有 `cln_*` 动作(可在调用 `await next(req)` 前后改请求或改响应)。
### 5.2 匹配服 RPC 扩展(`ctx.routes.matching`)
客户端 Quirrel 脚本可以直接用 `matchingApiFunc("wto_mod.<你的方法>", params, callback)` 调用本地服务器匹配接口!
- `ctx.routes.matching.register(method, (req) => ({ ... }))`:注册自定义 RPC(`req` 含 `{ method, params, userId }`,直接返回 JSON 对象);
- `ctx.routes.matching.wrap(method, (req, next) => { ... })`:包装现有匹配服 RPC。
```ts
ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({
ok: true,
userId,
echo: params,
}));
```
### 5.3 本地 HTTP / 内置浏览器网页路由(`ctx.routes.http`)
自动挂载在 **`/mods/<你的modId>/...`** 命名空间下,支持精确路径和 `/*` 通配后缀,既可用系统浏览器访问,也可以通过游戏内置浏览器直接打开:
```ts
ctx.routes.http.register('/panel', () => ({
status: 200,
contentType: 'text/html; charset=utf-8',
body: '<h1>My Mod Panel</h1>',
}));
ctx.routes.http.register('/api/*', (req) => ({
status: 200,
contentType: 'application/json; charset=utf-8',
body: JSON.stringify({ path: req.path, query: req.query }),
}));
```