diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 896f3bb4..3a66f8a8 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -635,7 +635,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { }); h.registerAction('set_online_status', async (params) => { - // 按 OneBot/NapCat 习惯提取参数,状态码默认为 11 const status = asNumber(params.status); const extStatus = asNumber(params.ext_status) || 0; const batteryStatus = asNumber(params.battery_status) || 100; @@ -838,8 +837,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId) { return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id'); } - - try { const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(groupId); return okResponse(data); @@ -864,8 +861,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (typeof longNick !== 'string') { return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick'); } - - try { await ctx.bridge.apis.profile.setSelfLongNick(longNick); return okResponse({}); @@ -908,7 +903,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'invalid event_type'); } - try { await ctx.bridge.apis.profile.setInputStatus(userId, eventType); return okResponse({}); @@ -1042,9 +1036,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); }); - // 原始数据包逃生口(兼容 NapCat)。 - // NapCat 暴露了两个名称:带点前缀的是 gocqhttp 时代的原始后门,不带前缀的是现代接口。 - // 它们在 SnowLuma 中执行相同逻辑:十六进制编码 → Bridge.sendRawPacket → 十六进制编码。 const handleSendPacket = async (params: JsonObject) => { const cmd = asString(params.cmd); const dataHex = asString(params.data); @@ -1070,14 +1061,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('.send_packet', handleSendPacket); // 机器人生命周期(兼容 NapCat)。 - h.registerAction('bot_exit', async () => { setTimeout(() => process.exit(0), 50); return okResponse(); }); - // SnowLuma 没有独立的数据包后端进程。 - // NapCat 的数据包服务在进程外运行,可能独立失败;这里始终报告健康。 h.registerAction('nc_get_packet_status', async () => { return okResponse(null); }); diff --git a/packages/onebot/src/actions/group-admin.ts b/packages/onebot/src/actions/group-admin.ts index 23bda0e2..2eda8977 100644 --- a/packages/onebot/src/actions/group-admin.ts +++ b/packages/onebot/src/actions/group-admin.ts @@ -1,5 +1,5 @@ -import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { asNumber, asString, asBoolean } from '../api-handler'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { asBoolean, asNumber, asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; export function register(h: ApiHandler, ctx: ApiActionContext): void { @@ -103,10 +103,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse(); }); - // Highway upload with cmdId 3000 + GroupAvatarExtra (Lagrange protocol). - // `file` accepts everything bridge.setGroupAvatar's underlying - // loadBinarySource handles: local paths, file:// URLs, http(s) URLs, - // and base64:// data URIs — same surface as set_qq_avatar. h.registerAction('set_group_portrait', async (params) => { const groupId = asNumber(params.group_id); const file = asString(params.file); @@ -119,4 +115,4 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); } }); -} \ No newline at end of file +} diff --git a/packages/onebot/src/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts index b7f8b1e9..80628ded 100644 --- a/packages/onebot/src/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -1,7 +1,7 @@ -import type { ApiHandler, ApiActionContext } from '../api-handler'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; import { asNumber, asString } from '../api-handler'; -import { RETCODE, failedResponse, okResponse } from '../types'; import type { JsonValue } from '../types'; +import { RETCODE, failedResponse, okResponse } from '../types'; export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_group_album_list', async (params) => { @@ -47,9 +47,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo); - // GroupAlbumMediaResult is a concrete domain type; okResponse - // expects JsonValue. The shape is JSON-compatible — same as the - // old ctx wrapper returning `Promise`. return okResponse(mediaList as unknown as JsonValue); } catch (error) { const message = error instanceof Error ? error.message : 'failed to get group album media list'; @@ -70,10 +67,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { const comment = await ctx.bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content); - // GroupAlbumCommentResult is a concrete domain type; okResponse - // expects JsonValue. The shape is JSON-compatible (no functions - // / classes / bigints), so cast is safe — same as the old ctx - // wrapper returning `Promise`. return okResponse(comment as unknown as JsonValue); } catch (error) { const message = error instanceof Error ? error.message : 'failed to comment on album media'; diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 0ba41c3f..e23fa093 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -1,24 +1,20 @@ -import type { JsonObject, JsonValue, MessageMeta } from './types'; -import type { ForwardPreviewMeta } from './modules/message-actions'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import { RETCODE, failedResponse } from './types'; -import { createLogger, type Logger } from '@snowluma/common/logger'; import { summarizeParams } from '@snowluma/common/log-summary'; - -const moduleLog = createLogger('Bridge.Action'); - +import { createLogger, type Logger } from '@snowluma/common/logger'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { register as registerExtended } from './actions/extended'; +import { register as registerFriend } from './actions/friend'; +import { register as registerGroupAdmin } from './actions/group-admin'; +import { register as registerGroupAlbum } from './actions/group-album'; +import { register as registerGroupFile } from './actions/group-file'; +import { register as registerGroupInfo } from './actions/group-info'; import { register as registerInfo } from './actions/info'; import { register as registerMessage } from './actions/message'; -import { register as registerFriend } from './actions/friend'; -import { register as registerGroupInfo } from './actions/group-info'; -import { register as registerGroupAdmin } from './actions/group-admin'; -import { register as registerGroupFile } from './actions/group-file'; import { register as registerRequest } from './actions/request'; -import { register as registerExtended } from './actions/extended'; -import { register as registerGroupAlbum } from './actions/group-album'; +import type { ForwardPreviewMeta } from './modules/message-actions'; +import type { JsonObject, JsonValue, MessageMeta } from './types'; +import { RETCODE, failedResponse } from './types'; +const moduleLog = createLogger('Bridge.Action'); -import { WebHonorType } from '@snowluma/protocol/web/group-honor'; -import type { ClientKeyInfo } from '@snowluma/core/bridge'; export interface MessageSendResult { messageId: number; @@ -37,14 +33,7 @@ export interface GroupEssenceMsgRet { } export interface ApiActionContext { - /** - * Direct access to the BridgeInterface. Use for actions that are pure - * 1:1 calls to a Bridge method — no rename, no default args, no - * composition with messageStore / mediaStore. When translation IS - * needed, route through the named adapters declared below instead. - */ bridge: BridgeInterface; - getLoginInfo: () => { userId: number; nickname: string }; isOnline: () => boolean; getMessage: (messageId: number) => JsonObject | null; @@ -54,37 +43,16 @@ export interface ApiActionContext { deleteMessage: (messageId: number, meta: MessageMeta) => Promise; canSendImage: () => boolean; canSendRecord: () => boolean; - // Info retrieval (async — triggers OIDB fetch) getFriendList: () => Promise; getGroupList: (noCache?: boolean) => Promise; getGroupInfo: (groupId: number, noCache?: boolean) => Promise; getGroupMemberList: (groupId: number, noCache?: boolean) => Promise; getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise; getStrangerInfo: (userId: number) => Promise; - // Group admin (mute/kick/admin/card/name/title/leave/etc) — all - // accessed directly through `ctx.bridge.apis.groupAdmin.method()` - // after the #6 OneBot-side slim-down; no per-method passthrough - // here anymore. - // Group file passthroughs are gone — actions call - // `ctx.bridge.apis.groupFile.{upload,uploadPrivate,getUrl, - // createFolder,getPrivateUrl,getCount}` directly. `getGroupFiles` - // stays because it composes through the `getGroupFiles` module - // helper (identity-lookup enrichment of uploader names). getGroupFiles: (groupId: number, folderId?: string) => Promise; - // Friend requests: direct via `ctx.bridge.apis.friend.handleRequest`. - // Group requests: stay on ctx because `handleGroupAddRequest` is a - // module helper that does the flag-parsing + group-request lookup - // dance before routing to `bridge.apis.groupAdmin.setAddRequest`. handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise; - // Pokes: direct via `ctx.bridge.apis.interaction.sendPoke(isGroup, …)`. - // Essence (adapter: bakes the set/unset boolean) setEssenceMsg: (messageId: number) => Promise; deleteEssenceMsg: (messageId: number) => Promise; - // Profile reads and group essence reads: direct via - // `ctx.bridge.apis.profile.getLike(...)` and - // `ctx.bridge.apis.web.getEssence(...)`. - // Friend deletion: direct via `ctx.bridge.apis.friend.delete(userId, block)`. - // Module wrappers / multi-dep compositions getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise; getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise; handleGetGroupSystemMsg: () => Promise; @@ -94,17 +62,7 @@ export interface ApiActionContext { sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>; getForwardMsg: (resId: string) => Promise; forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>; - // setMsgEmojiLike: stays because it threads messageStore meta lookup. setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise; - /** - * Fetch the cached reactor user list for a (message, emoji) pair. - * Backed by ReactionStore — see `reaction-store.ts` for the - * limitations vs. NapCat's wrapper-cache approach. - * - * `serverCount` comes from a side `0x9084_1` summary call; when it - * exceeds `cachedUsers.length` the cache is provably incomplete - * (push events missed before bot boot, etc). - */ fetchEmojiLikeUsers: ( messageId: number, emojiId: string, @@ -116,17 +74,6 @@ export interface ApiActionContext { serverCount: number; complete: boolean; }>; - // All other extended / NapCat-compatible / Web / Album actions are - // accessed directly through `ctx.bridge.apis..()`: - // * profile area: setProfile / setOnlineStatus / fetchCustomFace / - // setGroupAvatar / getLike - // * friend area: setRemark / delete / handleRequest - // * web area: getHonorInfo / getEssence(All) / sendNotice / - // getNotice / deleteNotice / getCookiesStr / - // getCsrfToken / getCredentials / forceFetchClientKey - // * groupAlbum area: list / upload / getMediaList / comment / - // delete / like - // Media lookup (populated from previously dispatched message segments) getImageInfo: (file: string) => Promise; getRecordInfo: (file: string) => Promise; } diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index e2c94a18..828393b2 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -1,7 +1,7 @@ +import { createLogger } from '@snowluma/common/logger'; +import { randomBytes } from 'crypto'; import fs from 'fs'; import path from 'path'; -import { randomBytes } from 'crypto'; -import { createLogger } from '@snowluma/common/logger'; import type { HttpClientNetwork, HttpServerNetwork, @@ -54,13 +54,6 @@ function generateAccessToken(): string { } export interface LoadOneBotConfigOptions { - /** - * Persist the normalized config to disk when the file is missing or was - * in legacy format. Default `false` so accidental call sites (read-only - * GETs in particular) don't generate fresh access tokens, race on - * concurrent writes, or surprise the operator with materialized files. - * Pass `true` from boot / explicit POST handlers. - */ persistDefaults?: boolean; } @@ -70,9 +63,6 @@ export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`); const globalRaw = tryLoadJson(DEFAULT_CONFIG_PATH); const perUinRaw = tryLoadJson(perUinPath); - - // Detect legacy on-disk format (top-level per-type arrays). We auto-migrate - // these entries into `networks.*` and rewrite the file on the next save. const legacy = !!perUinRaw && hasLegacyTopLevel(perUinRaw); const sources: JsonObject[] = []; @@ -162,11 +152,6 @@ function wsClientToJson(n: WsClientNetwork): JsonObject { } function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { - // Legacy top-level scalars are pulled DOWN into each adapter on the first - // load: the on-disk schema has no globals anymore, every adapter is - // self-describing. We compute the legacy fallbacks here so that adapters - // missing `messageFormat`/`reportSelfMessage` inherit them once and the - // file is rewritten in normalized form. let legacyFormat: MessageFormat | undefined; let legacyReport: boolean | undefined; let musicSignUrl = ''; @@ -178,19 +163,11 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { } const inheritedFormat: MessageFormat = legacyFormat ?? 'array'; const inheritedReport: boolean = legacyReport ?? false; - - // Pluck per-type arrays from each source: prefer `networks.` over - // legacy top-level arrays, but accept both. Later sources override earlier - // ones at the network level (last write wins per `(kind, name)` pair). const adapterDefaults = { messageFormat: inheritedFormat, reportSelfMessage: inheritedReport }; const httpServers = collectByName(sources, 'httpServers', (raw) => parseHttpServer(raw, adapterDefaults)); const httpClients = collectByName(sources, 'httpClients', (raw) => parseHttpClient(raw, adapterDefaults), 'httpPostEndpoints'); const wsServers = collectByName(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults)); const wsClients = collectByName(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults)); - - // Seed defaults ONLY for a brand-new install (no source files at all). - // If the operator deliberately emptied every adapter, respect that and - // do NOT silently revive default 0.0.0.0 listeners. if ( freshInstall && httpServers.length === 0 && @@ -340,8 +317,6 @@ function clean>(obj: T): T { } function asRole(value: unknown, fallback: WsRole): WsRole { - // Accept both uppercase (canonical) and lowercase (legacy on-disk) forms. - // Lowercase values are auto-migrated to uppercase on the next save. const text = asString(value, fallback).toLowerCase(); if (text === 'api') return 'Api'; if (text === 'event') return 'Event'; diff --git a/packages/onebot/src/env.d.ts b/packages/onebot/src/env.d.ts index c1f1bcd1..32800b0b 100644 --- a/packages/onebot/src/env.d.ts +++ b/packages/onebot/src/env.d.ts @@ -1,8 +1,2 @@ -// Globals injected by Vite at build time (see `packages/core/vite.config.ts`). -// `__APP_VERSION__` reads from the monorepo root `package.json::version`; -// `__BUILD_WEBUI__` flips on when `BUILD_WEBUI=true` is set so the runner -// stitches the SPA assets in. Both are typed as `unknown` outside vite -// (e.g. when running tests via vitest where the plugin isn't applied) — -// callers guard with `typeof __APP_VERSION__ !== 'undefined'`. declare const __BUILD_WEBUI__: boolean; declare const __APP_VERSION__: string; diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index 658ba26c..16f13f34 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -25,16 +25,10 @@ import { } from './to-request'; import { elementsToJson } from './to-segment'; -// ─────────────── resolver callback types ─────────────── - export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string; export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise; export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number; -/** - * Side-channel callback invoked every time an image / record / video - * segment is produced, so callers can keep a lookup index (e.g. for - * `get_image` / `get_record`) without re-scanning the message store. - */ + export type MediaSegmentSink = ( mediaType: 'image' | 'record' | 'video', element: MessageElement, @@ -45,15 +39,7 @@ export type MediaSegmentSink = ( // ─────────────── context ─────────────── -/** - * Everything `convertEvent` needs that isn't on the bridge event itself. - * Built once per OneBotInstance and passed through unchanged. Resolvers - * are nullable because tests routinely omit them; when missing, the - * converter falls back to the bridge event's own fields (e.g. raw - * `element.url`, raw `event.msgSeq`). - */ export interface ConverterContext { - /** Self uin parsed once into a Number for inclusion in `self_id`. */ selfId: number; imageUrlResolver: ImageUrlResolver | null; mediaUrlResolver: MediaUrlResolver | null; @@ -63,11 +49,6 @@ export interface ConverterContext { // ─────────────── dispatcher ─────────────── -/** - * Convert a bridge `QQEventVariant` to the OneBot wire-shape JSON. - * Returns null for kinds we don't surface (so callers can skip them - * without an explicit allow-list). - */ export async function convertEvent( ctx: ConverterContext, event: QQEventVariant, @@ -101,15 +82,6 @@ export async function convertEvent( } } -// ─────────────── side-channel re-export ─────────────── - -/** - * Element-array -> OneBot segment-array helper. Used by - * `modules/message-actions.ts` for forward-message rebuilding (where - * we already know the elements but want the OneBot segment shape). - * The signature stays backwards-compatible: each resolver is an - * optional positional argument. - */ export async function elementsToOneBotSegments( elements: MessageElement[], isGroup: boolean, diff --git a/packages/onebot/src/event-converter/to-message.ts b/packages/onebot/src/event-converter/to-message.ts index fbd5ff01..5f667a95 100644 --- a/packages/onebot/src/event-converter/to-message.ts +++ b/packages/onebot/src/event-converter/to-message.ts @@ -1,9 +1,10 @@ import type { QQEventVariant } from '@snowluma/protocol/events'; +import { segmentsToRawMessage } from '../helper/cq'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id'; import type { JsonObject } from '../types'; import type { ConverterContext } from './index'; import { elementsToJson } from './to-segment'; -import { applyMessageIdResolver, segmentsToRawMessage } from './utils'; +import { applyMessageIdResolver } from './utils'; type FriendMessage = Extract; type GroupMessage = Extract; diff --git a/packages/onebot/src/event-converter/to-notice.ts b/packages/onebot/src/event-converter/to-notice.ts index 2e6a24e4..b66899f1 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -183,17 +183,7 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO }; } -/** - * Group message emoji reaction notice. Matches the gocqhttp / NapCat - * extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot - * v11 standard has no slot for reactions and that's what every - * downstream framework keys off. - */ export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject { - // Reconstruct the OneBot message_id we originally minted for the - // reacted-to message. hashMessageIdInt32 is deterministic so the ID - // matches whatever the client received at receive-time, even when - // the message has fallen out of our store. const messageId = applyMessageIdResolver( ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT, ); diff --git a/packages/onebot/src/event-converter/to-segment.ts b/packages/onebot/src/event-converter/to-segment.ts index f2d5d236..f7a33d7c 100644 --- a/packages/onebot/src/event-converter/to-segment.ts +++ b/packages/onebot/src/event-converter/to-segment.ts @@ -142,8 +142,5 @@ async function elementToSegment( data: { id: element.resId ?? '' }, }; } - - // Unknown / unmapped element type — emit an empty segment to keep the - // outgoing message length consistent with the bridge event. return { type: element.type, data: {} }; } diff --git a/packages/onebot/src/event-converter/utils.ts b/packages/onebot/src/event-converter/utils.ts index 82523dc6..ab2af109 100644 --- a/packages/onebot/src/event-converter/utils.ts +++ b/packages/onebot/src/event-converter/utils.ts @@ -1,5 +1,4 @@ import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id'; -import type { JsonArray, JsonObject } from '../types'; import type { MessageIdResolver } from './index'; export function parseSelfId(instanceUin: string): number { @@ -7,11 +6,6 @@ export function parseSelfId(instanceUin: string): number { return Number.isNaN(parsed) ? 0 : parsed; } -/** - * Two QQEvent actors are "the same" when their uins match, or their - * uids match when uins aren't available. Used by the group_member_join - * sub-type calculation (self-approve vs. invite). - */ export function isSameActor( leftUin: number, leftUid: string | undefined, @@ -22,10 +16,6 @@ export function isSameActor( return Boolean(leftUid) && leftUid === rightUid; } -/** - * Run the optional MessageId resolver, falling back to the raw - * sequence when no resolver is wired or it returns 0. - */ export function applyMessageIdResolver( resolver: MessageIdResolver | null, isGroup: boolean, @@ -58,48 +48,3 @@ export function resolveReplyId( return seq; } - -// ─────────────── raw_message (CQ string) generation ─────────────── - -function cqEscape(text: string): string { - return text.replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']').replace(/,/g, ','); -} - -export function segmentsToRawMessage(segments: JsonArray): string { - return segments.map(seg => segmentToCQ(seg as JsonObject)).join(''); -} - -function segmentToCQ(seg: JsonObject): string { - const type = String(seg.type ?? ''); - const data = (seg.data ?? {}) as Record; - switch (type) { - case 'text': - return cqEscape(String(data.text ?? '')); - case 'face': - return `[CQ:face,id=${data.id ?? 0}]`; - case 'image': - return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; - case 'at': - return `[CQ:at,qq=${data.qq ?? ''}]`; - case 'reply': - return `[CQ:reply,id=${data.id ?? 0}]`; - case 'record': - return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; - case 'video': - return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; - case 'json': - return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`; - case 'xml': - return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`; - case 'forward': - return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`; - case 'mface': - return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`; - case 'poke': - return `[CQ:poke,type=${data.type ?? 0}]`; - case 'file': - return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; - default: - return `[CQ:${type}]`; - } -} diff --git a/packages/onebot/src/event-filter.ts b/packages/onebot/src/event-filter.ts index a3d90ae6..b4893573 100644 --- a/packages/onebot/src/event-filter.ts +++ b/packages/onebot/src/event-filter.ts @@ -1,16 +1,9 @@ import type { JsonObject, JsonValue, MessageFormat } from './types'; export interface EventReportOptions { - /** Effective `messageFormat` for this adapter. */ messageFormat: MessageFormat; - /** Whether self-sent messages should be forwarded to this adapter. */ reportSelfMessage: boolean; } -/** - * Extract the dispatch options from an adapter. Each adapter is fully - * self-describing — there is no global fallback. Defaults are applied here - * only as a safety net for partially-deserialized legacy configs. - */ export function resolveReportOptions( network: { messageFormat?: MessageFormat; reportSelfMessage?: boolean }, ): EventReportOptions { @@ -20,32 +13,12 @@ export function resolveReportOptions( }; } -/** - * Pre-built payload covering every adapter variant of a single canonical event. - * - * The bridge produces one OneBot-shaped event per upstream packet. Because - * adapters only differ in (a) whether they receive `message_sent` self-events - * and (b) whether the `message` field is the segment array or its CQ-string - * form, we serialize the event at most twice up-front and let every adapter - * pick the slot it needs in O(1). - */ export interface DispatchPayload { - /** True when the canonical event is a self-sent message (`post_type='message_sent'`). */ isSelfMessage: boolean; - /** JSON for adapters using `messageFormat: 'array'` (the canonical event). */ arrayJson: string; - /** - * JSON for adapters using `messageFormat: 'string'`. For non-message events - * this points at the same string as `arrayJson` (no transformation needed). - */ stringJson: string; } -/** - * Build the dispatch payload for one canonical OneBot event. Performs at most - * two `JSON.stringify` calls (one per format variant) regardless of how many - * adapters the payload will fan out to. - */ export function buildDispatchPayload(event: JsonObject): DispatchPayload { const isSelfMessage = event.post_type === 'message_sent'; const arrayJson = JSON.stringify(event); @@ -60,11 +33,6 @@ export function buildDispatchPayload(event: JsonObject): DispatchPayload { return { isSelfMessage, arrayJson, stringJson }; } -/** - * Pick the pre-serialized payload variant an adapter should send, or `null` - * when the adapter chose not to receive this event. Hot-path helper: one - * branch + one map lookup per connection, no allocation. - */ export function pickDispatchJson( payload: DispatchPayload, options: EventReportOptions, @@ -73,14 +41,6 @@ export function pickDispatchJson( return options.messageFormat === 'string' ? payload.stringJson : payload.arrayJson; } -/** - * One-shot variant of {@link buildDispatchPayload} + {@link pickDispatchJson} - * for ad-hoc events (e.g. WS connection bootstrap meta events) that aren't - * worth pre-building a full payload for. - * - * Returns `null` when the adapter shouldn't see this event. Otherwise returns - * the original event untouched, or a shallow clone with `message` rewritten. - */ export function shapeEventForAdapter( event: JsonObject, options: EventReportOptions, diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 7b58d6ae..a6a637f7 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -3,18 +3,8 @@ import { convertEvent } from './event-converter'; import type { OneBotInstanceContext } from './instance-context'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; -/** - * Subscribe every `OneBotInstanceContext`-aware handler onto the bridge - * event bus. Returns a disposer that removes every subscription registered - * here in one shot — useful for tests and for tearing down a session. - */ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void { const disposers: Array<() => void> = []; - - // Every kind that maps onto an OB11 message event also seeds the - // message-meta cache; we do that synchronously before async conversion so - // reply / quote lookups for that message id work even if the converter - // takes a beat to finish (e.g. while resolving image URLs). disposers.push( ctx.bridge.events.on('group_message', async (event) => { cacheGroupMessageMeta(ctx, event); @@ -33,15 +23,9 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void { await convertAndDispatch(ctx, event); }), ); - - // Notice / request / non-message events: no meta caching needed, just - // convert and dispatch. for (const kind of NOTICE_KINDS) { disposers.push( ctx.bridge.events.on(kind, async (event) => { - // Side-effect: write emoji-reaction events to the local cache - // BEFORE converting / dispatching, so a fetch_emoji_like that - // races with the push still sees the new row. if (event.kind === 'group_msg_emoji_like') { cacheReaction(ctx, event); } @@ -116,12 +100,6 @@ function cacheReaction( ctx: OneBotInstanceContext, event: Extract, ): void { - // `isAdd=true` means the operator just reacted; `isAdd=false` means - // the reaction was withdrawn. The decoder already normalizes both - // directions onto this single event kind. `emojiType` isn't on the - // push event payload — we default to 1 (QQ-face) which matches every - // observed reaction so far; the field is a known unknown and can be - // refined later if a wire dump shows it. if (!event.groupId || !event.msgSeq || !event.emojiId || !event.operatorUin) return; if (event.isAdd) { ctx.reactionStore.recordAdd( diff --git a/packages/onebot/src/helper/cq.ts b/packages/onebot/src/helper/cq.ts new file mode 100644 index 00000000..1ba348b0 --- /dev/null +++ b/packages/onebot/src/helper/cq.ts @@ -0,0 +1,80 @@ +import type { MessageElement } from '@snowluma/protocol/events'; +import { CQ_REGEX, parseCQParams, ParseMessageOptions, segmentToElement } from '../message-parser'; +import type { JsonArray, JsonObject } from '../types'; + + +export function segmentToCQ(seg: JsonObject): string { + const type = String(seg.type ?? ''); + const data = (seg.data ?? {}) as Record; + switch (type) { + case 'text': + return cqEscape(String(data.text ?? '')); + case 'face': + return `[CQ:face,id=${data.id ?? 0}]`; + case 'image': + return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + case 'at': + return `[CQ:at,qq=${data.qq ?? ''}]`; + case 'reply': + return `[CQ:reply,id=${data.id ?? 0}]`; + case 'record': + return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + case 'video': + return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + case 'json': + return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`; + case 'xml': + return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`; + case 'forward': + return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`; + case 'mface': + return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`; + case 'poke': + return `[CQ:poke,type=${data.type ?? 0}]`; + case 'file': + return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + default: + return `[CQ:${type}]`; + } +} export function segmentsToRawMessage(segments: JsonArray): string { + return segments.map(seg => segmentToCQ(seg as JsonObject)).join(''); +} +export function cqEscape(text: string): string { + return text.replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']').replace(/,/g, ','); +} +export function cqUnescape(text: string): string { + // Order matters: `&` MUST be last so that, e.g., `&#91;` keeps + // the literal `[` instead of decoding twice into `[`. + return text + .replace(/[/g, '[') + .replace(/]/g, ']') + .replace(/,/g, ',') + .replace(/&/g, '&'); +} +export async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise { + const elements: MessageElement[] = []; + let lastIndex = 0; + + for (const match of message.matchAll(CQ_REGEX)) { + // Text before this CQ code + if (match.index! > lastIndex) { + const text = cqUnescape(message.substring(lastIndex, match.index!)); + if (text) elements.push({ type: 'text', text }); + } + lastIndex = match.index! + match[0].length; + + const cqType = match[1]; + const params = parseCQParams(match[2] || ''); + const elem = await segmentToElement(cqType, params, options); + if (elem) elements.push(elem); + } + + // Trailing text + if (lastIndex < message.length) { + const text = cqUnescape(message.substring(lastIndex)); + if (text) elements.push({ type: 'text', text }); + } + + return elements; +} + diff --git a/packages/onebot/src/instance-context.ts b/packages/onebot/src/instance-context.ts index 25844bae..e32fecfc 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -1,11 +1,10 @@ -import type { WebHonorType } from '@snowluma/protocol/web/group-honor'; import type { Bridge } from '@snowluma/core/bridge'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { WebHonorType } from '@snowluma/protocol/web/group-honor'; 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 { ReactionStore } from './reaction-store'; -import type { JsonObject, MessageMeta, OneBotConfig } from './types'; import { getDownloadRKeys, getFriendList, @@ -18,6 +17,10 @@ import { getLoginInfo, getStrangerInfo, } from './modules/contact-actions'; +import { + getImageInfo as getCachedImageInfo, + getRecordInfo as getCachedRecordInfo, +} from './modules/media-actions'; import { deleteMessage, forwardSingleMessage, @@ -31,65 +34,24 @@ import { 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'; +import type { ReactionStore } from './reaction-store'; +import type { JsonObject, MessageMeta, OneBotConfig } from './types'; -/** - * 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; - /** Local cache of emoji-reaction events keyed by (group, msgSeq, emoji, - * reactor). Fed from `GroupMsgEmojiLikeEvent` push by the event - * pipeline; queried by fetch_emoji_like / get_emoji_likes. */ reactionStore: ReactionStore; - 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.` directly when no translation is - * happening (set_group_admin, set_online_status, set_avatar, …). - */ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { const { bridge, messageStore, mediaStore, reactionStore } = ref; @@ -102,38 +64,19 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { 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 — actions now call `ctx.bridge.apis.groupAdmin.X(...)` - // directly; no per-method passthrough here anymore. - - // Group file — `getGroupFiles` stays because the module helper - // enriches uploader/creator names from the identity cache; the - // rest of the area is called directly via `ctx.bridge.apis.groupFile.*`. getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId), - - // Group request handling stays here because `handleGroupAddRequest` - // is a module helper (flag parsing + group-request lookup). Friend - // request handling moved to direct `ctx.bridge.apis.friend.handleRequest`. handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason), - - // 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), @@ -141,25 +84,14 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId), getForwardMsg: (resId) => getForwardMessage(ref, resId), forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target), - - // Essence — bakes the set/unset boolean (the only "compose with - // messageStore meta lookup" entry remaining outside of dedicated - // module helpers). setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true), deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false), - - // Emoji-like — same shape: meta lookup → bridge call. Group-only - // (QQ doesn't expose emoji reactions on private chats). setMsgEmojiLike: async (messageId, emojiId, set) => { const meta = messageStore.findMeta(messageId); if (!meta) throw new Error('message not found'); 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); }, - - // Fetch reactor user list from local cache, cross-checked against - // the server's 0x9084_1 summary so callers can tell when the cache - // is incomplete (push events missed before bot boot, etc). fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => { const meta = messageStore.findMeta(messageId); if (!meta) throw new Error('message not found'); @@ -167,10 +99,6 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { const raw = reactionStore.listUsers(meta.targetId, meta.sequence, emojiId, count, offset); const users = raw.map(r => ({ uin: r.operatorUin, uid: r.operatorUid, setAt: r.setAt })); const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId); - // Best-effort server-side count cross-check. If the summary call - // itself fails (network blip / server hiccup) we fall back to the - // cached count and report complete=true since we have no contrary - // evidence. let serverCount = cachedCount; try { const summary = await bridge.apis.interaction.fetchReactionSummary(meta.targetId, meta.sequence); @@ -186,17 +114,10 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { complete: cachedCount >= serverCount, }; }, - - // 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 }; +export type { Bridge, WebHonorType }; -// Re-export WebHonorType so legacy spots that imported it via this module -// keep working. -export type { WebHonorType }; diff --git a/packages/onebot/src/instance-rkey.ts b/packages/onebot/src/instance-rkey.ts index 709aec21..b713537c 100644 --- a/packages/onebot/src/instance-rkey.ts +++ b/packages/onebot/src/instance-rkey.ts @@ -1,7 +1,7 @@ -import type { MessageElement } from '@snowluma/protocol/events'; +import { createLogger } from '@snowluma/common/logger'; import type { DownloadRKeyInfo } from '@snowluma/core/bridge'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import { createLogger } from '@snowluma/common/logger'; +import type { MessageElement } from '@snowluma/protocol/events'; const log = createLogger('OneBot'); @@ -50,11 +50,6 @@ export class RKeyCache { const separator = url.includes('?') ? '&rkey=' : '?rkey='; return url + separator + encodeURIComponent(cleanRKey); } - - /** - * Resolve a URL for video/record/file media elements. - * Appends the correct RKey type based on media kind and group/private context. - */ resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string { const url = element.url ?? ''; if (!url || !urlNeedsRKey(url)) return url; @@ -111,18 +106,13 @@ export class RKeyCache { let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE); if (result) return result; - - // Refresh check cooldown if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null; this.lastRefreshAttempt = now; - - // Schedule async refresh bridge.apis.contacts.fetchDownloadRKeys().then( (rkeys) => this.updateCache(rkeys), () => { /* ignore */ }, ); - // Try again (won't be ready yet for this call, but future calls will benefit) result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE); return result; } @@ -132,8 +122,8 @@ function urlNeedsRKey(url: string): boolean { if (!url || url.includes('rkey=')) return false; if (url.includes('gchat.qpic.cn')) return false; return url.includes('multimedia.nt.qq.com.cn') || - url.includes('.nt.qq.com.cn') || - url.includes('/download'); + url.includes('.nt.qq.com.cn') || + url.includes('/download'); } function stripRKeyPrefix(rkey: string): string { diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index f033c832..2adc02e7 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -1,27 +1,27 @@ -import path from 'path'; +import { createLogger, type Logger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format'; +import path from 'path'; import { ApiHandler } from './api-handler'; import type { ConverterContext } from './event-converter'; +import { registerEventPipeline } from './event-pipeline'; +import { buildApiContext, type OneBotInstanceContext } from './instance-context'; +import { RKeyCache } from './instance-rkey'; import { MediaIndexer } from './media-indexer'; import { MediaStore } from './media-store'; -import { ReactionStore } from './reaction-store'; import { MediaUrlResolver } from './media-url-resolver'; -import { MessageStore } from './message-store'; -import { RKeyCache } from './instance-rkey'; -import { buildApiContext, type OneBotInstanceContext } from './instance-context'; -import { registerEventPipeline } from './event-pipeline'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; -import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types'; +import { MessageStore } from './message-store'; import { - OneBotNetworkManager, - WsServerAdapter, - WsClientAdapter, - HttpServerAdapter, HttpPostAdapter, + HttpServerAdapter, + OneBotNetworkManager, + WsClientAdapter, + WsServerAdapter, type NetworkAdapterContext, } from './network'; -import { createLogger, type Logger } from '@snowluma/common/logger'; -import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format'; +import { ReactionStore } from './reaction-store'; +import type { JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types'; const moduleLog = createLogger('Event'); @@ -59,10 +59,6 @@ export class OneBotInstance { this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db')); this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json')); this.reactionStore = new ReactionStore(path.join('data', this.uin, 'reactions.db')); - - // The converter context's four callbacks delegate to small, focused - // modules so this constructor doesn't carry the bridge-URL fetch - // branching or the mediaStore field-mapping fanout inline. const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache); const mediaIndexer = new MediaIndexer(this.mediaStore); this.converterCtx = { @@ -76,10 +72,6 @@ export class OneBotInstance { mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) => mediaIndexer.remember(mediaType, element, data, isGroup, sessionId), }; - - // Shared instance context. Only carries fields that are actually read - // through it — api handler and network manager stay as direct fields on - // the instance because nothing reads them via ctx. const ctx: OneBotInstanceContext = { uin: this.uin, selfId: parseInt(this.uin, 10) || 0, @@ -104,9 +96,6 @@ export class OneBotInstance { this.startHeartbeat(); this.rkeyCache.warmUp(this.bridge, this.uin); - - // Per-kind subscription on the typed event bus. Each bridge event kind - // gets its own focused handler in `event-pipeline`; the firehose is gone. this.disposeEventPipeline = registerEventPipeline(ctx); } @@ -152,10 +141,6 @@ export class OneBotInstance { private dispatchEvent(event: JsonObject): void { this.cacheMessageEvent(event); this.logReceivedMessage(event); - // NetworkManager builds the dispatch payload once and fans out to every - // active adapter in parallel via Promise.allSettled — per-adapter errors - // are already isolated, so the outer promise should never reject. The - // .catch is a belt-and-suspenders guard against future refactors. void this.networkManager.emitEvent(event).catch((err) => { this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); }); @@ -218,14 +203,11 @@ export class OneBotInstance { await this.networkManager.closeOne(adapter.name); } } - - // Reload existing adapters in place; spin up new ones the manager hasn't - // seen before. for (const [name, net] of desired) { const existing = this.networkManager.get(name); if (existing) { try { - await existing.reload(net as never); + await existing.reload(net); } catch (err) { this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err)); } @@ -333,9 +315,6 @@ export class OneBotInstance { }, }; } - - // --- Heartbeat --- - private startHeartbeat(): void { this.heartbeatTimer = setInterval(() => { this.dispatchEvent(this.makeHeartbeatEvent()); diff --git a/packages/onebot/src/manager.ts b/packages/onebot/src/manager.ts index dac92b2d..ed52586a 100644 --- a/packages/onebot/src/manager.ts +++ b/packages/onebot/src/manager.ts @@ -1,6 +1,6 @@ +import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import type { BridgeManager } from '@snowluma/core/manager'; -import { createLogger } from '@snowluma/common/logger'; import { loadOneBotConfig } from './config'; import { OneBotInstance } from './instance'; @@ -55,15 +55,10 @@ export class OneBotManager { if (activePid !== null) { instance.addPid(activePid); } - - // Seed nickname with the UIN so the WebUI never renders blank while - // warmup is in flight or if warmup never resolves a real nickname. if (!bridge.identity.nickname) bridge.identity.nickname = uin; this.instances.set(uin, instance); log.info('session started: UIN=%s', uin); - - // Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state) warmUpBridgeState(uin, bridge).catch((err) => { log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err)); }); diff --git a/packages/onebot/src/media-indexer.ts b/packages/onebot/src/media-indexer.ts index c87c9b10..4c4be292 100644 --- a/packages/onebot/src/media-indexer.ts +++ b/packages/onebot/src/media-indexer.ts @@ -1,7 +1,3 @@ -// Side-channel observer that watches every image / record / video -// segment emitted by the event converter and writes a row into the -// MediaStore so later `get_image` / `get_record` OneBot actions can - import type { MessageElement } from '@snowluma/protocol/events'; import type { MediaStore } from './media-store'; import type { JsonObject } from './types'; diff --git a/packages/onebot/src/media-store.ts b/packages/onebot/src/media-store.ts index 65cd074f..b9f3a0d8 100644 --- a/packages/onebot/src/media-store.ts +++ b/packages/onebot/src/media-store.ts @@ -1,31 +1,18 @@ -// Persistent media metadata store. -// -// The `get_image` / `get_record` actions need to map a `data.file` (or related -// identifier) we previously emitted in a message segment back to the URL, -// size, name, and any OIDB media-node info needed to re-resolve a stale URL. - -import fs from 'fs'; +import type { MessageElement } from '@snowluma/protocol/events'; import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; +import fs from 'fs'; import path from 'path'; -import type { MessageElement } from '@snowluma/protocol/events'; - export interface CachedImage { - /** Primary `data.file` value as exposed in the OneBot segment. */ file: string; - /** Last known resolved URL (may be empty if resolution failed). */ url: string; fileSize: number; fileName: string; subType: number; summary: string; - /** Conversation the media originated from. */ isGroup: boolean; sessionId: number; - /** Original imageUrl from the MessageElement, used for RKey re-appending. */ imageUrl: string; - /** Fingerprints used for md5/sha1 fast-upload on forward. Optional because - * legacy CustomFace / NotOnlineImage only carry md5. */ md5Hex?: string; sha1Hex?: string; width?: number; @@ -34,19 +21,14 @@ export interface CachedImage { } export interface CachedRecord { - /** Primary `data.file` value as exposed in the OneBot segment. */ file: string; - /** Raw fileId from the MessageElement (typically the fileUuid). */ fileId: string; - /** Last known resolved URL (may be empty if resolution failed). */ url: string; fileSize: number; fileName: string; duration: number; fileHash: string; - /** OIDB media node used to re-fetch the URL via getPtt*UrlByNode. */ mediaNode?: MessageElement['mediaNode']; - /** Conversation the media originated from (group vs private path). */ isGroup: boolean; sessionId: number; /** Fingerprints used for md5/sha1 fast-upload on forward. */ diff --git a/packages/onebot/src/media-url-resolver.ts b/packages/onebot/src/media-url-resolver.ts index f5f5dad3..a2cf4c1f 100644 --- a/packages/onebot/src/media-url-resolver.ts +++ b/packages/onebot/src/media-url-resolver.ts @@ -19,10 +19,6 @@ export class MediaUrlResolver { } return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup); } - - /** Branches by element.type + isGroup to pick the right Bridge API. - * Mutates `element.url` in-place so the caller sees the same URL - * the downstream rkey/media-store path will see. */ private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise { if (element.type === 'file' && element.fileId) { if (isGroup) { diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 9191f569..23f6fe3f 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -1,5 +1,6 @@ -import type { MessageElement } from '@snowluma/protocol/events'; import { createLogger } from '@snowluma/common/logger'; +import type { MessageElement } from '@snowluma/protocol/events'; +import { parseFromCQString } from './helper/cq'; import type { JsonValue } from './types'; const log = createLogger('MsgParser'); @@ -13,14 +14,8 @@ export interface ParseMessageOptions { // --- CQ Code parsing --- -const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g; +export const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g; -/** - * Best-effort base-10 integer coercion. Falls back to `fallback` (default 0) - * when the input can't be parsed as a finite integer — `parseInt('abc')` - * is `NaN`, which silently turns into `0`/`null` further down the wire - * pipeline and produces undebuggable protocol-level failures. - */ function intOr(value: unknown, fallback = 0): number { if (value === undefined || value === null) return fallback; if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback; @@ -28,7 +23,7 @@ function intOr(value: unknown, fallback = 0): number { return Number.isFinite(n) ? n : fallback; } -function parseCQParams(raw: string): Record { +export function parseCQParams(raw: string): Record { const params: Record = {}; if (!raw) return params; for (const pair of raw.split(',')) { @@ -44,43 +39,6 @@ function parseCQParams(raw: string): Record { return params; } -function cqUnescape(text: string): string { - // Order matters: `&` MUST be last so that, e.g., `&#91;` keeps - // the literal `[` instead of decoding twice into `[`. - return text - .replace(/[/g, '[') - .replace(/]/g, ']') - .replace(/,/g, ',') - .replace(/&/g, '&'); -} - -async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise { - const elements: MessageElement[] = []; - let lastIndex = 0; - - for (const match of message.matchAll(CQ_REGEX)) { - // Text before this CQ code - if (match.index! > lastIndex) { - const text = cqUnescape(message.substring(lastIndex, match.index!)); - if (text) elements.push({ type: 'text', text }); - } - lastIndex = match.index! + match[0].length; - - const cqType = match[1]; - const params = parseCQParams(match[2] || ''); - const elem = await segmentToElement(cqType, params, options); - if (elem) elements.push(elem); - } - - // Trailing text - if (lastIndex < message.length) { - const text = cqUnescape(message.substring(lastIndex)); - if (text) elements.push({ type: 'text', text }); - } - - return elements; -} - // --- JSON segment parsing --- interface MessageSegment { @@ -95,7 +53,7 @@ function isSegmentArray(val: unknown): val is MessageSegment[] { ); } -async function segmentToElement(type: string, data: Record, options?: ParseMessageOptions): Promise { +export async function segmentToElement(type: string, data: Record, options?: ParseMessageOptions): Promise { const normalizedType = type.toLowerCase(); switch (normalizedType) { case 'text': { @@ -120,10 +78,6 @@ async function segmentToElement(type: string, data: Record, opt if (!uid && options?.resolveMentionUid) { uid = (await options.resolveMentionUid(uin))?.trim() ?? ''; } - - // Leave `text` undefined when the caller didn't supply a display - // name. The element-builder then resolves it from the group roster - // (so QQ renders `@昵称` instead of `@QQ号`). const element: MessageElement = { type: 'at', targetUin: uin }; if (uid) element.uid = uid; if (name) element.text = `@${name} `; @@ -333,14 +287,6 @@ async function segmentToElement(type: string, data: Record, opt return null; } case 'file': { - // OneBot11 file segment referencing a previously-uploaded file - // (returned by `upload_group_file` / `upload_private_file`). - // We deliberately do NOT support `{file: '/path'}` here because - // the upload pipeline is async and lives behind the bridge — - // the element-builder runs synchronously over the parsed - // message. Callers that want upload-and-send should use the - // dedicated `upload_*` actions which now publish the file in - // chat atomically (`actions/group-file.ts`). const fileId = String(data.file_id ?? data.fileId ?? '').trim(); if (!fileId) { log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)'); @@ -350,10 +296,6 @@ async function segmentToElement(type: string, data: Record, opt const fileSize = intOr(data.size ?? data.fileSize, 0); const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim(); const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim(); - // file_hash is the c2c-file server-issued addon string — needed - // on the wire when re-sending a previously-uploaded c2c file. - // get_private_file_url callers already pass it through, so honour - // the same field naming here. const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim(); const elem: MessageElement = { type: 'file', fileId }; if (fileName) elem.fileName = fileName; @@ -381,14 +323,6 @@ function segmentPayload(seg: MessageSegment): Record { // --- Public API --- -/** - * Parse an OneBot11 message value into internal MessageElement array. - * Supports: - * - string (plain text or CQ code string) - * - array of { type, data } segments (JSON segment format) - * - * If autoEscape is true, the string is treated as plain text (no CQ parsing). - */ export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise { if (typeof message === 'string') { if (autoEscape) { diff --git a/packages/onebot/src/message-store.ts b/packages/onebot/src/message-store.ts index 32f70d52..c30a3946 100644 --- a/packages/onebot/src/message-store.ts +++ b/packages/onebot/src/message-store.ts @@ -1,21 +1,8 @@ -import fs from 'fs'; import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; +import fs from 'fs'; import path from 'path'; import type { JsonObject, MessageMeta } from './types'; -// Prepared statements are cached as `readonly` fields so the SQL parser -// runs once at construction time. Previously each `db.prepare(sql)` -// inside a hot-path method re-parsed on every call — the textbook -// SQLite anti-pattern. RoadMap #5 bench numbers showed -// storeMeta ≈ 17μs/op and storeEvent ≈ 23μs/op before caching; -// caching + better-sqlite3 drops both to single-digit-μs (see the -// commit-message numbers). -// -// Also: `node:sqlite` is still an experimental Node API (the -// "ExperimentalWarning: SQLite is an experimental feature" line shows -// up on every test run) — better-sqlite3 is the stable, sync, widely- -// deployed wrapper that proposes the same prepared-statement model. - export class MessageStore { private readonly db: DatabaseType; private readonly stmtStoreEvent: Statement; diff --git a/packages/onebot/src/modules/contact-actions.ts b/packages/onebot/src/modules/contact-actions.ts index 243a9fb5..62e44a67 100644 --- a/packages/onebot/src/modules/contact-actions.ts +++ b/packages/onebot/src/modules/contact-actions.ts @@ -9,13 +9,11 @@ export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nick return { userId, nickname }; } -// Keep refreshes scoped. A broad "refresh all members in all groups" call can -// turn one OneBot request into N OIDB calls, which is risky for busy clients. async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise { try { await bridge.apis.contacts.fetchGroupMemberList(groupId); } catch { - // Use cached data. + // 需要打log以便排查问题,但不应当让调用者感知到这个失败。 } } @@ -23,15 +21,15 @@ export async function getFriendList(bridge: BridgeInterface): Promise ({ - user_id: f.uin as any, - nickname: f.nickname as any, - remark: f.remark as any, + user_id: f.uin, + nickname: f.nickname, + remark: f.remark, })); } catch { return bridge.identity.friends.map(f => ({ - user_id: f.uin as any, - nickname: f.nickname as any, - remark: f.remark as any, + user_id: f.uin, + nickname: f.nickname, + remark: f.remark, })); } } @@ -48,10 +46,10 @@ export async function getGroupList( // Use cached data. } return bridge.identity.groups.map(g => ({ - group_id: g.groupId as any, - group_name: g.groupName as any, - member_count: g.memberCount as any, - max_member_count: g.memberMax as any, + group_id: g.groupId, + group_name: g.groupName, + member_count: g.memberCount, + max_member_count: g.memberMax, })); } @@ -70,10 +68,10 @@ export async function getGroupInfo( const g = bridge.identity.findGroup(groupId); if (!g) return null; return { - group_id: g.groupId as any, - group_name: g.groupName as any, - member_count: g.memberCount as any, - max_member_count: g.memberMax as any, + group_id: g.groupId, + group_name: g.groupName, + member_count: g.memberCount, + max_member_count: g.memberMax, }; } @@ -117,27 +115,27 @@ export async function getGroupFiles( const result = await bridge.apis.groupFile.list(groupId, folderId ?? '/'); return { files: result.files.map((file) => ({ - group_id: groupId as any, - file_id: file.fileId as any, - file_name: file.fileName as any, - busid: file.busId as any, - file_size: file.fileSize as any, - upload_time: file.uploadTime as any, - dead_time: file.deadTime as any, - modify_time: file.modifyTime as any, - download_times: file.downloadTimes as any, - uploader: file.uploader as any, - uploader_name: file.uploaderName as any, - } as JsonObject)) as any, + group_id: groupId, + file_id: file.fileId, + file_name: file.fileName, + busid: file.busId, + file_size: file.fileSize, + upload_time: file.uploadTime, + dead_time: file.deadTime, + modify_time: file.modifyTime, + download_times: file.downloadTimes, + uploader: file.uploader, + uploader_name: file.uploaderName, + } as JsonObject)), folders: result.folders.map((folder) => ({ - group_id: groupId as any, - folder_id: folder.folderId as any, - folder_name: folder.folderName as any, - create_time: folder.createTime as any, - creator: folder.creator as any, - create_name: folder.creatorName as any, - total_file_count: folder.totalFileCount as any, - } as JsonObject)) as any, + group_id: groupId, + folder_id: folder.folderId, + folder_name: folder.folderName, + create_time: folder.createTime, + creator: folder.creator, + create_name: folder.creatorName, + total_file_count: folder.totalFileCount, + } as JsonObject)), }; } @@ -148,27 +146,23 @@ export async function getStrangerInfo( try { const p = await bridge.apis.contacts.fetchUserProfile(userId); return { - user_id: p.uin as any, - nickname: p.nickname as any, - sex: p.sex as any, - age: p.age as any, - // NapCat-compatible field name (`qq_level`). Source: OIDB 0xFE1_2 - // number-property key 105 (Level), already requested via - // `fetchUserProfile`'s keys[]. Pre-fix this number was decoded - // but never surfaced. - qq_level: p.level as any, - level: p.level as any, + user_id: p.uin, + nickname: p.nickname, + sex: p.sex, + age: p.age, + qq_level: p.level, + level: p.level, }; } catch { const p = bridge.identity.findUserProfile(userId); if (!p) return null; return { - user_id: p.uin as any, - nickname: p.nickname as any, - sex: p.sex as any, - age: p.age as any, - qq_level: p.level as any, - level: p.level as any, + user_id: p.uin, + nickname: p.nickname, + sex: p.sex, + age: p.age, + qq_level: p.level, + level: p.level, }; } } @@ -184,7 +178,7 @@ export async function getGroupSystemMessages(bridge: BridgeInterface): Promise { const cached = mediaStore.findRecord(file); if (!cached) return null; - - // Re-resolve via OIDB if the cached URL is missing or empty. - // Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid. let url = cached.url; if (!url && cached.mediaNode) { try { @@ -43,7 +40,6 @@ export async function getRecordInfo( log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err)); } } - return { file: url || cached.file, url: url || '', diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index e90c8b4a..8b80c5e8 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -1,14 +1,14 @@ +import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events'; -import { createLogger } from '@snowluma/common/logger'; import type { MessageSendResult } from '../api-handler'; import { elementsToOneBotSegments } from '../event-converter'; -import { segmentsToRawMessage } from '../event-converter/utils'; +import { segmentsToRawMessage } from '../helper/cq'; +import type { OneBotInstanceContext } from '../instance-context'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id'; import { parseMessage } from '../message-parser'; import type { MessageStore } from '../message-store'; import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types'; -import type { OneBotInstanceContext } from '../instance-context'; const log = createLogger('OneBot'); diff --git a/packages/onebot/src/modules/request-actions.ts b/packages/onebot/src/modules/request-actions.ts index 5d15c8c9..29954e2b 100644 --- a/packages/onebot/src/modules/request-actions.ts +++ b/packages/onebot/src/modules/request-actions.ts @@ -6,7 +6,7 @@ export async function handleGroupAddRequest( approve: boolean, reason: string, ): Promise { - // flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter) + // flag format: "add:groupId:uid" or "invite:groupId:uid" const parts = flag.split(':'); if (parts.length < 3) throw new Error('invalid group request flag'); const requestType = parts[0]; @@ -26,7 +26,6 @@ export async function handleGroupAddRequest( if (!matching) { throw new Error('matching group request not found'); } - await bridge.apis.groupAdmin.setAddRequest( groupId, matching.sequence, diff --git a/packages/onebot/src/network/adapter.ts b/packages/onebot/src/network/adapter.ts index 7e194d53..8162707e 100644 --- a/packages/onebot/src/network/adapter.ts +++ b/packages/onebot/src/network/adapter.ts @@ -3,24 +3,16 @@ import type { DispatchPayload } from '../event-filter'; import type { JsonObject, NetworkBase } from '../types'; export interface NetworkAdapterContext { - /** Self UIN as string — written into outbound headers. */ uin: string; - /** Shared API dispatcher used by request/response style adapters. */ api: ApiHandler; - /** Build a lifecycle event payload (connect/enable/disable). */ buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject; - /** Build a heartbeat event payload. */ buildHeartbeatEvent(): JsonObject; } export enum NetworkReloadType { - /** Configuration unchanged or only soft fields updated. */ Normal = 0, - /** Underlying socket/listener restarted in place. */ Reopened = 1, - /** Was running, now closed. */ Closed = 2, - /** Was idle, now opened. */ Opened = 3, } @@ -32,25 +24,17 @@ export abstract class IOneBotNetworkAdapter { constructor(name: string, config: C, ctx: NetworkAdapterContext) { this.name = name; - // Defensive copy so reload diffs never mutate the caller's object. this.config = structuredClone(config); this.ctx = ctx; } - /** Whether the adapter is currently accepting/relaying events. */ get isActive(): boolean { return this.isEnabled; } - /** Snapshot of the active config (read-only). */ get currentConfig(): Readonly { return this.config; } abstract open(): void | Promise; abstract close(): void | Promise; abstract reload(config: C): NetworkReloadType | Promise; - /** - * Receive one fully-shaped OneBot event for forwarding. Adapters that - * don't push events (e.g. HTTP request-response servers) override with a - * no-op. - */ abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise; } diff --git a/packages/onebot/src/network/http-server-adapter.ts b/packages/onebot/src/network/http-server-adapter.ts index 565a07b1..0ef8084b 100644 --- a/packages/onebot/src/network/http-server-adapter.ts +++ b/packages/onebot/src/network/http-server-adapter.ts @@ -1,10 +1,10 @@ +import { createLogger, type Logger } from '@snowluma/common/logger'; import { createServer, type IncomingMessage, type Server, type ServerResponse, } from 'http'; -import { createLogger, type Logger } from '@snowluma/common/logger'; import type { DispatchPayload } from '../event-filter'; import type { HttpServerNetwork, JsonObject, JsonValue } from '../types'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; @@ -23,8 +23,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } override get isActive(): boolean { - // HTTP server never receives events — `isActive` purely tracks the - // bound listener so the network manager can skip dispatch cleanly. return this.isEnabled; } @@ -69,7 +67,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter return NetworkReloadType.Normal; } - // HTTP server only acts on inbound requests; it doesn't push events. onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ } private startServer(): void { @@ -95,12 +92,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise { - // Read `path` + `accessToken` fresh from `this.config` on every - // request so config hot-reloads (`reload()` overwrites `this.config` - // in place) take effect on the very next request without - // re-binding the listener. Matches the ws-server / http-post / - // ws-client adapters, which all read `this.config.accessToken` - // inline at the point of use. const expectedPath = normalizePath(this.config.path ?? '/'); const accessToken = this.config.accessToken ?? ''; const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1'); @@ -223,15 +214,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } function bindingSignature(net: HttpServerNetwork): string { - // `accessToken` deliberately omitted: it's read per-request from - // `this.config`, so a token change doesn't need to re-bind the - // listener. Including it here would cause a `close()` + `listen()` - // round trip on every token edit — a needless port-rebind that, on - // some hosts, races with the OS releasing the port and lands the - // server in a half-broken state where the old token still - // authenticates because the EADDRINUSE-failing new server never - // replaced the old one. `host`/`port`/`path` still gate a restart - // because Node's HTTP `Server.listen()` binds the socket on those. return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`; } diff --git a/packages/onebot/src/network/network-manager.ts b/packages/onebot/src/network/network-manager.ts index 5100d86b..8edab3c5 100644 --- a/packages/onebot/src/network/network-manager.ts +++ b/packages/onebot/src/network/network-manager.ts @@ -13,10 +13,11 @@ export class OneBotNetworkManager { register(adapter: IOneBotNetworkAdapter): void { const existing = this.adapters.get(adapter.name); if (existing) { - // Replacing an adapter under the same name — close the previous one - // before storing the new instance to keep ports/sockets clean. log.info('replacing adapter [%s]', adapter.name); - void Promise.resolve(existing.close()).catch(() => { /* best-effort */ }); + Promise.resolve(existing.close()).catch(() => { + /* best-effort */ + // 应该该打个日志以便排查问题,但不应当让调用者感知到这个失败。 + }); } this.adapters.set(adapter.name, adapter as AnyAdapter); } @@ -68,14 +69,6 @@ export class OneBotNetworkManager { } } - /** - * Dispatch one canonical OneBot event to every active adapter in parallel. - * The dispatch payload is built once so each adapter pays only the cost - * of picking the right pre-serialized variant. - * - * Errors thrown inside an adapter are isolated — one bad adapter never - * blocks the others. - */ async emitEvent(event: JsonObject): Promise { if (!this.hasActiveAdapters()) return; const payload = buildDispatchPayload(event); diff --git a/packages/onebot/src/network/utils.ts b/packages/onebot/src/network/utils.ts index 197c53c8..c65c7c87 100644 --- a/packages/onebot/src/network/utils.ts +++ b/packages/onebot/src/network/utils.ts @@ -1,7 +1,6 @@ import type { WebSocket } from '@snowluma/websocket'; import type { IncomingMessage } from 'http'; -/** Validate a request's bearer token / `?access_token=` query against the configured token. */ export function isAuthorized(request: IncomingMessage, token: string): boolean { if (!token) return true; const auth = request.headers.authorization ?? ''; @@ -25,7 +24,6 @@ export function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBuffer return ''; } -/** Best-effort send: drops payload if the socket isn't OPEN, reports send errors. */ export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void { if (socket.readyState !== 1 /* WebSocket.OPEN */) return; socket.send(payload, (error?: Error | null) => { @@ -33,20 +31,17 @@ export function safeSend(socket: WebSocket, payload: string, onError?: (err: Err }); } -/** Best-effort close, treats already-closed sockets as a no-op. */ export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void { if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return; socket.close(code, reason); } -/** Normalize an HTTP/WS path to a comparable form (strip trailing slash, default to "/"). */ export function normalizePath(pathValue: string | undefined): string { const path = (pathValue ?? '/').trim() || '/'; if (path === '/') return '/'; return path.endsWith('/') ? path.slice(0, -1) : path; } -/** Parse the `pathname` from a (potentially relative) WebSocket request URL. */ export function parseRequestPath(urlValue: string): string { try { return new URL(urlValue, 'ws://127.0.0.1').pathname; diff --git a/packages/onebot/src/reaction-store.ts b/packages/onebot/src/reaction-store.ts index ccfe0ffe..c1e05c59 100644 --- a/packages/onebot/src/reaction-store.ts +++ b/packages/onebot/src/reaction-store.ts @@ -1,24 +1,7 @@ +import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; import fs from 'fs'; import path from 'path'; -import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; -// Local cache of "who reacted with which emoji on which group message", -// fed from `GroupMsgEmojiLikeEvent` push events. Mirrors what NTQQ's -// internal wrapper cache stores — we maintain our own copy because -// SnowLuma runs outside the NTQQ process and can't directly call -// `NodeIKernelMsgService.getMsgEmojiLikesList`, and the OIDB SSO paths -// for "fetch users who reacted with emoji X" are all blocked by the -// server-side capability whitelist (cmds 0x9082_3..5, 0x9084_2..5, -// etc. exist but our client isn't authorized to call them). -// -// Limitations vs. the wrapper cache: -// - Only data from the bot's lifetime is captured. Reactions placed -// before the bot booted are invisible until either: -// (a) someone reacts again on that emoji (push event fires) -// (b) caller cross-checks against `fetchReactionSummary` to -// detect a count mismatch and warn the user -// - Push events occasionally drop in unreliable network conditions; -// periodic resync via 0x9084_1 summary can repair counts. export class ReactionStore { private readonly db: DatabaseType; private readonly stmtUpsert: Statement; diff --git a/packages/onebot/src/types.ts b/packages/onebot/src/types.ts index 61dd8a72..4235978b 100644 --- a/packages/onebot/src/types.ts +++ b/packages/onebot/src/types.ts @@ -1,9 +1,5 @@ -// Plain JSON types now live in @snowluma/common/json so @snowluma/protocol -// (event-format / receive parsers) can talk about JSON payloads without -// importing OneBot. Re-exported here so the legacy import shape stays -// supported — `import { JsonValue } from '<…>/onebot/types'` keeps working. -export type { JsonPrimitive, JsonValue, JsonObject, JsonArray } from '@snowluma/common/json'; -import type { JsonValue, JsonObject } from '@snowluma/common/json'; + +import type { JsonObject, JsonValue } from '@snowluma/common/json'; export interface ApiResponse { status: 'ok' | 'failed'; @@ -25,14 +21,6 @@ export type MessageFormat = 'array' | 'string'; export type NetworkKind = 'httpServers' | 'httpClients' | 'wsServers' | 'wsClients'; -/** - * Fields shared by every network adapter. `messageFormat` and - * `reportSelfMessage` live on the adapter itself — there is no global default - * fallback; each adapter is fully self-describing. - * - * The `name` is a free-form identifier scoped to the adapter's array; it is - * used for hot-reload bookkeeping and as a label in logs / WebUI. - */ export interface NetworkBase { name: string; /** When `false`, the adapter is configured but inactive. Defaults to `true`. */ @@ -68,10 +56,6 @@ export interface WsClientNetwork extends NetworkBase { reconnectIntervalMs?: number; } -/** - * Network adapters grouped by type. Each adapter is identified by `name` - * within its own array; hot-reload works on a per-(kind, name) basis. - */ export interface OneBotNetworks { httpServers: HttpServerNetwork[]; httpClients: HttpClientNetwork[]; @@ -119,3 +103,5 @@ export function failedResponse(retcode: number, wording: string): ApiResponse { wording, }; } +export type { JsonArray, JsonObject, JsonPrimitive, JsonValue } from '@snowluma/common/json'; +