refactor(onebot): drop pure pass-through closures from ApiActionContext

instance-context.ts used to declare ~130 closures inside buildApiContext,
mirrored by ~130 method signatures on ApiActionContext. About 38 of
those were pure 1:1 pass-throughs — `setGroupAdmin: (gid, uid, en) =>
bridge.setGroupAdmin(gid, uid, en)`, `setOnlineStatus`, `setProfile`,
`setAvatar`, `markGroupMsgAsRead`, `getCookiesStr`, `getCsrfToken`,
`getCredentials`, the lot of them. Each was three places to edit (the
closure, the interface signature, the action call site) and zero added
value: the OneBot name matched the Bridge name and no defaults / rename
/ composition was happening.

Expose `bridge: BridgeInterface` on ApiActionContext and have action
handlers route through `ctx.bridge.<name>` for those cases. The 38
closure declarations go away; ApiActionContext shrinks from ~70 method
signatures to ~30; instance-context.ts loses ~50 lines of boilerplate.

The ~30 adapter closures stay — every one of them does real work:
  - Renames: setGroupKick → bridge.kickGroupMember, sendFriendPoke →
    bridge.sendPoke(false, …), handleDeleteFriend → bridge.deleteFriend
  - Field extraction: uploadGroupFile returns result.fileId, not the
    full {fileId} envelope
  - Baked constants: setEssenceMsg passes `true`, deleteEssenceMsg
    passes `false` to the shared setEssenceMessage module function
  - Compositions: sendPrivateMessage / sendGroupMessage / setMsgEmojiLike
    need messageStore + mediaStore + bridge wired together
  - OneBot-specific defaults: getProfileLike defaults start=0 limit=10,
    getGroupEssence defaults pageStart=0 pageLimit=50

Two small downstream nudges that fell out of the type changes:
  - extended.ts:99 — `essenceDataAll.flatMap(res => …)` now needs an
    explicit `(res: any)` since bridge.getGroupEssenceAll returns
    `Promise<any>`, not the previously-asserted `GroupEssenceMsgRet[]`.
  - extended.ts:835 — `okResponse(clientKeyInfo)` widened via spread to
    `okResponse({ ...clientKeyInfo })` because `ClientKeyInfo` is a
    named interface (no index signature) and okResponse expects
    JsonValue/JsonObject. Behavior identical; the response shape is
    unchanged.

402 tests pass (the OneBot contact-actions test added in PR6 doubles as
regression coverage for the seam).
This commit is contained in:
DrSmoothl committed 2026-05-15 01:38:11 +08:00
1 parent 29fa2696c8
commit 7f53bcd085
6 files changed
+106 -151

No files matched your search

