refactor(onebot): extract OneBot protocol translation into @snowluma/onebot

Phase 3 of the 4-package split (RoadMap #3). Moves the entire
`packages/core/src/onebot/` subtree (43 source files + 20 test files
spanning network adapters, action handlers, event converters, message
parser, message store, media store, instance + manager) into the new
`@snowluma/onebot` workspace package. The remaining `@snowluma/core`
now hosts only the api-layer (Bridge class + 13 Api classes), the
hook tooling, the WebUI server, and the runnable `index.ts`.

Why
---
- The OneBot adapter is the public-facing OneBot11 protocol surface;
  it has its own version cadence and its own consumers (third-party
  bots talking OneBot WS / HTTP). Splitting it lets that cadence move
  independently of the Api-on-ctx layer.
- The two were sharing the `packages/core/` build pipeline only
  because they happened to live in the same directory. Nothing in
  the api-layer reaches into OneBot internals.
- Mirrors NapCat / Lagrange.OneBot's repo split (their OneBot adapter
  is a separate assembly from the Core protocol library).

Layout
------
Moved via `git mv` (history preserved):
  packages/core/src/onebot/*  → @snowluma/onebot/src/<x>
  packages/core/tests/onebot/* (6 files)   → @snowluma/onebot/tests/
  packages/core/tests/{message-parser,message-store,event-pipeline,
    media-store,media-url-resolver,event-converter,
    http-server-hot-reload,http-server-content-type,
    api-handler-logging,message-id,group-msg-emoji-like,
    config,media-indexer,network-manager}.test.ts (14 files)
                                              → @snowluma/onebot/tests/

What stays in @snowluma/core
----------------------------
- `bridge/{bridge,bridge-interface,bridge-context,manager}.ts`
- `bridge/apis/*` (the 13 typed Api classes)
- `hook/*` (debugger/injector — tooling for the core protocol layer)
- `webui/*` (admin UI server — application wiring, not the OneBot
  adapter itself)
- `index.ts` (application entry that wires BridgeManager +
  OneBotManager + HookManager + WebUI together)

Changes
-------
- New package `packages/onebot/` (package.json with subpath exports
  mirroring legacy `core/src/onebot/<x>` 1:1, tsconfig.json,
  vitest.config.ts with `SNOWLUMA_LOG_LEVEL=debug` env so the action-
  dispatch logging tests see debug-level subscribers — copied verbatim
  from core's vitest.config.ts).
- @snowluma/core grows new subpath exports for the api-layer files
  OneBot's type-only imports need: `./bridge`, `./bridge-interface`,
  `./bridge-context`, `./manager`, `./apis`.
- `@snowluma/onebot` depends on `@snowluma/bridge`, `@snowluma/common`,
  `@snowluma/core`, `@snowluma/proto-defs`, `@snowluma/proton`,
  `@snowluma/websocket`.
- `@snowluma/core` depends on `@snowluma/onebot` (for index.ts +
  webui/server.ts wiring).
- 100+ import sites rewritten via sed:
  * OneBot → core: `'../bridge/bridge'` → `'@snowluma/core/bridge'`,
    `'../bridge/manager'` → `'@snowluma/core/manager'`,
    `'../bridge/bridge-interface'` → `'@snowluma/core/bridge-interface'`,
    `'@/bridge/bridge'` (vite path alias) → `'@snowluma/core/bridge'`.
  * Core → OneBot: `'./onebot/manager'` → `'@snowluma/onebot/manager'`,
    `'../onebot/config'` → `'@snowluma/onebot/config'`, etc.
  * Test relative paths: `'../../src/onebot/<x>'` → `'../src/<x>'`
    after the test file move (one level shallower).
- New `packages/onebot/src/env.d.ts` declaring `__APP_VERSION__` and
  `__BUILD_WEBUI__` (the vite-injected globals `info.ts` reads).

Workspace cycle
---------------
core ↔ onebot is allowed by pnpm workspaces. The runtime direction
is one-way: core → onebot (index.ts constructs OneBotManager,
webui/server reads OneBot config). OneBot only reaches into core for
TYPES (Bridge, BridgeInterface, BridgeManager, ClientKeyInfo,
DownloadRKeyInfo); those imports use `import type` so they compile
out at runtime and don't introduce a real cycle.

Verification
------------
- Full workspace `pnpm -r typecheck`: all 11 projects clean.
- `@snowluma/core` test suite: 302/302 pass (33 test files).
- `@snowluma/onebot` test suite: 250/250 pass (20 test files;
  pre-existing `network-manager.test.ts` native-addon failure
  unchanged — same baseline as before the split).
- Combined: 552/552 — identical pass count to the pre-Phase-3
  baseline.
- Vite build with stubbed native binary: clean, 2.84 MB bundle /
  224 KB gzip (identical envelope).
This commit is contained in:
DrSmoothl committed 2026-05-21 08:52:00 +08:00
1 parent f7a03ca05a
commit 9a30df9907
71 files changed
+286 -59

No files matched your search

+218
View File
@@ -0,0 +1,218 @@
import type { WebHonorType } from '@snowluma/bridge/web/group-honor';
import type { Bridge } from '@snowluma/core/bridge';
import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store';
import type { MessageStore } from './message-store';
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import {
getDownloadRKeys,
getFriendList,
getGroupFiles,
getGroupInfo,
getGroupList,
getGroupMemberInfo,
getGroupMemberList,
getGroupSystemMessages,
getLoginInfo,
getStrangerInfo,
} from './modules/contact-actions';
import {
deleteMessage,
forwardSingleMessage,
getForwardMessage,
getFriendMsgHistory,
getGroupMsgHistory,
sendGroupForwardMessage,
sendGroupMessage,
sendPrivateForwardMessage,
sendPrivateMessage,
setEssenceMessage,
uploadForwardMessage,
} from './modules/message-actions';
import {
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
import { handleGroupAddRequest } from './modules/request-actions';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
/**
* Single shared context bag that flows through every OneBot instance-internal
* subsystem: API builder and the per-kind event pipeline.
*
* Only fields that are actually read through this bag live here. The API
* handler and network manager are owned by `OneBotInstance` directly because
* nothing reads them via ctx, and including them here would force a
* chicken-and-egg late-bound field dance during construction.
*
* `dispatchEvent` is the indirection used by the event pipeline to hand a
* converted OneBot event back to the instance for caching + adapter fan-out;
* it lets the pipeline stay decoupled from the network manager.
*/
export interface OneBotInstanceContext {
/** Self UIN as string (matches what's on disk and on the wire). */
uin: string;
/** Self UIN parsed once, used in event payloads. */
selfId: number;
bridge: BridgeInterface;
messageStore: MessageStore;
mediaStore: MediaStore;
converterCtx: ConverterContext;
config: OneBotConfig;
musicSignUrl?: string;
/** Persist meta about a message id; safe to call any number of times. */
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
/** Hand a fully-converted OneBot event to the network manager + caches. */
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),
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
canSendImage: () => true,
canSendRecord: () => true,
// OneBot11 message actions.
sendPrivateMessage: (userId, message, autoEscape) => sendPrivateMessage(ref, userId, message, autoEscape),
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
// OneBot11 info actions (wrap modules that also touch identity).
getFriendList: () => getFriendList(bridge),
getGroupList: (noCache) => getGroupList(bridge, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
// Group admin — names translate to OneBot vocabulary.
setGroupKick: (groupId, userId, reject) => bridge.apis.groupAdmin.kickMember(groupId, userId, reject),
setGroupKickMembers: (groupId, userIds, reject) => bridge.apis.groupAdmin.kickMembers(groupId, userIds, reject),
setGroupBan: (groupId, userId, duration) => bridge.apis.groupAdmin.muteMember(groupId, userId, duration),
setGroupWholeBan: (groupId, enable) => bridge.apis.groupAdmin.muteAll(groupId, enable),
setGroupLeave: (groupId) => bridge.apis.groupAdmin.leave(groupId),
// Group file — fileId field extraction + defaults.
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.apis.groupFile.upload(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
return result.fileId;
},
uploadPrivateFile: async (userId, file, name, uploadFile) => {
const result = await bridge.apis.groupFile.uploadPrivate(userId, file, name ?? '', uploadFile ?? true);
return result.fileId;
},
getGroupFileUrl: (groupId, fileId, busId) => bridge.apis.groupFile.getUrl(groupId, fileId, busId ?? 102),
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
createGroupFileFolder: (groupId, name, parentId) => bridge.apis.groupFile.createFolder(groupId, name, parentId ?? '/'),
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash),
// Requests — name translation.
handleFriendRequest: (flag, approve) => bridge.apis.friend.handleRequest(flag, approve),
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
// Pokes — flatten isGroup into the bridge signature.
sendFriendPoke: (userId, targetId) => bridge.apis.interaction.sendPoke(false, userId, targetId),
sendGroupPoke: (groupId, userId) => bridge.apis.interaction.sendPoke(true, groupId, userId),
// Essence — bake the set/unset boolean.
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
// Profile-like / get_group_essence — OneBot-specific defaults that the
// action handlers don't supply.
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.apis.profile.getLike(userId, start, limit),
getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.apis.web.getEssence(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),
sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta),
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
handleDeleteFriend: (userId, block) => bridge.apis.friend.delete(userId, !!block),
forceFetchClientKey: () => bridge.apis.web.forceFetchClientKey(),
setFriendRemark: (userId, remark) => bridge.apis.friend.setRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.apis.groupAdmin.setRemark(groupId, remark),
setGroupAvatar: (groupId, source) => bridge.apis.profile.setGroupAvatar(groupId, source),
getGroupFileCount: (groupId) => bridge.apis.groupFile.getCount(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');
// QQ itself doesn't expose emoji reactions on private chats, so
// there is no wire path to forward this to; fail loudly instead
// of silently no-op'ing.
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set);
},
markGroupMsgAsRead: (groupId, sequence) => bridge.apis.message.markGroupRead(groupId, sequence),
markPrivateMsgAsRead: (userId, sequence) => bridge.apis.message.markPrivateRead(userId, sequence),
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.apis.profile.setOnlineStatus(status, extStatus, batteryStatus),
setProfile: (nickname?: string, personalNote?: string) => bridge.apis.profile.setProfile(nickname, personalNote),
// Web-backed actions.
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.apis.web.getHonorInfo(groupId, type),
getGroupEssenceAll: (groupId) => bridge.apis.web.getEssenceAll(groupId),
getGroupAlbumList: (groupId) => bridge.apis.groupAlbum.list(groupId),
uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.apis.groupAlbum.upload(groupId, albumId, albumName, filePath),
getGroupAlbumMediaList: (groupId, albumId, attachInfo) => bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo),
commentGroupAlbumMedia: (groupId, albumId, lloc, content) => bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content),
deleteGroupAlbumMedia: (groupId, albumId, lloc) => bridge.apis.groupAlbum.delete(groupId, albumId, lloc),
likeGroupAlbumMedia: (groupId, albumId, batchId, lloc, isLike) => bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, isLike),
sendGroupNotice: (groupId, content, options) => bridge.apis.web.sendNotice(groupId, content, options),
getGroupNotice: (groupId) => bridge.apis.web.getNotice(groupId),
deleteGroupNotice: (groupId, fid) => bridge.apis.web.deleteNotice(groupId, fid),
getCookiesStr: (domain) => bridge.apis.web.getCookiesStr(domain),
getCsrfToken: () => bridge.apis.web.getCsrfToken(),
getCredentials: (domain) => bridge.apis.web.getCredentials(domain),
// Extended
fetchCustomFace: (count) => bridge.apis.profile.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.apis.interaction.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
// Media lookup.
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
};
}
// 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 };