refactor(api): introduce MessageApi + BridgeContext + ApiHub skeleton (#6 commit 1/13)

First of 13 commits decomposing the Bridge god-object into typed Api
classes following NapCat's `ctx.apis.XxxApi.method()` pattern. This
commit lays the foundation (BridgeContext, ApiHub, eager construction)
plus moves the message-send/recall/mark-read methods onto MessageApi.
Subsequent commits will move the other 12 areas (group admin, files,
profile, …) similarly.

Architecture
------------
* `bridge-context.ts` — new interface, the surface Api classes see.
  Carries identity / events / apis / sendRawPacket / resolveUserUid /
  next{Message,Client}Sequence helpers / upload meta cache. Replaces
  the previous `BridgeInterface` for Api-class consumption (the
  legacy interface still exists, just slimmed; full removal happens
  in commit 13).

* `apis/index.ts` — `ApiHub` interface + `buildApiHub(ctx)` factory.
  Each commit grows `ApiHub` by one entry; today only `message` is
  populated.

* `apis/message.ts` — `MessageApi` with seven methods inlined from
  the previous Bridge implementation:
    sendGroup        ← Bridge.sendGroupMessage
    sendPrivate      ← Bridge.sendPrivateMessage
    sendC2cFile      ← Bridge.sendC2cFileMessage
    recallGroup      ← actions/group-message.ts::recallGroupMessage
    recallPrivate    ← actions/group-message.ts::recallPrivateMessage
    markGroupRead    ← actions/group-message.ts::markGroupMessageRead
    markPrivateRead  ← actions/group-message.ts::markPrivateMessageRead
  (Names trimmed: the `apis.message` prefix already signals the
  context, so `apis.message.sendGroupMessage` would be redundant.)

Bridge changes
--------------
* Removed the 7 methods listed above (moved to MessageApi).
* Removed unused imports + `SEND_MSG_CMD` constant + `buildSendElems`
  + `protobuf_encode/decode` (now used only inside MessageApi).
* Added `readonly apis: ApiHub` field, built eagerly in constructor.
* Promoted `nextMessageRandom` / `nextClientSequence` from private →
  public (Api classes need them to build SendMessageRequest packets).
* `BridgeInterface` now also lists `apis: ApiHub` + the two
  generators; the 7 deleted method signatures are gone.

Caller-site updates (~9 files)
------------------------------
* `bridge/actions/group-file.ts` — `bridge.sendC2cFileMessage(...)`
  → `bridge.apis.message.sendC2cFile(...)`.
* `onebot/instance-context.ts` — markGroupMsgAsRead / markPrivateMsgAsRead
  bindings now route through `apis.message.markGroup/PrivateRead`.
* `onebot/modules/message-actions.ts` — every send/recall site
  rerouted; `typeof ref.bridge.sendXxx` type refs also updated.
* `onebot/actions/extended.ts` — same.

Tests (~5 files)
----------------
* `tests/actions/_helpers.ts` — `mockBridge()` grows an `apis` field
  built by `mockApiHub()`; the previous flat `sendGroupMessage` etc.
  vi.fn stubs are replaced with `mockMessageApi()`.
* All test files using direct `bridge.sendXxx` / `bridge.recallXxx` /
  `bridge.markXxxAsRead` calls or stubs updated to `bridge.apis.message.*`.
* No behaviour changes — 587/587 pass (same baseline; pre-existing
  network-manager native-addon failure unchanged).
This commit is contained in:
DrSmoothl committed 2026-05-20 22:17:47 +08:00
1 parent 9a678442e9
commit 3e5dca1bd4
15 files changed
+598 -332

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
// ApiHub — the per-instance bag of typed Api classes hanging off
// `bridge.apis`. Mirrors NapCat's `NapCatCore.apis = { MsgApi, …}`
// pattern but uses camelCase keys (`apis.message.sendGroup`) to match
// the rest of the SnowLuma TypeScript style.
//
// Each Api class is constructed once when the parent `Bridge` is
// constructed (eager — every account that connects gets its own
// `apis.*` set immediately). Api classes receive a `BridgeContext`
// reference, NOT the concrete `Bridge`, so they remain easy to mock
// without standing up a full Bridge instance.
//
// Adding a new Api:
// 1. Create `bridge/apis/<name>.ts` exporting a `class XxxApi`.
// 2. Add a property here.
// 3. Construct it inside `buildApiHub(ctx)` below.
// 4. Move the relevant methods OFF Bridge and onto the new Api.
//
// This file evolves commit-by-commit as `#6 NapCat-style Api on ctx`
// lands the 13 areas. Until all 13 are in place, ApiHub will have a
// mix of "done" entries and "TODO" markers below — the TODO list
// shrinks as each commit lands.
import type { BridgeContext } from '../bridge-context';
import { MessageApi } from './message';
export interface ApiHub {
/** Send/recall/markRead operations across c2c + group + c2c-file. */
readonly message: MessageApi;
// Pending — added as later commits land:
// readonly contacts: ContactsApi;
// readonly groupAdmin: GroupAdminApi;
// readonly groupFile: GroupFileApi;
// readonly groupAlbum: GroupAlbumApi;
// readonly friend: FriendApi;
// readonly interaction: InteractionApi;
// readonly profile: ProfileApi;
// readonly forward: ForwardApi;
// readonly misc: MiscApi;
// readonly extras: ExtrasApi;
// readonly web: WebApi;
}
/**
* Construct the ApiHub for a Bridge. Called once from the Bridge
* constructor. Eager construction means every Bridge instance pays
* the cost up-front (a few object allocations) — there's no lazy
* path because that would require either a thunk-based wrapper or
* runtime-mutated `apis.xxx` slots, neither of which is worth the
* complexity for ~13 small classes.
*/
export function buildApiHub(ctx: BridgeContext): ApiHub {
return {
message: new MessageApi(ctx),
};
}
// Re-export the Api classes themselves so callers can write
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
// signature use. Concrete instances always come from `bridge.apis.*`.
export { MessageApi } from './message';
+345
View File
@@ -0,0 +1,345 @@
// MessageApi — send / recall / mark-read operations.
//
// Folds together the previous shapes:
// - `Bridge.sendGroupMessage` / `sendPrivateMessage` / `sendC2cFileMessage`
// (formerly inline on the Bridge class).
// - `actions/group-message.ts` (recallGroup / recallPrivate /
// markGroupRead / markPrivateRead).
//
// All implementations are inlined here — the previous indirection
// through `actions/group-message.ts` exported functions was just
// `(bridge, args) → method body`; once methods live on a typed Api
// class the wrapper layer doesn't earn its keep.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
SendMessageRequest,
SendMessageResponse,
} from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import type {
C2CRecallRequest,
GroupRecallRequest,
SsoReadedReportReq,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { MessageElement } from '../events';
import { buildSendElems } from '../element-builder';
import type { BridgeContext } from '../bridge-context';
// `Bridge` is imported as a type only so we can narrow `ctx` back to
// the concrete Bridge instance when passing it to `buildSendElems`
// (which still takes `Bridge` because the highway upload helpers it
// transitively calls each take `Bridge` — refactoring those is a
// separate concern that doesn't need to land alongside the Api split).
//
// At runtime `ctx` IS the Bridge instance that constructed this
// MessageApi — `buildApiHub(ctx)` passes the Bridge itself.
import type { Bridge, SendMessageReceipt } from '../bridge';
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
export class MessageApi {
constructor(private readonly ctx: BridgeContext) {}
/**
* Send a message to a QQ group.
*
* Wraps `MessageSvc.PbSendMsg` with `routingHead.grp.groupCode`.
* Media elements (image / record / video) trigger highway uploads
* inside `buildSendElems` — see `element-builder.ts`.
*
* Returns a `SendMessageReceipt` carrying the assigned messageId,
* group sequence, and timestamps; callers cache this for later
* `recall` / reply lookups.
*/
async sendGroup(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, groupId });
const random = this.ctx.nextMessageRandom();
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
grp: { groupCode: BigInt(groupId) },
},
contentHead: {
type: 1,
},
messageBody: {
richText: {
elems: protoElems,
},
} as any,
clientSequence: 0,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
multiSendSeq: 0,
});
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.groupSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: 0, random, timestamp };
}
/**
* Send a c2c (private) message.
*
* Resolves the recipient's UID only when the message carries media
* — text-only messages skip the lookup. Routes through `c2c.uin`
* (and optionally `c2c.uid` for the media case).
*/
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
let userUid = '';
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
if (hasMedia) {
userUid = await this.ctx.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
c2c: {
uin: userUin,
...(userUid ? { uid: userUid } : {}),
},
},
contentHead: {
type: 1,
subType: 0,
c2cCmd: 11,
},
messageBody: {
richText: {
elems: protoElems,
},
} as any,
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: {
msgFlag: Math.floor(Date.now() / 1000),
},
multiSendSeq: 0,
});
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.privateSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
}
/**
* Send a c2c file as a chat message.
*
* The wire shape isn't the same as a regular c2c message — the c2c
* file path uses three slots that differ from a normal text/image
* send (verified against `dev/Lagrange.Core/.../MessagePacker.cs:
* BuildPacketBase` + `FileEntity.PackMessageContent`):
*
* 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of
* `routingHead.c2c { uin, uid }`. The server rejects c2c file
* messages routed through the regular c2c slot.
* 2. `messageBody.msgContent` carries the serialised
* `FileExtra { file: NotOnlineFile }` bytes. NOT
* `richText.notOnlineFile` — the receiver doesn't read that
* slot for file metadata.
* 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The
* previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT
* server doesn't recognise.
*
* NotOnlineFile carries three required-on-send fields the receiver
* itself ignores but the server's intake validator checks:
* - `subcmd: 1` — c2c file send command code
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
* - `expireTime` — 7 days from now (Lagrange convention)
*/
async sendC2cFile(
userUin: number,
userUid: string,
info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string },
): Promise<SendMessageReceipt> {
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
const nowSec = Math.floor(Date.now() / 1000);
const sevenDaysSec = 7 * 24 * 60 * 60;
const fileExtraBytes = protobuf_encode<FileExtra>({
file: {
fileType: 0,
fileUuid: info.fileId,
fileMd5: info.fileMd5,
fileName: info.fileName,
fileSize: BigInt(info.fileSize),
subcmd: 1,
dangerEvel: 0,
expireTime: nowSec + sevenDaysSec,
fileHash: info.fileHash ?? '',
},
});
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
trans0x211: { ccCmd: 4, uid: userUid },
},
contentHead: {
type: 1,
subType: 0,
},
messageBody: {
msgContent: fileExtraBytes,
},
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: { msgFlag: nowSec },
multiSendSeq: 0,
});
// `userUin` is part of the public contract (the OneBot layer
// threads it through for symmetry with `sendPrivate`) but the
// wire shape only needs the uid. Silence the unused-parameter
// lint without changing the signature.
void userUin;
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.privateSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
}
/**
* Recall (revoke) a group message by sequence number. Server-side
* the message ages out after the standard 2-minute window unless
* the user is an admin/owner.
*/
async recallGroup(groupId: number, sequence: number): Promise<void> {
const request = protobuf_encode<GroupRecallRequest>({
type: 1,
groupUin: groupId,
info: { sequence, random: 0, field3: 0 },
settings: { field1: 0 },
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall group message failed');
}
/**
* Recall a c2c (private) message. Needs more positional info than
* the group variant because c2c messages are identified by the
* `(clientSequence, msgSequence, random, timestamp)` tuple rather
* than a single group-side sequence.
*/
async recallPrivate(
userUin: number,
clientSeq: number,
msgSeq: number,
random: number,
timestamp: number,
): Promise<void> {
const targetUid = await this.ctx.resolveUserUid(userUin);
const request = protobuf_encode<C2CRecallRequest>({
type: 1,
targetUid,
info: {
clientSequence: clientSeq,
random,
messageId: BigInt((0x01000000 * 0x100000000) + random),
timestamp,
field5: 0,
messageSequence: msgSeq,
},
settings: { field1: false, field2: false },
field6: false,
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
}
/**
* Push a group read-report (`trpc.msg.msg_svc.MsgService.SsoReadedReport`)
* advancing the bot's last-read marker to `sequence`. Mirrors the QQ
* NT client's own "scrolled to bottom" behaviour so subsequent
* sync packets don't replay messages we've already processed.
*/
async markGroupRead(groupId: number, sequence: number): Promise<void> {
const request = protobuf_encode<SsoReadedReportReq>({
groupList: [
{
groupUin: BigInt(groupId),
lastReadSeq: BigInt(sequence),
},
],
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark group message read failed');
}
}
/**
* Push a c2c read-report. Same wire-cmd as the group variant but
* keyed by friend uid (resolved from uin via IdentityService).
* `lastReadTime` defaults to "now" — matches the QQ NT client
* which also uses wall-clock seconds rather than the read-message
* timestamp.
*/
async markPrivateRead(userId: number, sequence: number): Promise<void> {
const uid = await this.ctx.resolveUserUid(userId);
const request = protobuf_encode<SsoReadedReportReq>({
c2cList: [
{
uid,
lastReadTime: BigInt(Math.floor(Date.now() / 1000)),
lastReadSeq: BigInt(sequence),
},
],
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark private message read failed');
}
}
}