+43 -58
View File
@@ -1,5 +1,5 @@
import type { WebHonorType } from '@/bridge/web/group-honor';
import type { BridgeInterface } from '../bridge/bridge-interface';
import type { Bridge } from '../bridge/bridge';
import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store';
@@ -35,6 +35,7 @@ import {
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
import { handleGroupAddRequest } from './modules/request-actions';
import type { BridgeInterface } from '../bridge/bridge-interface';
/**
* Single shared context bag that flows through every OneBot instance-internal
@@ -71,10 +72,25 @@ export interface OneBotInstanceContext {
dispatchEvent(event: JsonObject): void;
}
/**
* Build the ApiActionContext that ApiHandler hands to each action file.
*
* Two flavours of entries live in here:
* - Adapters — rename a Bridge method (setGroupKick → kickGroupMember),
* compose with messageStore / mediaStore / ref, bake in a constant
* (setEssenceMsg passes true; deleteEssenceMsg passes false), bridge a
* bridge call into OneBot vocabulary (sendFriendPoke flattens the
* isGroup boolean), or extract a field from the bridge return shape.
* - Pass-throughs used to live here too but added zero value; OneBot
* actions now call `ctx.bridge.<name>` directly when no translation is
* happening (set_group_admin, set_online_status, set_avatar, …).
*/
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const { bridge, messageStore, mediaStore } = ref;
return {
bridge,
getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true,
getMessage: (messageId) => messageStore.findEvent(messageId),
@@ -87,7 +103,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
// OneBot11 info actions.
// OneBot11 info actions (wrap modules that also touch identity).
getFriendList: () => getFriendList(bridge),
getGroupList: (noCache) => getGroupList(bridge, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
@@ -95,21 +111,14 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
// Group admin.
// Group admin — names translate to OneBot vocabulary.
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
setGroupKickMembers: (groupId, userIds, reject) => bridge.kickGroupMembers(groupId, userIds, reject),
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable),
setGroupAddOption: (groupId, addType) => bridge.setGroupAddOption(groupId, addType),
setGroupSearch: (groupId) => bridge.setGroupSearch(groupId),
setGroupAdmin: (groupId, userId, enable) => bridge.setGroupAdmin(groupId, userId, enable),
setGroupCard: (groupId, userId, card) => bridge.setGroupCard(groupId, userId, card),
setGroupName: (groupId, name) => bridge.setGroupName(groupId, name),
setGroupLeave: (groupId) => bridge.leaveGroup(groupId),
setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title),
getGroupAtAllRemain: (groupId) => bridge.getGroupAtAllRemain(groupId),
// Group file.
// Group file — fileId field extraction + defaults.
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
return result.fileId;
@@ -120,45 +129,31 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
},
getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102),
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
deleteGroupFile: (groupId, fileId) => bridge.deleteGroupFile(groupId, fileId),
moveGroupFile: (groupId, fileId, parentDirectory, targetDirectory) => {
return bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
},
createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'),
deleteGroupFileFolder: (groupId, folderId) => bridge.deleteGroupFileFolder(groupId, folderId),
renameGroupFileFolder: (groupId, folderId, newName) => bridge.renameGroupFileFolder(groupId, folderId, newName),
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash),
// Requests.
// Requests — name translation.
handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve),
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
// Extended.
sendLike: (userId, times) => bridge.sendLike(userId, times),
// Pokes — flatten isGroup into the bridge signature.
sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId),
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
// Essence — bake the set/unset boolean.
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.getProfileLike(userId, start, limit),
fetchCustomFace: (count) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => {
return bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie);
},
getUnidirectionalFriendList: () => bridge.getUnidirectionalFriendList(),
setSelfLongNick: (longNick) => bridge.setSelfLongNick(longNick),
setInputStatus: (userId, eventType) => bridge.setInputStatus(userId, eventType),
translateEn2Zh: (words) => bridge.translateEn2Zh(words),
getMiniAppArk: (type, title, desc, picUrl, jumpUrl) => bridge.getMiniAppArk(type, title, desc, picUrl, jumpUrl),
clickInlineKeyboardButton: (groupId, botAppid, buttonId, callbackData, msgSeq) => {
return bridge.clickInlineKeyboardButton(groupId, botAppid, buttonId, callbackData, msgSeq);
},
sendGroupSign: (groupId) => bridge.sendGroupSign(groupId),
// NapCat-compatible extended actions.
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
// Profile-like / get_group_essence — OneBot-specific defaults that the
// action handlers don't supply.
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.getProfileLike(userId, start, limit),
getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit),
// Message-store-backed history reads.
getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
// Module wrappers / multi-dep compositions.
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
@@ -166,10 +161,10 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendForwardMsg: (messages) => uploadForwardMessage(ref, messages),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
forceFetchClientKey: () => bridge.forceFetchClientKey(),
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
// Cross-store: looks up the meta then routes through Bridge.
setMsgEmojiLike: async (messageId, emojiId, set) => {
const meta = messageStore.findMeta(messageId);
if (!meta) throw new Error('message not found');
@@ -179,27 +174,17 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
},
markGroupMsgAsRead: (groupId, sequence) => bridge.markGroupMsgAsRead(groupId, sequence),
markPrivateMsgAsRead: (userId, sequence) => bridge.markPrivateMsgAsRead(userId, sequence),
setOnlineStatus: (status, extStatus, batteryStatus) => bridge.setOnlineStatus(status, extStatus, batteryStatus),
setProfile: (nickname, personalNote) => bridge.setProfile(nickname, personalNote),
// Web-backed actions.
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.getGroupHonorInfo(groupId, type),
getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit),
getGroupEssenceAll: (groupId) => bridge.getGroupEssenceAll(groupId),
sendGroupNotice: (groupId, content, options) => bridge.sendGroupNotice(groupId, content, options),
getGroupNotice: (groupId) => bridge.getGroupNotice(groupId),
deleteGroupNotice: (groupId, fid) => bridge.deleteGroupNotice(groupId, fid),
getCookiesStr: (domain) => bridge.getCookiesStr(domain),
getCsrfToken: () => bridge.getCsrfToken(),
getCredentials: (domain) => bridge.getCredentials(domain),
// Media lookup.
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
// Avatar.
setAvatar: (source) => bridge.setAvatar(source),
};
}
// Re-export Bridge type so consumers of OneBotInstanceContext that need it
// (legacy) keep the import surface stable.
export type { Bridge };
// Re-export WebHonorType so legacy spots that imported it via this module
// keep working.
export type { WebHonorType };