diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..8c75d06c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = crlf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{json,yml,yaml,md}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false \ No newline at end of file diff --git a/RoadMap.md b/RoadMap.md index b5f929d8..8cd7f7d4 100644 --- a/RoadMap.md +++ b/RoadMap.md @@ -1,3 +1,9 @@ # V2.0.0 前计划 - [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。 -- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。 +- [x] 优化Debug体验,实现免打包Debug,同时数据目录正确。(Proton兜底思路改成ts+map提取类型,用于tsx和nodejs,vite正常打包的时候剥离) +- [x] 拆分core,架构为Common(公共能力) OneBot(外层封装 协议转换),Core(Api raw能力,基础能力等功能),Bridge(封装和关键解析能力和Event message/sent group/member_add ...) +- [x] 剥离ProtocolBuffer定义到单独package。 +- [x] 整理发送和解析消息链路,提高性能。`packages/{bridge,onebot}/bench/*.bench.ts` 拿到了基线数字。最大瓶颈不在 protobuf 解析(已经 sub-μs),而在两处 SQLite 反复 `db.prepare(sql)` 重 parse —— 把 `node:sqlite`(实验性)换成 `better-sqlite3`(稳定)+ 缓存 prepared statements 后:`group_member_join` 全链路 17.5μs → 4.7μs(**3.7x**),`storeMeta` 17μs → 11μs,`storeEvent` 23μs → 18μs,`findMeta` 5.4μs → 1.3μs(**4x**)。送侧组合 hot path(storeMeta + storeEvent)单条消息 40μs → 29μs。另外干掉 `Buffer.from(pkt.body)` 的冗余 alloc(pkt.body 本来就是 Uint8Array)。`elementsToJson` 同步快路径 / WAL checkpoint 调参 / JSON 序列化替换 等次要优化点保留,待真有 throughput 压力再做。 +- [x] 对齐NapCat设计采用Api层,挂到ctx,Core与Onebot都这么设计。 + - [x] Core 侧:13 个 Api 类(message/contacts/groupAdmin/groupFile/groupAlbum/interaction/friend/profile/forward/misc/extras/web)已挂到 `bridge.apis..method()`,`BridgeInterface` + `actions/*` 全部删除。 + - [x] OneBot 侧:`ApiActionContext` 砍掉 ~40 个纯转发字段(groupAdmin / groupFile / groupAlbum / friend / interaction / message / profile / web 八区),actions 直接 `ctx.bridge.apis..method(...)` 调用 Core 的 Api 层。保留的 ~30 个字段全是真组合 helper(module-level send/forward、message store reads、meta-lookup composers)。完全 NapCat 化(class-per-action / TypeBox schema / actionName 枚举 / auto-register decorator)暂未做——profile 文档/工具链需求出现后再做。 diff --git a/eslint.config.ts b/eslint.config.ts new file mode 100644 index 00000000..3318e517 --- /dev/null +++ b/eslint.config.ts @@ -0,0 +1,80 @@ +import js from '@eslint/js'; +import globals from 'globals'; +import reactHooks from 'eslint-plugin-react-hooks'; +import reactRefresh from 'eslint-plugin-react-refresh'; +import tseslint from 'typescript-eslint'; +import { defineConfig, globalIgnores } from 'eslint/config'; + +const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1'); + +export default defineConfig([ + globalIgnores([ + '**/dist/**', + '**/node_modules/**', + '**/coverage/**', + '**/.turbo/**', + '**/.vite/**', + '**/*.tsbuildinfo', + '**/test/fixtures/**', + 'packages/runtime/native/**', + ]), + { + files: ['**/*.{js,mjs,cjs,ts,tsx}'], + extends: [js.configs.recommended], + languageOptions: { + ecmaVersion: 2023, + sourceType: 'module', + globals: { + ...globals.es2023, + ...globals.node, + }, + }, + rules: { + 'indent': ['error', 2, { SwitchCase: 1 }], + 'no-unused-vars': 'off', + 'no-useless-assignment': 'off', + 'prefer-const': 'off', + 'preserve-caught-error': 'off', + }, + }, + { + files: ['**/*.{ts,tsx}'], + extends: [tseslint.configs.recommended], + languageOptions: { + parserOptions: { + tsconfigRootDir, + }, + }, + rules: { + 'indent': ['error', 2, { SwitchCase: 1 }], + 'prefer-const': 'off', + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-empty-object-type': 'off', + '@typescript-eslint/no-this-alias': 'off', + '@typescript-eslint/no-unused-vars': [ + 'warn', + { + argsIgnorePattern: '^_', + varsIgnorePattern: '^_', + caughtErrorsIgnorePattern: '^_', + }, + ], + }, + }, + { + files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'], + extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite], + languageOptions: { + globals: globals.browser, + parserOptions: { + tsconfigRootDir, + }, + }, + rules: { + 'indent': ['error', 2, { SwitchCase: 1 }], + 'prefer-const': 'off', + 'react-refresh/only-export-components': 'off', + 'react-hooks/set-state-in-effect': 'off', + }, + }, +]); \ No newline at end of file diff --git a/package.json b/package.json index e131e7c6..b53a6379 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.9.0", + "version": "1.9.1", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", @@ -15,21 +15,32 @@ "test": "pnpm --filter @snowluma/core test", "test:watch": "pnpm --filter @snowluma/core test:watch", "typecheck": "pnpm -r --if-present typecheck", - "lint": "pnpm -r --if-present lint", + "lint": "eslint .", + "lint:fix": "eslint . --fix", "start": "node dist/index.mjs", "bump": "node tools/bump-version.mjs", "release": "node tools/release.mjs" }, "devDependencies": { + "@eslint/js": "^10.0.1", "cross-env": "^10.1.0", - "typescript": "catalog:" + "eslint": "^10.2.0", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.5.0", + "jiti": "^2.6.1", + "typescript": "catalog:", + "typescript-eslint": "^8.58.2" }, "pnpm": { "peerDependencyRules": { "allowedVersions": { "eslint-plugin-react-hooks>eslint": "10" } - } + }, + "onlyBuiltDependencies": [ + "better-sqlite3" + ] }, "packageManager": "pnpm@10.28.0", "engines": { diff --git a/packages/bridge/bench/recv.bench.ts b/packages/bridge/bench/recv.bench.ts new file mode 100644 index 00000000..1ff63838 --- /dev/null +++ b/packages/bridge/bench/recv.bench.ts @@ -0,0 +1,176 @@ +// Receive-chain micro-benchmark (RoadMap #5). +// +// Measured paths: +// 1. `parseMsgPush` — pure decode + decoder dispatch (no SQLite, no +// event emit). The protobuf workload only. +// 2. `IncomingPacketPipeline.process` — full receive pipeline: +// decode + decoder + handleSideEffects (identity-service SQLite +// writes) + event emit through BridgeEventBus. +// +// Run via: pnpm -F @snowluma/bridge bench +// +// Output is `tinybench` ops/sec — vitest's built-in `bench()` is just a +// thin wrapper. Run before AND after a perf commit; the delta is what +// matters (RoadMap #5 commit messages quote the % shift). + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { bench, describe } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import type { PushMsg } from '@snowluma/proto-defs/message'; +import type { GroupChange } from '@snowluma/proto-defs/notify'; +import { parseMsgPush, MSG_PUSH_CMD } from '../src/msg-push/index'; +import { IdentityService } from '../src/identity-service'; +import { BridgeEventBus } from '../src/event-bus'; +import { IncomingPacketPipeline } from '../src/packet-pipeline'; + +const SELF_UIN = '10001'; +const GROUP_ID = 123456789; +const SENDER_UIN = 22222; +const SENDER_UID = 'u_sender'; + +// ─── Synthetic packet builders ─── + +function makeGroupTextPacket(): PacketInfo { + const body = protobuf_encode({ + message: { + responseHead: { fromUin: SENDER_UIN, fromUid: SENDER_UID }, + contentHead: { + msgType: 82, + subType: 1, + sequence: 1234, + timestamp: 1710000000, + msgId: 999999, + }, + body: { + richText: { + elems: [{ text: { str: 'hello world from bench' } }], + }, + }, + }, + status: 0, + grpInfo: { groupUin: GROUP_ID }, + } as any); + return { + pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, + seqId: 1, retCode: 0, fromClient: false, body, + }; +} + +function makeGroupMixedPacket(): PacketInfo { + const body = protobuf_encode({ + message: { + responseHead: { fromUin: SENDER_UIN, fromUid: SENDER_UID }, + contentHead: { + msgType: 82, + subType: 1, + sequence: 1235, + timestamp: 1710000000, + msgId: 999998, + }, + body: { + richText: { + elems: [ + { text: { str: '@some_user ' } }, + { face: { index: 76 } }, + { text: { str: 'hello ' } }, + { srcMsg: { origSeqs: [4242] } }, + { text: { str: ' world' } }, + ], + }, + }, + }, + status: 0, + grpInfo: { groupUin: GROUP_ID }, + } as any); + return { + pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, + seqId: 2, retCode: 0, fromClient: false, body, + }; +} + +function makeGroupJoinPacket(): PacketInfo { + const content = protobuf_encode({ + groupUin: GROUP_ID, + memberUid: 'u_newcomer', + }); + const body = protobuf_encode({ + message: { + responseHead: { fromUin: GROUP_ID }, + contentHead: { msgType: 33, timestamp: 1710000000 }, + body: { msgContent: content }, + }, + status: 0, + } as any); + return { + pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, + seqId: 3, retCode: 0, fromClient: false, body, + }; +} + +// ─── Setup helpers ─── + +// In-memory identity (no SQLite writes) — used for the "pure decode" +// bench to isolate proton + decoder cost from DB cost. +function makeIdentity(): IdentityService { + return IdentityService.memory(SELF_UIN); +} + +// SQLite-backed identity in a temp file — used for the full-pipeline +// bench so we capture per-event identity writes. Temp dir is cleaned +// implicitly on process exit (OS tmp policy); we don't need to unlink +// because each `bench()` recreates it. +function makeIdentityWithDb(): IdentityService { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-bench-recv-')); + return new IdentityService(SELF_UIN, path.join(dir, 'identity.db')); +} + +function makePipeline(identity: IdentityService): IncomingPacketPipeline { + const events = new BridgeEventBus(); + events.on('group_message', () => { /* drain */ }); + events.on('group_member_join', () => { /* drain */ }); + const pipeline = new IncomingPacketPipeline({ + identity, + events, + refreshMemberCache: async () => false, + }); + pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush); + return pipeline; +} + +// ─── Benches ─── + +const groupText = makeGroupTextPacket(); +const groupMixed = makeGroupMixedPacket(); +const groupJoin = makeGroupJoinPacket(); + +describe('parseMsgPush — pure decode + dispatch (no SQLite, no emit)', () => { + const identityPure = makeIdentity(); + bench('group_message (text only)', () => { + parseMsgPush(groupText, identityPure); + }); + bench('group_message (5 mixed elements)', () => { + parseMsgPush(groupMixed, identityPure); + }); + bench('group_member_join', () => { + parseMsgPush(groupJoin, identityPure); + }); +}); + +describe('IncomingPacketPipeline.process — full pipeline (with SQLite identity writes)', () => { + const pipelineText = makePipeline(makeIdentityWithDb()); + const pipelineMixed = makePipeline(makeIdentityWithDb()); + const pipelineJoin = makePipeline(makeIdentityWithDb()); + + bench('group_message (text only)', () => { + pipelineText.process(groupText); + }); + bench('group_message (5 mixed elements)', () => { + pipelineMixed.process(groupMixed); + }); + bench('group_member_join', () => { + pipelineJoin.process(groupJoin); + }); +}); diff --git a/packages/bridge/package.json b/packages/bridge/package.json new file mode 100644 index 00000000..6c3ac96b --- /dev/null +++ b/packages/bridge/package.json @@ -0,0 +1,131 @@ +{ + "name": "@snowluma/bridge", + "version": "1.9.1", + "private": true, + "type": "module", + "description": "SnowLuma bridge — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/bridge/'`.", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./events": { + "types": "./src/events.ts", + "default": "./src/events.ts" + }, + "./event-bus": { + "types": "./src/event-bus.ts", + "default": "./src/event-bus.ts" + }, + "./identity-service": { + "types": "./src/identity-service.ts", + "default": "./src/identity-service.ts" + }, + "./packet-pipeline": { + "types": "./src/packet-pipeline.ts", + "default": "./src/packet-pipeline.ts" + }, + "./element-builder": { + "types": "./src/element-builder.ts", + "default": "./src/element-builder.ts" + }, + "./bridge-oidb": { + "types": "./src/bridge-oidb.ts", + "default": "./src/bridge-oidb.ts" + }, + "./bridge-context": { + "types": "./src/bridge-context.ts", + "default": "./src/bridge-context.ts" + }, + "./qq-info": { + "types": "./src/qq-info.ts", + "default": "./src/qq-info.ts" + }, + "./format": { + "types": "./src/format.ts", + "default": "./src/format.ts" + }, + "./msg-push": { + "types": "./src/msg-push/index.ts", + "default": "./src/msg-push/index.ts" + }, + "./msg-push/registry": { + "types": "./src/msg-push/registry.ts", + "default": "./src/msg-push/registry.ts" + }, + "./msg-push/context": { + "types": "./src/msg-push/context.ts", + "default": "./src/msg-push/context.ts" + }, + "./msg-push/decoders/event-0x2dc": { + "types": "./src/msg-push/decoders/event-0x2dc.ts", + "default": "./src/msg-push/decoders/event-0x2dc.ts" + }, + "./highway": { + "types": "./src/highway/highway-client.ts", + "default": "./src/highway/highway-client.ts" + }, + "./highway/utils": { + "types": "./src/highway/utils.ts", + "default": "./src/highway/utils.ts" + }, + "./highway/pipeline": { + "types": "./src/highway/pipeline.ts", + "default": "./src/highway/pipeline.ts" + }, + "./highway/image-upload": { + "types": "./src/highway/image-upload.ts", + "default": "./src/highway/image-upload.ts" + }, + "./highway/ptt-upload": { + "types": "./src/highway/ptt-upload.ts", + "default": "./src/highway/ptt-upload.ts" + }, + "./highway/video-upload": { + "types": "./src/highway/video-upload.ts", + "default": "./src/highway/video-upload.ts" + }, + "./highway/ffmpeg-addon": { + "types": "./src/highway/ffmpeg-addon.ts", + "default": "./src/highway/ffmpeg-addon.ts" + }, + "./web/group-album": { + "types": "./src/web/group-album.ts", + "default": "./src/web/group-album.ts" + }, + "./web/group-essence": { + "types": "./src/web/group-essence.ts", + "default": "./src/web/group-essence.ts" + }, + "./web/group-honor": { + "types": "./src/web/group-honor.ts", + "default": "./src/web/group-honor.ts" + }, + "./web/group-notice": { + "types": "./src/web/group-notice.ts", + "default": "./src/web/group-notice.ts" + }, + "./web/request-util": { + "types": "./src/web/request-util.ts", + "default": "./src/web/request-util.ts" + } + }, + "scripts": { + "bench": "vitest bench --run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@snowluma/common": "workspace:*", + "@snowluma/proto-defs": "workspace:*", + "@snowluma/proton": "workspace:*", + "@snowluma/sqlite": "workspace:*" + }, + "devDependencies": { + "@types/node": "^24.12.2", + "typescript": "catalog:", + "vite": "catalog:", + "vitest": "^4.1.4" + } +} diff --git a/packages/bridge/src/bridge-context.ts b/packages/bridge/src/bridge-context.ts new file mode 100644 index 00000000..63a371f7 --- /dev/null +++ b/packages/bridge/src/bridge-context.ts @@ -0,0 +1,81 @@ +// BridgeContext — the protocol-layer surface that anything inside +// @snowluma/bridge (highway uploaders, OIDB envelope helper, element +// builder, msg-push parsers) accepts when it needs `bridge.identity` +// or `bridge.sendRawPacket` plus the upload-metadata cache. +// +// Deliberately apis-less: @snowluma/bridge knows nothing about the +// `apis..method()` hub that lives in @snowluma/core, so the +// type that bridge code accepts must NOT mention `ApiHub`. The api- +// layer's own extended context (with `apis: ApiHub`) lives at +// @snowluma/core's same-named file and `extends` this one — Api +// classes import from THERE, bridge helpers import from HERE. +// +// The concrete `Bridge` class (in @snowluma/core) implements the +// extended interface, which is a superset of this one. Passing a +// `Bridge` where a slim `BridgeContext` is expected is a free upcast. + +import type { IdentityService } from './identity-service'; +import type { BridgeEventBus } from './event-bus'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +/** + * Metadata remembered after `upload_group_file` / `upload_private_file` + * succeeds. Lets the OneBot send-message path reconstruct the full + * payload when the caller only echoes the `file_id` back later. Lives + * here (not on @snowluma/core's `bridge.ts`) so element-builder + the + * forward-builder — both inside @snowluma/bridge — can read the cache + * without circular-importing @snowluma/core. + */ +export interface UploadedFileMeta { + fileId: string; + scope: 'group' | 'private'; + /** Group id if scope='group', else `undefined`. */ + groupId?: number; + /** Friend uin if scope='private', else `undefined`. */ + userId?: number; + fileName: string; + fileSize: number; + fileMd5: Uint8Array; + fileSha1: Uint8Array; + /** Server-issued hash returned alongside the upload (private only). */ + fileHash?: string; + /** Insert time — used to evict the oldest entry when the cache fills. */ + rememberedAt: number; +} + +export interface BridgeContext { + // ── Per-instance state (one set per QQ account in a multi-account + // runtime; `BridgeManager` allocates one `Bridge` per uin and + // each Bridge owns its own identity/events/pipeline/apis). ── + readonly identity: IdentityService; + readonly events: BridgeEventBus; + + // ── Raw I/O ── + /** Escape hatch for arbitrary protocol calls (used by Api classes + * and by the `send_packet` OneBot action). Every typed wrapper on an + * Api class eventually routes through here. */ + sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise; + /** uin → uid lookup (cached in IdentityService). `groupId` is an + * optional hint that lets the resolver fall back to a group-member + * roster when the friend list doesn't have the uin. */ + resolveUserUid(uin: number, groupId?: number): Promise; + + // ── Send-side protocol helpers (Api classes that build a + // `SendMessageRequest` need these monotonic generators to fill in + // `clientSequence` and `random`). They were previously `private` + // on Bridge — promoted to public so the new Api classes can call + // them without `(bridge as any).nextXxx()`. ── + nextMessageRandom(): number; + nextClientSequence(): number; + + // ── Uploaded-file metadata cache ── + // + // Bookkeeping shared between `GroupFileApi.upload*File` (writes the + // tuple at upload time) and `MessageApi.sendPrivateMessage` (reads + // it on later `send_msg` calls that carry only a file_id). Lives at + // this layer rather than inside `GroupFileApi` because the message + // send path is what queries the cache, and it shouldn't have to + // reach into a different Api class for an infrastructure lookup. + rememberUploadedFile(meta: UploadedFileMeta): void; + recallUploadedFile(fileId: string): UploadedFileMeta | undefined; +} diff --git a/packages/bridge/src/bridge-oidb.ts b/packages/bridge/src/bridge-oidb.ts new file mode 100644 index 00000000..7f618b8c --- /dev/null +++ b/packages/bridge/src/bridge-oidb.ts @@ -0,0 +1,66 @@ +import { protobuf_decode } from '@snowluma/proton'; +import type { BridgeContext } from './bridge-context'; +import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb'; + +/** + * Build the OidbBase-shaped TS value. Pure helper, no protobuf + * encoding happens here — pair with `encodeOidbEnv` to produce the + * wire bytes. + * + * The `isUid` flag sets the envelope `reserved` field to 1; despite the + * name (kept for back-compat with the legacy API), `reserved = 1` + * empirically signals the UIN-form variant of an OIDB call. Omit + * (default false) for genuinely UID-keyed calls. + */ +export function makeOidbEnvelope( + oidbCmd: number, + subCmd: number, + body: T, + isUid: boolean = false, +): OidbBase { + return { + command: oidbCmd, + subCommand: subCmd, + errorCode: 0, + body, + errorMsg: '', + reserved: isUid ? 1 : 0, + }; +} + +/** + * Issue one OIDB request and return the raw response bytes. + * + * Typical usage: + * const env = makeOidbEnvelope(0x1253, 1, value); + * const buf = await runOidb(bridge, cmd, encodeOidbEnv(env)); + * const resp = decodeOidbEnv(buf).body; + * + * Fire-and-check (no body decode): + * await runOidb(bridge, cmd, encodeOidbEnv(env)); + * + * Always peeks at the envelope errorCode via the non-generic + * `OidbBaseMeta` view so a server-side rejection cannot slip past + * silently. Returns the raw response bytes (empty `Uint8Array` if the + * packet carried no payload). + */ +export async function runOidb( + bridge: BridgeContext, + cmd: string, + envelopeBytes: Uint8Array, + timeoutMs?: number, +): Promise { + const result = await bridge.sendRawPacket(cmd, envelopeBytes, timeoutMs); + if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); + if (!result.gotResponse) throw new Error(result.errorMessage || 'no response'); + + const bytes = result.responseData ?? new Uint8Array(0); + if (bytes.length > 0) { + const meta = protobuf_decode(bytes); + const code = meta?.errorCode; + if (code && code !== 0) { + throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`); + } + } + return bytes; +} diff --git a/packages/core/src/bridge/element-builder.ts b/packages/bridge/src/element-builder.ts similarity index 91% rename from packages/core/src/bridge/element-builder.ts rename to packages/bridge/src/element-builder.ts index 96e7e78d..8e39da2d 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/bridge/src/element-builder.ts @@ -1,28 +1,20 @@ -// Element Builder — converts internal MessageElement[] into proto Elem objects -// for encoding with protoEncode(SendMessageRequestSchema). -// Port of src/bridge/src/bridge_messages.cpp build_send_elems() - -import type { Bridge } from './bridge'; -import type { MessageElement } from './events'; -import type { ProtoDecoded } from '../protobuf/decode'; import { protobuf_encode } from '@snowluma/proton'; -import { - ElemSchema, -} from './proto/element'; -import type { - MentionExtraSend, - MarkdownData, -} from './proto/proton/action'; -import type { GroupFileExtra } from './proto/proton/element'; +import type { BridgeContext } from './bridge-context'; +import type { MessageElement } from './events'; import { uploadImageMsgInfo } from './highway/image-upload'; +import { hexToBytes } from './highway/pipeline'; import { uploadPttMsgInfo } from './highway/ptt-upload'; import { uploadVideoMsgInfo } from './highway/video-upload'; -import { hexToBytes } from './highway/pipeline'; +import type { + MarkdownData, + MentionExtraSend, +} from '@snowluma/proto-defs/action'; +import type { Elem, GroupFileExtra } from '@snowluma/proto-defs/element'; -type ProtoElem = Partial>; +type ProtoElem = Partial; export interface SendContext { - bridge: Bridge; + bridge: BridgeContext; groupId?: number; userUid?: string; /** @@ -95,11 +87,11 @@ function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem function makeReplyElem(element: MessageElement): ProtoElem { const seq = element.replySeq! & 0xFFFFFFFF; - + const srcMsg: any = { origSeqs: [seq], }; - + // Add additional fields if available for better reply display if (element.replySenderUin) { srcMsg.senderUin = BigInt(element.replySenderUin); @@ -107,7 +99,7 @@ function makeReplyElem(element: MessageElement): ProtoElem { if (element.replyTime) { srcMsg.time = element.replyTime; } - + return { srcMsg }; } @@ -264,18 +256,31 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise

= Extract; diff --git a/packages/core/src/bridge/events.ts b/packages/bridge/src/events.ts similarity index 98% rename from packages/core/src/bridge/events.ts rename to packages/bridge/src/events.ts index dcfe20ac..6ca1cf51 100644 --- a/packages/core/src/bridge/events.ts +++ b/packages/bridge/src/events.ts @@ -1,6 +1,3 @@ -// Bridge event types and MessageElement. -// Port of src/bridge/include/bridge/events.h - export interface MessageElement { type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward' text?: string; diff --git a/packages/core/src/utils/event-format.ts b/packages/bridge/src/format.ts similarity index 91% rename from packages/core/src/utils/event-format.ts rename to packages/bridge/src/format.ts index 243f098a..f6f641e3 100644 --- a/packages/core/src/utils/event-format.ts +++ b/packages/bridge/src/format.ts @@ -1,18 +1,18 @@ -// Identity-aware, one-line readable rendering for log output. -// -// Two layers consume this: -// - bridge/packet-pipeline.ts → notice events (recall / join / poke / …) -// - onebot/instance.ts → received-message log -// -// All formatters are defensive: any field lookup that throws falls -// back to the raw numeric form, so a malformed event or stale -// Identity cache never crashes the logger. Cache misses simply -// degrade to the previous "just print the uin / groupId" output. +import type { QQEventVariant } from './events'; +import type { IdentityService } from './identity-service'; +import type { JsonObject, JsonValue } from '@snowluma/common/json'; -import type { IdentityService } from '../bridge/identity-service'; -import type { QQEventVariant } from '../bridge/events'; -import type { MessageStore } from '../onebot/message-store'; -import type { JsonObject, JsonValue } from '../onebot/types'; +/** + * Minimal shape of the OneBot-side `MessageStore` that `formatReply` + * needs — just `findEvent(id)`. Defined inline (instead of importing + * the full `MessageStore` class from @snowluma/onebot) so this + * package doesn't depend on the OneBot layer above it. The OneBot + * `MessageStore` is structurally a superset of this interface, so + * callers pass it through with zero adaptation. + */ +export interface ReplyEventLookup { + findEvent(messageId: number): JsonObject | null; +} const MAX_TEXT_PREVIEW = 50; const MAX_REPLY_BODY_PREVIEW = 30; @@ -121,7 +121,7 @@ function truncate(s: string, max: number): string { * to" questions. */ export function formatReply( - messageStore: MessageStore, + messageStore: ReplyEventLookup, identity: IdentityService, replyId: number, ): string { diff --git a/packages/core/src/bridge/highway/ffmpeg-addon.ts b/packages/bridge/src/highway/ffmpeg-addon.ts similarity index 94% rename from packages/core/src/bridge/highway/ffmpeg-addon.ts rename to packages/bridge/src/highway/ffmpeg-addon.ts index df5cde3f..c4b69ce5 100644 --- a/packages/core/src/bridge/highway/ffmpeg-addon.ts +++ b/packages/bridge/src/highway/ffmpeg-addon.ts @@ -1,14 +1,7 @@ -// FFmpeg native addon wrapper — port of NapCat's FFmpegAddonAdapter. -// No fallback: throws if the addon isn't available on this platform/arch. -// -// The addon is shipped under `native/ffmpeg/ffmpegAddon...node` -// to match the layout used by the upstream NapCat build so the binaries -// can be dropped in as-is. - +import crypto from 'crypto'; import fs from 'fs'; import os from 'os'; import path from 'path'; -import crypto from 'crypto'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); diff --git a/packages/core/src/bridge/highway/highway-client.ts b/packages/bridge/src/highway/highway-client.ts similarity index 94% rename from packages/core/src/bridge/highway/highway-client.ts rename to packages/bridge/src/highway/highway-client.ts index bab560f8..963a92dd 100644 --- a/packages/core/src/bridge/highway/highway-client.ts +++ b/packages/bridge/src/highway/highway-client.ts @@ -1,17 +1,14 @@ -// Highway HTTP client: session fetch and chunked binary upload. -// Port of src/bridge/src/highway_client.cpp - +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import net from 'net'; -import type { Bridge } from '../bridge'; -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { BridgeContext } from '../bridge-context'; import type { HttpConn0x6FF501Request, HttpConn0x6FF501Response, + NTV2RichMediaHighwayExt, ReqDataHighwayHead, RespDataHighwayHead, - NTV2RichMediaHighwayExt, -} from '../proto/proton/highway'; -import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils'; +} from '@snowluma/proto-defs/highway'; +import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils'; const HIGHWAY_APP_ID = 1600001604; const HIGHWAY_BLOCK_SIZE = 1024 * 1024; @@ -30,7 +27,7 @@ function ipv4ToString(value: number): string { return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`; } -export async function fetchHighwaySession(bridge: Bridge): Promise { +export async function fetchHighwaySession(bridge: BridgeContext): Promise { const request = protobuf_encode({ httpConn: { field1: 0, field2: 0, field3: 16, field4: 1, field6: 3, @@ -221,7 +218,7 @@ async function httpPostFrame( } export async function uploadHighwayHttp( - bridge: Bridge, session: HighwaySession, commandId: number, + bridge: BridgeContext, session: HighwaySession, commandId: number, bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array, ): Promise { const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`; diff --git a/packages/core/src/bridge/highway/image-upload.ts b/packages/bridge/src/highway/image-upload.ts similarity index 91% rename from packages/core/src/bridge/highway/image-upload.ts rename to packages/bridge/src/highway/image-upload.ts index 6d43e303..dbdba3d4 100644 --- a/packages/core/src/bridge/highway/image-upload.ts +++ b/packages/bridge/src/highway/image-upload.ts @@ -1,13 +1,6 @@ -// Image upload: load the source, run NTV2 upload + (optional) Highway PUT, -// return the encoded MsgInfo for the outgoing commonElem. -// -// Shared OIDB envelope + response handling + Highway PUT live in -// pipeline.ts; this file just supplies the image-specific bits (format -// detection, picFormat, bizType, command ids). - -import type { Bridge } from '../bridge'; +import { createLogger } from '@snowluma/common/logger'; +import type { BridgeContext } from '../bridge-context'; import type { MessageElement } from '../events'; -import { createLogger } from '../../utils/logger'; import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client'; import { finalizeMediaMsgInfo, @@ -19,7 +12,7 @@ import { computeHashes, detectImageFormat, loadBinarySource } from './utils'; const moduleLog = createLogger('Highway.Image'); -function loggerFor(bridge: Bridge) { +function loggerFor(bridge: BridgeContext) { const raw = bridge.identity?.uin; const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog; @@ -110,7 +103,7 @@ async function loadImageFromSource(source: string, fileName: string, subType: nu * commonElem. */ export async function uploadImageMsgInfo( - bridge: Bridge, + bridge: BridgeContext, isGroup: boolean, targetIdOrUid: string | number, element: MessageElement, diff --git a/packages/core/src/bridge/highway/pipeline.ts b/packages/bridge/src/highway/pipeline.ts similarity index 88% rename from packages/core/src/bridge/highway/pipeline.ts rename to packages/bridge/src/highway/pipeline.ts index 86b0be53..7eb0e551 100644 --- a/packages/core/src/bridge/highway/pipeline.ts +++ b/packages/bridge/src/highway/pipeline.ts @@ -1,31 +1,15 @@ -// Shared NTV2 rich-media upload pipeline. -// -// Image, PTT, and video all follow the same three-step shape: -// 1. send a NTV2UploadRichMediaReq OIDB packet describing the file(s), -// 2. for any sub-file the server signals it wants (uKey present in the -// response), do a Highway HTTP PUT of the bytes, -// 3. encode the returned msgInfo into the bytes that go inside a -// commonElem on the outgoing message. -// -// The per-format files (image-upload, ptt-upload, video-upload) used to -// each implement steps 1 / 2 / 3 inline with subtle drift between them. -// This module pulls the envelope, response decoding, error handling, and -// the Highway PUT loop into one place, leaving each format file with -// only: how to load the file, how to fill the type-specific fileInfo + -// extBizInfo, and which command ids to use. - +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import crypto from 'crypto'; - -import type { Bridge } from '../bridge'; -import { protobuf_encode } from '@snowluma/proton'; -import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import { createLogger } from '@snowluma/common/logger'; +import type { BridgeContext } from '../bridge-context'; +import { makeOidbEnvelope } from '../bridge-oidb'; import type { EncodableMediaMsgInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp, -} from '../proto/proton/highway'; +} from '@snowluma/proto-defs/highway'; +import { OidbBase } from '@snowluma/proto-defs/oidb'; import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client'; -import { createLogger } from '../../utils/logger'; const moduleLog = createLogger('Highway'); @@ -66,7 +50,7 @@ export interface MediaSubFileUpload { } export interface NtV2UploadParams { - bridge: Bridge; + bridge: BridgeContext; isGroup: boolean; /** Group uin when isGroup, otherwise the recipient's uid string. */ targetIdOrUid: string | number; @@ -160,14 +144,14 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { }; const env = makeOidbEnvelope(oidbCmd, 100, body, true); - const requestBytes = encodeOidbEnv(env); + const requestBytes = protobuf_encode>(env); const result = await bridge.sendRawPacket(serviceCmd, requestBytes); if (!result.success || !result.gotResponse || !result.responseData) { throw new Error(result.errorMessage || `${label} upload request failed`); } - const resp = decodeOidbEnv(result.responseData); + const resp = protobuf_decode>(result.responseData); if (!resp) throw new Error(`failed to decode ${label} upload response`); if (resp.errorCode && resp.errorCode !== 0) { throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`); diff --git a/packages/core/src/bridge/highway/ptt-upload.ts b/packages/bridge/src/highway/ptt-upload.ts similarity index 92% rename from packages/core/src/bridge/highway/ptt-upload.ts rename to packages/bridge/src/highway/ptt-upload.ts index b3cf868b..927e6d00 100644 --- a/packages/core/src/bridge/highway/ptt-upload.ts +++ b/packages/bridge/src/highway/ptt-upload.ts @@ -1,30 +1,22 @@ -// Voice (PTT) upload: stage the audio bytes (convert to NT silk if -// necessary), run NTV2 upload + (optional) Highway PUT, return the -// encoded MsgInfo for the outgoing commonElem. -// -// Shared OIDB envelope + response handling + Highway PUT live in -// pipeline.ts; this file owns the silk transcoding, the temp-file -// cleanup hooks, and the PTT-specific OIDB fields. - +import crypto from 'crypto'; import fs from 'fs'; import path from 'path'; -import crypto from 'crypto'; -import type { Bridge } from '../bridge'; +import { createLogger } from '@snowluma/common/logger'; +import type { BridgeContext } from '../bridge-context'; import type { MessageElement } from '../events'; -import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils'; import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon'; -import { createLogger } from '../../utils/logger'; import { finalizeMediaMsgInfo, hexToBytes, runNtv2Upload, type MediaSubFileUpload, } from './pipeline'; +import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils'; const moduleLog = createLogger('Highway.Ptt'); -function loggerFor(bridge: Bridge) { +function loggerFor(bridge: BridgeContext) { const raw = bridge.identity?.uin; const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog; @@ -142,7 +134,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise= 24 && - bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) { + bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) { width = readBE32(bytes, 16); height = readBE32(bytes, 20); return { format: 1001, width, height }; @@ -201,8 +198,8 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat { // GIF if (bytes.length >= 10 && - bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 && - (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) { + bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 && + (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) { width = readLE16(bytes, 6); height = readLE16(bytes, 8); return { format: 2000, width, height }; @@ -217,8 +214,8 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat { // WebP if (bytes.length >= 30 && - bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && - bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) { + bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && + bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) { if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) { width = readLE16(bytes, 26); height = readLE16(bytes, 28); @@ -251,7 +248,7 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat { // (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT // and friends, then misread Huffman table bytes as image dimensions. const isSof = marker >= 0xC0 && marker <= 0xCF - && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC; + && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC; if (isSof && segLen >= 7 && offset + 9 <= bytes.length) { height = readBE16(bytes, offset + 5); width = readBE16(bytes, offset + 7); diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/bridge/src/highway/video-upload.ts similarity index 96% rename from packages/core/src/bridge/highway/video-upload.ts rename to packages/bridge/src/highway/video-upload.ts index bc7568a6..2b003515 100644 --- a/packages/core/src/bridge/highway/video-upload.ts +++ b/packages/bridge/src/highway/video-upload.ts @@ -1,37 +1,27 @@ -// Video upload: stage the source video and a thumbnail (extracted via -// ffmpeg if not supplied), run NTV2 upload + (optional) Highway PUTs for -// both files, return the encoded MsgInfo for the outgoing commonElem. -// -// Shared OIDB envelope + response handling + Highway PUT loop live in -// pipeline.ts; this file owns the ffmpeg thumb extraction, the 1 MB -// streaming sha1 used by main-video Highway uploads, and the -// video-specific OIDB fields (uploadInfo has TWO entries — main + thumb). - +import crypto from 'crypto'; import fs from 'fs'; import os from 'os'; import path from 'path'; -import crypto from 'crypto'; - -import type { Bridge } from '../bridge'; +import { createLogger } from '@snowluma/common/logger'; +import type { BridgeContext } from '../bridge-context'; import type { MessageElement } from '../events'; -import { - computeHashes, - detectImageFormat, - loadBinarySource, - resolveLocalFilePath, -} from './utils'; import { getFFmpegAddon } from './ffmpeg-addon'; -import { createLogger } from '../../utils/logger'; import { finalizeMediaMsgInfo, hexToBytes, runNtv2Upload, type MediaSubFileUpload, } from './pipeline'; +import { + computeHashes, + detectImageFormat, + loadBinarySource, + resolveLocalFilePath, +} from './utils'; const moduleLog = createLogger('Highway.Video'); -function loggerFor(bridge: Bridge) { +function loggerFor(bridge: BridgeContext) { const raw = bridge.identity?.uin; const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog; @@ -431,7 +421,7 @@ async function loadVideo(element: MessageElement): Promise { * (with per-1MB-block sha1) and a thumb (read off `upload.subFileInfos[0]`). */ export async function uploadVideoMsgInfo( - bridge: Bridge, + bridge: BridgeContext, isGroup: boolean, targetIdOrUid: string | number, element: MessageElement, diff --git a/packages/core/src/bridge/identity-service.ts b/packages/bridge/src/identity-service.ts similarity index 92% rename from packages/core/src/bridge/identity-service.ts rename to packages/bridge/src/identity-service.ts index d5e41d3e..cf68358f 100644 --- a/packages/core/src/bridge/identity-service.ts +++ b/packages/bridge/src/identity-service.ts @@ -1,12 +1,12 @@ import fs from 'fs'; import path from 'path'; -import { DatabaseSync } from 'node:sqlite'; +import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, GroupRequestInfo, } from './qq-info'; -import { createLogger, type Logger } from '../utils/logger'; +import { createLogger, type Logger } from '@snowluma/common/logger'; const moduleLogger = createLogger('Identity'); @@ -109,7 +109,14 @@ export class IdentityService { private readonly uidByUin = new Map(); // ─── Persistence + fetcher ─── - private readonly db: DatabaseSync | null; + private readonly db: DatabaseType | null; + // Prepared-statement cache. Every `.prepare(sql)` call in this + // service re-parses the SQL — that's the SQLite anti-pattern + // RoadMap #5 is fixing. We memoize by the SQL string itself so the + // call sites stay readable (no need to enumerate 20+ named fields + // upfront); the Map lookup is O(1) hash + string-eq, which is + // negligible next to the SQL parse it replaces. + private readonly stmtCache_ = new Map(); private inTransaction = false; private fetcher: IdentityFetcher | null = null; private readonly log: Logger; @@ -127,13 +134,23 @@ export class IdentityService { } fs.mkdirSync(path.dirname(dbPath), { recursive: true }); - this.db = new DatabaseSync(dbPath); - this.db.exec('PRAGMA journal_mode = WAL'); - this.db.exec('PRAGMA synchronous = NORMAL'); + this.db = new Database(dbPath); + this.db.pragma('journal_mode = WAL'); + this.db.pragma('synchronous = NORMAL'); this.initSchema(); this.loadSnapshot(); } + /** Cached `prepare(sql)`. First call per unique SQL parses; later + * calls reuse the same `Statement` object. See `stmtCache_`. */ + private pstmt(sql: string): Statement { + let cached = this.stmtCache_.get(sql); + if (cached !== undefined) return cached; + cached = this.db!.prepare(sql); + this.stmtCache_.set(sql, cached); + return cached; + } + static openForUin(uin: string, dataRoot = 'data'): IdentityService { return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db')); } @@ -238,7 +255,7 @@ export class IdentityService { if (!this.db) return null; if (groupId !== undefined) { - const row = this.db.prepare( + const row = this.pstmt( `SELECT uin FROM group_members WHERE group_id = ? AND uid = ? AND uin IS NOT NULL ORDER BY active DESC, updated_at DESC @@ -248,7 +265,7 @@ export class IdentityService { if (uin !== null) return uin; } - const row = this.db.prepare( + const row = this.pstmt( 'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1', ).get(normalized) as { uin: number | null } | undefined; return normalizeUin(row?.uin); @@ -267,7 +284,7 @@ export class IdentityService { if (!this.db) return null; if (groupId !== undefined) { - const row = this.db.prepare( + const row = this.pstmt( `SELECT uid FROM group_members WHERE group_id = ? AND uin = ? AND uid IS NOT NULL ORDER BY active DESC, updated_at DESC @@ -277,7 +294,7 @@ export class IdentityService { if (uid) return uid; } - const row = this.db.prepare( + const row = this.pstmt( 'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1', ).get(normalized) as { uid: string | null } | undefined; return normalizeUid(row?.uid) || null; @@ -289,7 +306,7 @@ export class IdentityService { this.friends_ = friends; for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin); this.runWrite('friends', () => this.transaction(() => { - this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1') + this.pstmt('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1') .run(nowSeconds()); for (const friend of friends) { this.upsertUser({ @@ -307,7 +324,7 @@ export class IdentityService { rememberGroups(groups: QQGroupInfo[]): void { this.setGroupsInMemory(groups); this.runWrite('groups', () => this.transaction(() => { - this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1') + this.pstmt('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1') .run(nowSeconds()); for (const group of groups) { this.upsertGroup({ @@ -327,7 +344,7 @@ export class IdentityService { for (const member of members) this.rememberUidUin(member.uid, member.uin); this.runWrite('group members', () => this.transaction(() => { this.upsertGroup({ groupId, memberCount: members.length }); - this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?') + this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?') .run(nowSeconds(), groupId); for (const member of members) { this.upsertGroupMember({ @@ -432,7 +449,7 @@ export class IdentityService { const updatedAt = nowSeconds(); this.transaction(() => { for (const row of rows) { - this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?') + this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?') .run(updatedAt, row.id); } }); @@ -541,7 +558,7 @@ export class IdentityService { } private loadSnapshot(): void { - const friendRows = this.db!.prepare( + const friendRows = this.pstmt( `SELECT uid, uin, nickname, remark FROM users WHERE is_friend = 1 AND uin IS NOT NULL`, @@ -554,7 +571,7 @@ export class IdentityService { })); for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin); - const groups = this.db!.prepare( + const groups = this.pstmt( `SELECT group_id, group_name, remark, member_count, member_max FROM groups WHERE active = 1`, @@ -579,7 +596,7 @@ export class IdentityService { private hydrateActiveMembersForGroups(groupIds: number[]): void { if (!this.db || groupIds.length === 0) return; - const select = this.db.prepare( + const select = this.pstmt( `SELECT group_id, uid, uin, nickname, card, role, level, title, join_time, last_sent_time, shut_up_time FROM group_members @@ -626,9 +643,9 @@ export class IdentityService { if (primary) { for (const duplicate of rows.slice(1)) { - this.db.prepare('DELETE FROM users WHERE id = ?').run(duplicate.id); + this.pstmt('DELETE FROM users WHERE id = ?').run(duplicate.id); } - this.db.prepare( + this.pstmt( `UPDATE users SET uid = ?, uin = ?, nickname = ?, remark = ?, is_friend = ?, source = ?, updated_at = ? WHERE id = ?`, @@ -645,7 +662,7 @@ export class IdentityService { return; } - this.db.prepare( + this.pstmt( `INSERT INTO users (uid, uin, nickname, remark, is_friend, source, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, ).run( @@ -662,7 +679,7 @@ export class IdentityService { private upsertGroup(input: GroupInput): void { if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return; - const existing = this.db.prepare( + const existing = this.pstmt( 'SELECT group_name, remark, member_count, member_max FROM groups WHERE group_id = ?', ).get(input.groupId) as { group_name: string; @@ -671,7 +688,7 @@ export class IdentityService { member_max: number; } | undefined; - this.db.prepare( + this.pstmt( `INSERT INTO groups (group_id, group_name, remark, member_count, member_max, active, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?) ON CONFLICT(group_id) DO UPDATE SET @@ -725,9 +742,9 @@ export class IdentityService { if (primary) { for (const duplicate of rows.slice(1)) { - this.db.prepare('DELETE FROM group_members WHERE id = ?').run(duplicate.id); + this.pstmt('DELETE FROM group_members WHERE id = ?').run(duplicate.id); } - this.db.prepare( + this.pstmt( `UPDATE group_members SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?, join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ? @@ -750,7 +767,7 @@ export class IdentityService { return; } - this.db.prepare( + this.pstmt( `INSERT INTO group_members (group_id, uid, uin, nickname, card, role, level, title, join_time, last_sent_time, shut_up_time, active, updated_at) @@ -775,17 +792,17 @@ export class IdentityService { private findUserRows(uid: string, uin: number | null): UserRow[] { if (!this.db) return []; if (uid && uin !== null) { - return this.db.prepare( + return this.pstmt( 'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? OR uin = ? ORDER BY id', ).all(uid, uin) as unknown as UserRow[]; } if (uid) { - return this.db.prepare( + return this.pstmt( 'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? ORDER BY id', ).all(uid) as unknown as UserRow[]; } if (uin !== null) { - return this.db.prepare( + return this.pstmt( 'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uin = ? ORDER BY id', ).all(uin) as unknown as UserRow[]; } @@ -795,7 +812,7 @@ export class IdentityService { private findMemberRows(groupId: number, uid: string, uin: number | null): MemberRow[] { if (!this.db) return []; if (uid && uin !== null) { - return this.db.prepare( + return this.pstmt( `SELECT id, group_id, uid, uin, nickname, card, role, level, title, join_time, last_sent_time, shut_up_time, active FROM group_members @@ -804,7 +821,7 @@ export class IdentityService { ).all(groupId, uid, uin) as unknown as MemberRow[]; } if (uid) { - return this.db.prepare( + return this.pstmt( `SELECT id, group_id, uid, uin, nickname, card, role, level, title, join_time, last_sent_time, shut_up_time, active FROM group_members @@ -813,7 +830,7 @@ export class IdentityService { ).all(groupId, uid) as unknown as MemberRow[]; } if (uin !== null) { - return this.db.prepare( + return this.pstmt( `SELECT id, group_id, uid, uin, nickname, card, role, level, title, join_time, last_sent_time, shut_up_time, active FROM group_members diff --git a/packages/core/src/bridge/msg-push/context.ts b/packages/bridge/src/msg-push/context.ts similarity index 66% rename from packages/core/src/bridge/msg-push/context.ts rename to packages/bridge/src/msg-push/context.ts index 556be152..463fc087 100644 --- a/packages/core/src/bridge/msg-push/context.ts +++ b/packages/bridge/src/msg-push/context.ts @@ -1,18 +1,11 @@ -// MsgPushContext — the decoded envelope fields every decoder may need. -// One unified shape: notice decoders pick from `content`, message decoders -// pick from `body` / `responseHead`. Decoders ignore fields they don't need. - -import { protoDecode } from '../../protobuf/decode'; -import type { ProtoDecoded } from '../../protobuf/decode'; -import { - PushMsgSchema, MessageBodySchema, ResponseHeadSchema, ContentHeadSchema, -} from '../proto/message'; -import type { PacketInfo } from '../../protocol/types'; +import { protobuf_decode } from '@snowluma/proton'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; import type { IdentityService } from '../identity-service'; +import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '@snowluma/proto-defs/message'; -export type PushMsgBody = ProtoDecoded; -export type PushMsgResponseHead = ProtoDecoded; -export type PushMsgContentHead = ProtoDecoded; +export type PushMsgBody = MessageBody; +export type PushMsgResponseHead = ResponseHead; +export type PushMsgContentHead = ContentHead; export interface MsgPushHead { readonly msgType: number; @@ -36,7 +29,12 @@ export interface MsgPushContext { export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null { if (pkt.body.length === 0) return null; - const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema); + // `pkt.body` is already a `Uint8Array` (see `PacketInfo` in + // @snowluma/common/protocol-types). The legacy `Buffer.from(uint8)` + // wrap was a no-op copy — Buffer is a Uint8Array subclass and + // proton's decoder accepts the parent type directly. Dropping the + // wrap saves one allocation per incoming push packet. + const push = protobuf_decode(pkt.body); if (!push?.message) return null; const msg = push.message; diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/bridge/src/msg-push/decoders/event-0x210.ts similarity index 83% rename from packages/core/src/bridge/msg-push/decoders/event-0x210.ts rename to packages/bridge/src/msg-push/decoders/event-0x210.ts index 9c3ebd1e..31d94e56 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts +++ b/packages/bridge/src/msg-push/decoders/event-0x210.ts @@ -1,36 +1,27 @@ -// Handles Event0x210 wrapper (528). Internal switch on subType dispatches -// to FriendRequest (35) / FriendRecall (138, 139) / NewFriend -// (179, 226) / FriendPoke (290). - import { protobuf_decode } from '@snowluma/proton'; -// Proto types imported unaliased — proton's import-resolver registers -// `importedTypeSources` keyed on the *imported* name. If we also did -// `import type { FriendRecall } from '../../events'` it would shadow -// the proto-side mapping (last-write-wins), point the resolver at the -// event-side file which has no `pb<>` schema, and the codec would -// never get generated — `protobuf_decode(...)` then -// falls through to the runtime fallback and throws (silently caught -// by `MsgPushRegistry.decode`). The event-side colliding names are -// re-derived from `QQEventVariant` below via `Extract` instead. +import { createLogger } from '@snowluma/common/logger'; +import type { + FriendAddEvent, + FriendPokeEvent, + FriendRequestEvent, + QQEventVariant, +} from '../../events'; import type { - FriendRequest, FriendRecall, + FriendRequest, GeneralGrayTipInfo, NewFriend, -} from '../../proto/proton/notify'; -import type { - FriendRequestEvent, FriendPokeEvent, - FriendAddEvent, QQEventVariant, -} from '../../events'; - -type FriendRecallEvent = Extract; -import type { MsgPushDecoder } from '../registry'; +} from '@snowluma/proto-defs/notify'; import type { MsgPushContext } from '../context'; import { Event0x210SubType } from '../enums'; import { - resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue, + buildTemplateMap, findTemplateValue, + parseU64OrZero, + resolveUidToUin, } from '../helpers'; -import { createLogger } from '../../../utils/logger'; +import type { MsgPushDecoder } from '../registry'; + +type FriendRecallEvent = Extract; const unknownLog = createLogger('MsgPush.Unknown'); diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts b/packages/bridge/src/msg-push/decoders/event-0x2dc.ts similarity index 93% rename from packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts rename to packages/bridge/src/msg-push/decoders/event-0x2dc.ts index e16205ae..ca0b4dbe 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts +++ b/packages/bridge/src/msg-push/decoders/event-0x2dc.ts @@ -1,24 +1,27 @@ -// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches -// to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) / -// GroupGreyTip (20) / GroupEssence (21). - import { protobuf_decode } from '@snowluma/proton'; +import { createLogger } from '@snowluma/common/logger'; import type { - GroupMute, NotifyMessageBody, GroupReactNotify, -} from '../../proto/proton/notify'; -import type { - GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent, + GroupEssenceEvent, GroupMsgEmojiLikeEvent, + GroupMuteEvent, + GroupPokeEvent, + GroupRecallEvent, QQEventVariant, } from '../../events'; -import type { MsgPushDecoder } from '../registry'; +import type { + GroupMute, + GroupReactNotify, + NotifyMessageBody, +} from '@snowluma/proto-defs/notify'; import type { MsgPushContext } from '../context'; import { Event0x2DCSubType } from '../enums'; import { - resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue, + buildTemplateMap, findTemplateValue, + parseU64OrZero, + resolveUidToUin, unwrapGroupNotifyPayload, } from '../helpers'; -import { createLogger } from '../../../utils/logger'; +import type { MsgPushDecoder } from '../registry'; const unknownLog = createLogger('MsgPush.Unknown'); diff --git a/packages/core/src/bridge/msg-push/decoders/friend-message.ts b/packages/bridge/src/msg-push/decoders/friend-message.ts similarity index 70% rename from packages/core/src/bridge/msg-push/decoders/friend-message.ts rename to packages/bridge/src/msg-push/decoders/friend-message.ts index c07a28bc..d0bedd21 100644 --- a/packages/core/src/bridge/msg-push/decoders/friend-message.ts +++ b/packages/bridge/src/msg-push/decoders/friend-message.ts @@ -1,9 +1,3 @@ -// Handles the four PkgTypes that produce a FriendMessage event: -// PrivateMessage (166), ForwardFakePrivateMessage (9), -// PrivateRecordMessage (208), PrivateFileMessage (529). The PkgType -// difference only affects which proto-level elements show up in the -// body — decodeRichBody handles all of them uniformly. - import type { FriendMessage } from '../../events'; import type { MsgPushDecoder } from '../registry'; import { decodeRichBody } from '../rich-body-decoder'; diff --git a/packages/core/src/bridge/msg-push/decoders/group-admin.ts b/packages/bridge/src/msg-push/decoders/group-admin.ts similarity index 82% rename from packages/core/src/bridge/msg-push/decoders/group-admin.ts rename to packages/bridge/src/msg-push/decoders/group-admin.ts index d5c75087..b82a80cc 100644 --- a/packages/core/src/bridge/msg-push/decoders/group-admin.ts +++ b/packages/bridge/src/msg-push/decoders/group-admin.ts @@ -1,11 +1,8 @@ -// Handles GroupAdminChangedNotice (44). extraEnable / extraDisable -// distinguishes set vs. unset. - import { protobuf_decode } from '@snowluma/proton'; -import type { GroupAdmin } from '../../proto/proton/notify'; import type { GroupAdminEvent } from '../../events'; -import type { MsgPushDecoder } from '../registry'; +import type { GroupAdmin } from '@snowluma/proto-defs/notify'; import { resolveUidToUin } from '../helpers'; +import type { MsgPushDecoder } from '../registry'; export const decodeGroupAdmin: MsgPushDecoder = (ctx) => { const admin = protobuf_decode(ctx.content); diff --git a/packages/core/src/bridge/msg-push/decoders/group-join-request.ts b/packages/bridge/src/msg-push/decoders/group-join-request.ts similarity index 87% rename from packages/core/src/bridge/msg-push/decoders/group-join-request.ts rename to packages/bridge/src/msg-push/decoders/group-join-request.ts index 50c589bc..67d87aea 100644 --- a/packages/core/src/bridge/msg-push/decoders/group-join-request.ts +++ b/packages/bridge/src/msg-push/decoders/group-join-request.ts @@ -1,14 +1,11 @@ -// Handles GroupRequestJoinNotice (84) + GroupRequestInvitationNotice (525) -// + GroupInviteNotice (87). All three produce GroupInviteEvent with -// different subType ('add' / 'invite') and flag prefixes. - import { protobuf_decode } from '@snowluma/proton'; -import type { - GroupJoin, GroupInvitation, GroupInvite, -} from '../../proto/proton/notify'; import type { GroupInviteEvent } from '../../events'; -import type { MsgPushDecoder } from '../registry'; +import type { + GroupInvitation, GroupInvite, + GroupJoin, +} from '@snowluma/proto-defs/notify'; import { resolveUidToUin } from '../helpers'; +import type { MsgPushDecoder } from '../registry'; export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => { const join = protobuf_decode(ctx.content); diff --git a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts b/packages/bridge/src/msg-push/decoders/group-member-change.ts similarity index 74% rename from packages/core/src/bridge/msg-push/decoders/group-member-change.ts rename to packages/bridge/src/msg-push/decoders/group-member-change.ts index 4d371620..e9aa3736 100644 --- a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts +++ b/packages/bridge/src/msg-push/decoders/group-member-change.ts @@ -1,24 +1,8 @@ -// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34) + -// GroupSelfJoinedNotice (85, bot-self admittance). -// -// 33/34 share GroupChangeSchema; the decreaseType field distinguishes -// kick vs voluntary leave (dt != 0 && dt != 130 means kicked). -// -// 85 carries a different wire shape (`SelfJoinInGroup`) — without it -// the bot has no signal that its own `set_group_add_request` was -// approved (33 fires only for *other* members joining). We surface -// 85 as a regular GroupMemberJoin with `userUin = selfUin` so the -// existing OneBot converter naturally produces -// `notice.group_increase` with `sub_type: 'approve' | 'invite'` -// (the converter compares operator == user to pick the sub_type; -// for self-join the operator is the admin/inviter, so 'invite' is -// emitted — matching go-cqhttp / NapCat semantics). - import { protobuf_decode } from '@snowluma/proton'; -import type { GroupChange, SelfJoinInGroup } from '../../proto/proton/notify'; import type { GroupMemberJoin, GroupMemberLeave } from '../../events'; -import type { MsgPushDecoder } from '../registry'; +import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify'; import { decodeOperatorUid, resolveUidToUin } from '../helpers'; +import type { MsgPushDecoder } from '../registry'; export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => { const change = protobuf_decode(ctx.content); diff --git a/packages/core/src/bridge/msg-push/decoders/group-message.ts b/packages/bridge/src/msg-push/decoders/group-message.ts similarity index 89% rename from packages/core/src/bridge/msg-push/decoders/group-message.ts rename to packages/bridge/src/msg-push/decoders/group-message.ts index 6def3b67..3ab677a5 100644 --- a/packages/core/src/bridge/msg-push/decoders/group-message.ts +++ b/packages/bridge/src/msg-push/decoders/group-message.ts @@ -1,6 +1,3 @@ -// Handles GroupMessage (82). Resolves senderCard / senderRole from the -// group member roster when present. - import type { GroupMessage } from '../../events'; import type { MsgPushDecoder } from '../registry'; import { decodeRichBody } from '../rich-body-decoder'; diff --git a/packages/core/src/bridge/msg-push/decoders/temp-message.ts b/packages/bridge/src/msg-push/decoders/temp-message.ts similarity index 87% rename from packages/core/src/bridge/msg-push/decoders/temp-message.ts rename to packages/bridge/src/msg-push/decoders/temp-message.ts index f2c89f72..a61046ed 100644 --- a/packages/core/src/bridge/msg-push/decoders/temp-message.ts +++ b/packages/bridge/src/msg-push/decoders/temp-message.ts @@ -1,6 +1,3 @@ -// Handles TempMessage (141). Pulls senderNick from group hint first -// then falls back to friend roster. - import type { TempMessage } from '../../events'; import type { MsgPushDecoder } from '../registry'; import { decodeRichBody } from '../rich-body-decoder'; diff --git a/packages/core/src/bridge/msg-push/enums.ts b/packages/bridge/src/msg-push/enums.ts similarity index 95% rename from packages/core/src/bridge/msg-push/enums.ts rename to packages/bridge/src/msg-push/enums.ts index 30f28279..74422733 100644 --- a/packages/core/src/bridge/msg-push/enums.ts +++ b/packages/bridge/src/msg-push/enums.ts @@ -1,7 +1,3 @@ -// MsgPush PkgType taxonomy. The top-level msgType field in PushMsg.contentHead -// names a QQ-protocol-defined packet shape; Event0x210 / Event0x2DC are wrapper -// PkgTypes whose payload is further dispatched by subType. - export enum PkgType { ForwardFakePrivateMessage = 9, PrivateMessage = 166, diff --git a/packages/core/src/bridge/msg-push/helpers.ts b/packages/bridge/src/msg-push/helpers.ts similarity index 90% rename from packages/core/src/bridge/msg-push/helpers.ts rename to packages/bridge/src/msg-push/helpers.ts index dc8cd1ec..200d1abe 100644 --- a/packages/core/src/bridge/msg-push/helpers.ts +++ b/packages/bridge/src/msg-push/helpers.ts @@ -1,10 +1,7 @@ -// MsgPush decode helpers — pure functions shared across PkgType decoders -// and the rich-body decoder. No state, no I/O. - -import { inflateSync } from 'zlib'; import { protobuf_decode } from '@snowluma/proton'; -import type { OperatorInfo } from '../proto/proton/notify'; +import { inflateSync } from 'zlib'; import type { IdentityService } from '../identity-service'; +import type { OperatorInfo } from '@snowluma/proto-defs/notify'; export function makeImageUrl(origUrl: string): string { if (!origUrl) return ''; @@ -57,7 +54,7 @@ export function decodeOperatorUid(bytes: Uint8Array): string { return Buffer.from(bytes).toString('utf8'); } -export function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map { +export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map { const map = new Map(); for (const p of params) { if (p.name !== undefined) map.set(p.name, p.value ?? ''); diff --git a/packages/core/src/bridge/msg-push/index.ts b/packages/bridge/src/msg-push/index.ts similarity index 86% rename from packages/core/src/bridge/msg-push/index.ts rename to packages/bridge/src/msg-push/index.ts index 71766e90..d69f00cd 100644 --- a/packages/core/src/bridge/msg-push/index.ts +++ b/packages/bridge/src/msg-push/index.ts @@ -1,25 +1,22 @@ -// MsgPush entry point — assembles the PkgType registry and exposes -// `parseMsgPush(pkt, identity)` as the single CmdParser registered against -// `MSG_PUSH_CMD` on the IncomingPacketPipeline. - -import type { PacketInfo } from '../../protocol/types'; -import type { IdentityService } from '../identity-service'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; import type { QQEventVariant } from '../events'; +import type { IdentityService } from '../identity-service'; import { buildContext } from './context'; -import { MsgPushRegistry } from './registry'; -import { PkgType } from './enums'; +import { decodeEvent0x210 } from './decoders/event-0x210'; +import { decodeEvent0x2DC } from './decoders/event-0x2dc'; +import { decodeFriendMessage } from './decoders/friend-message'; +import { decodeGroupAdmin } from './decoders/group-admin'; +import { + decodeGroupInvitation, decodeGroupInvite, + decodeGroupJoinRequest, +} from './decoders/group-join-request'; import { decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined, } from './decoders/group-member-change'; -import { decodeGroupAdmin } from './decoders/group-admin'; -import { - decodeGroupJoinRequest, decodeGroupInvitation, decodeGroupInvite, -} from './decoders/group-join-request'; -import { decodeEvent0x210 } from './decoders/event-0x210'; -import { decodeEvent0x2DC } from './decoders/event-0x2dc'; import { decodeGroupMessage } from './decoders/group-message'; import { decodeTempMessage } from './decoders/temp-message'; -import { decodeFriendMessage } from './decoders/friend-message'; +import { PkgType } from './enums'; +import { MsgPushRegistry } from './registry'; export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush'; diff --git a/packages/core/src/bridge/msg-push/registry.ts b/packages/bridge/src/msg-push/registry.ts similarity index 80% rename from packages/core/src/bridge/msg-push/registry.ts rename to packages/bridge/src/msg-push/registry.ts index 4a3e9a18..cf00479d 100644 --- a/packages/core/src/bridge/msg-push/registry.ts +++ b/packages/bridge/src/msg-push/registry.ts @@ -1,9 +1,4 @@ -// MsgPushRegistry — per-PkgType dispatch table. Each PkgType maps to a single -// decoder; double-registration is a programming error (throws at register time). -// Decoder errors are caught and logged with the PkgType so a single bad decoder -// can never silently take down sibling decoders sharing the cmd. - -import { createLogger } from '../../utils/logger'; +import { createLogger } from '@snowluma/common/logger'; import type { QQEventVariant } from '../events'; import type { MsgPushContext } from './context'; import type { PkgType } from './enums'; diff --git a/packages/core/src/bridge/msg-push/rich-body-decoder.ts b/packages/bridge/src/msg-push/rich-body-decoder.ts similarity index 90% rename from packages/core/src/bridge/msg-push/rich-body-decoder.ts rename to packages/bridge/src/msg-push/rich-body-decoder.ts index c980d23b..2f1840e1 100644 --- a/packages/core/src/bridge/msg-push/rich-body-decoder.ts +++ b/packages/bridge/src/msg-push/rich-body-decoder.ts @@ -1,26 +1,21 @@ -// Rich body decoder — turns the proto MessageBody (richText.elems + -// richText.ptt/notOnlineFile + msgContent) of a MsgPush message into -// the bridge-internal MessageElement[] sequence. Pure, no identity -// lookups, no I/O. The single small interface `decodeRichBody` hides -// ~400 lines of per-element-type decoding behind it. - -import { protoDecode } from '../../protobuf/decode'; -import type { ProtoDecoded } from '../../protobuf/decode'; -import { ElemSchema } from '../proto/element'; -import { - MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema, - MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema, -} from '../proto/element'; -import { - MessageBodySchema, RichTextSchema, FileExtraSchema, -} from '../proto/message'; +import { protobuf_decode } from '@snowluma/proton'; +import { toHexUpper } from '@snowluma/common/hex'; import type { MessageElement } from '../events'; -import { toHexUpper } from '../../utils/hex'; +import type { + Elem, + GroupFileExtra, + MentionExtra, + MsgInfo, + NotOnlineImage, + QFaceExtra, + QSmallFaceExtra, +} from '@snowluma/proto-defs/element'; +import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message'; import { decompressData, makeImageUrl } from './helpers'; -type ElemDecoded = ProtoDecoded; -type RichTextDecoded = ProtoDecoded; -export type PushMsgBody = ProtoDecoded; +type ElemDecoded = Elem; +type RichTextDecoded = RichText; +export type PushMsgBody = MessageBody; export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] { const elements: MessageElement[] = []; @@ -50,9 +45,9 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // Text (with possible @ detection) if (elem.text) { const t = elem.text; - let mention: ProtoDecoded | null = null; + let mention: MentionExtra | null = null; if (t.pbReserve && t.pbReserve.length > 0) { - mention = protoDecode(t.pbReserve, MentionExtraSchema); + mention = protobuf_decode(t.pbReserve); } const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11; const hasMention = mention && (mention.type === 1 || mention.type === 2); @@ -172,7 +167,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { const val = te.elemValue; const len = (val[1] << 8) | val[2]; if (val.length >= 3 + len) { - const extra = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema); + const extra = protobuf_decode(val.subarray(3, 3 + len)); if (extra?.inner?.info) { const info = extra.inner.info; result.push({ @@ -243,7 +238,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { if ((b & 0x80) === 0) break; } if (pos + length <= pb.length) { - const img = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema); + const img = protobuf_decode(pb.subarray(pos, pos + length)); if (img) { const me: MessageElement = { type: 'image', fileId: img.filePath ?? '', @@ -260,7 +255,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { skipNext = true; } else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) { // NTQQ new protocol image/record/video - const info = protoDecode(ce.pbElem, MsgInfoSchema); + const info = protobuf_decode(ce.pbElem); if (info?.msgInfoBody && info.msgInfoBody.length > 0) { const body = info.msgInfoBody[0]; if (body.index?.info) { @@ -368,11 +363,11 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { } } else if (svcType === 33 && ce.pbElem) { // Small face - const extra = protoDecode(ce.pbElem, QSmallFaceExtraSchema); + const extra = protobuf_decode(ce.pbElem); if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 }); } else if (svcType === 37 && ce.pbElem) { // Big face - const extra = protoDecode(ce.pbElem, QFaceExtraSchema); + const extra = protobuf_decode(ce.pbElem); if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid }); skipNext = true; } @@ -443,7 +438,7 @@ function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): // "incomplete metadata". After consolidating FileExtra to wrap // `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`), // this reads the right tags. - const extra = protoDecode(msgContent, FileExtraSchema); + const extra = protobuf_decode(msgContent); if (!extra?.file) return; const f = extra.file; if (!f.fileUuid) return; diff --git a/packages/core/src/bridge/packet-pipeline.ts b/packages/bridge/src/packet-pipeline.ts similarity index 89% rename from packages/core/src/bridge/packet-pipeline.ts rename to packages/bridge/src/packet-pipeline.ts index 1697a15e..89861ee3 100644 --- a/packages/core/src/bridge/packet-pipeline.ts +++ b/packages/bridge/src/packet-pipeline.ts @@ -1,27 +1,9 @@ -// Incoming packet pipeline — the chain that turns a single PacketInfo -// arriving from the hook layer into a stream of QQEventVariant -// emissions on the typed event bus. Replaces the inline orchestration -// that previously lived on Bridge.onPacket / triggerMemberCacheRefresh / -// rememberEventIdentity / dispatchAfterIdentityRefresh / etc. -// -// Stage chain per parser output: -// parse → enrich identity (sync, or async refresh) -// → side-effects (remember UID/UIN + schedule roster refresh) -// → log -// → emit on bus -// -// The pipeline owns its cmd handler map and its per-group coalesce table -// for background member-list refreshes. It does NOT own protocol calls -// — `refreshMemberCache` is injected by Bridge because it ultimately -// dispatches OIDB packets through Bridge.fetchGroupList / -// Bridge.fetchGroupMemberList. - -import type { PacketInfo } from '../protocol/types'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import { formatEvent } from './format'; +import { createLogger, type Logger } from '@snowluma/common/logger'; +import type { BridgeEventBus } from './event-bus'; import type { QQEventVariant } from './events'; import type { IdentityService } from './identity-service'; -import type { BridgeEventBus } from './event-bus'; -import { createLogger, type Logger } from '../utils/logger'; -import { formatEvent } from '../utils/event-format'; const moduleLog = createLogger('Bridge'); const moduleEventLog = createLogger('Event'); diff --git a/packages/core/src/bridge/qq-info.ts b/packages/bridge/src/qq-info.ts similarity index 79% rename from packages/core/src/bridge/qq-info.ts rename to packages/bridge/src/qq-info.ts index 549788a3..e3302539 100644 --- a/packages/core/src/bridge/qq-info.ts +++ b/packages/bridge/src/qq-info.ts @@ -1,8 +1,3 @@ -// Domain object shapes shared by IdentityService and its callers. The -// concrete state (own UIN, friends list, group rosters, profile cache) -// lives inside IdentityService — these interfaces just describe the -// records that flow across remember*/refresh* and find* boundaries. - export interface UserProfileInfo { uin: number; uid: string; diff --git a/packages/core/src/bridge/web/group-album.ts b/packages/bridge/src/web/group-album.ts similarity index 96% rename from packages/core/src/bridge/web/group-album.ts rename to packages/bridge/src/web/group-album.ts index 321e9790..830ec25e 100644 --- a/packages/core/src/bridge/web/group-album.ts +++ b/packages/bridge/src/web/group-album.ts @@ -1,6 +1,6 @@ import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; import { createHash } from 'crypto'; -import { readFileSync, statSync, createReadStream, writeFileSync, unlinkSync } from 'fs'; +import { statSync, createReadStream, writeFileSync, unlinkSync } from 'fs'; import { basename, join } from 'path'; import { tmpdir } from 'os'; @@ -147,13 +147,13 @@ async function createAlbumUploadSession( * 修复后的上传图片分片方法 */ async function uploadAlbumSlice( - session: string, - filePath: string, - // 移除 offset 和 chunkSize 参数,改为在内部控制 - imgMd5: string, - skey: string, - pskey: string, - uin: string + session: string, + filePath: string, + // 移除 offset 和 chunkSize 参数,改为在内部控制 + imgMd5: string, + skey: string, + pskey: string, + uin: string ): Promise { const img_size = statSync(filePath).size; const slice_size = 16384; // 严格使用 16KB diff --git a/packages/bridge/src/web/group-essence.ts b/packages/bridge/src/web/group-essence.ts new file mode 100644 index 00000000..cf46eff7 --- /dev/null +++ b/packages/bridge/src/web/group-essence.ts @@ -0,0 +1,71 @@ +import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; +import { createLogger } from '@snowluma/common/logger'; + +const log = createLogger('Bridge.Web'); + +// 定义接口返回类型 +export interface GroupEssenceMsgRet { + retcode: number; + data: { + is_end: boolean; + msg_list: any[]; // 具体结构视需要补充 + [key: string]: any; + }; + [key: string]: any; +} + + +/** + * 分页获取群精华消息 + */ +export async function getGroupEssenceMsg( + cookieObject: Record, + groupCode: string, + pageStart: number = 0, + pageLimit: number = 50 +): Promise { + const bkn = getBknFromCookie(cookieObject); + + const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({ + bkn: bkn, + page_start: pageStart.toString(), + page_limit: pageLimit.toString(), + group_code: groupCode, + }).toString()}`; + + try { + const ret = await RequestUtil.HttpGetJson( + url, + 'GET', + '', + { Cookie: cookieToString(cookieObject) } + ); + return ret.retcode === 0 ? ret : undefined; + } catch (e) { + log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s', + groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e)); + return undefined; + } +} + +/** + * 获取所有群精华消息 (最多循环 20 页) + */ +export async function getGroupEssenceMsgAll( + cookieObject: Record, + groupCode: string +): Promise { + const ret: GroupEssenceMsgRet[] = []; + + for (let i = 0; i < 20; i++) { + const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50); + + if (!data) break; + + ret.push(data); + + if (data.data?.is_end) break; + } + + return ret; +} \ No newline at end of file diff --git a/packages/bridge/src/web/group-honor.ts b/packages/bridge/src/web/group-honor.ts new file mode 100644 index 00000000..133e4f9d --- /dev/null +++ b/packages/bridge/src/web/group-honor.ts @@ -0,0 +1,53 @@ +import { RequestUtil, cookieToString } from './request-util'; +import { createLogger } from '@snowluma/common/logger'; + +const log = createLogger('Bridge.Web'); + +export enum WebHonorType { + TALKATIVE = 'talkative', + PERFORMER = 'performer', + LEGEND = 'legend', + EMOTION = 'emotion', + ALL = 'all', +} + + +async function fetchHonorData(cookieObject: Record, groupCode: string, type: number) { + let resJson; + try { + const res = await RequestUtil.HttpGetText( + `https://qun.qq.com/interactive/honorlist?${new URLSearchParams({ + gc: groupCode, + type: type.toString(), + }).toString()}`, + 'GET', + '', + { Cookie: cookieToString(cookieObject) } + ); + const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res); + if (match?.[1]) { + resJson = JSON.parse(match[1].trim()); + } + return type === 1 ? resJson?.talkativeList : resJson?.actorList; + } catch (e) { + throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`); + } +} + +export async function getHonorListWebAPI(cookieObject: Record, groupCode: string, type: number) { + try { + const data = await fetchHonorData(cookieObject, groupCode, type); + if (!data) return []; + + return data.map((item: any) => ({ + user_id: item?.uin, + nickname: item?.name, + avatar: item?.avatar, + description: item?.desc, + })); + } catch (e) { + log.warn('getHonorListWebAPI failed (group=%s type=%d): %s', + groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e)); + return []; + } +} \ No newline at end of file diff --git a/packages/bridge/src/web/group-notice.ts b/packages/bridge/src/web/group-notice.ts new file mode 100644 index 00000000..2fc3b8fa --- /dev/null +++ b/packages/bridge/src/web/group-notice.ts @@ -0,0 +1,273 @@ +import { RequestUtil, cookieToString } from './request-util'; +import https from 'node:https'; +import { createLogger } from '@snowluma/common/logger'; + +const log = createLogger('Bridge.Web'); + +export interface SetNoticeRetSuccess { + ec?: number; + em?: string; + [key: string]: any; +} + +export interface UploadImageRetSuccess { + ec?: number; + id?: string; + [key: string]: any; +} + +export interface WebApiGroupNoticeFeed { + fid: string; + u: number; + pubt: number; + msg: { + text: string; + pics?: Array<{ id: string; w: number; h: number }>; + }; + settings: any; + read_num: number; + [key: string]: any; +} + +export interface WebApiGroupNoticeRet { + ec: number; + em?: string; + feeds?: Record; + [key: string]: any; +} + +export function calculateBkn(key: string): string { + let hash = 5381; + for (let i = 0; i < key.length; i++) { + const code = key.charCodeAt(i); + hash = hash + (hash << 5) + code; + } + return (hash & 0x7FFFFFFF).toString(); +} + +/** + * 发送群公告 Web API + */ +export async function setGroupNoticeWebAPI( + cookieObject: Record, + groupCode: string, + content: string, + pinned: number = 0, + type: number = 1, + isShowEditCard: number = 1, + tipWindowType: number = 1, + confirmRequired: number = 1, + picId: string = '', + imgWidth: number = 540, + imgHeight: number = 300 +): Promise { + try { + // 分别获取 skey 和 p_skey + const skey = cookieObject['skey'] || ''; + const pskey = cookieObject['p_skey'] || skey; + + const bodyBkn = calculateBkn(skey); + const urlBkn = calculateBkn(pskey); + // + // console.log(skey) + // console.log(pskey) + // + // console.log(urlBkn); + // console.log(bodyBkn) + + const settings = JSON.stringify({ + is_show_edit_card: isShowEditCard, + tip_window_type: tipWindowType, + confirm_required: confirmRequired, + }); + + const bodyParams: Record = { + qid: groupCode, + bkn: bodyBkn, + text: content, + pinned: pinned.toString(), + type: type.toString(), + settings, + }; + + if (picId !== '') { + bodyParams.pic = picId; + bodyParams.imgWidth = imgWidth.toString(); + bodyParams.imgHeight = imgHeight.toString(); + } + + // 注意这里:URL 必须使用 skey 算出来的 bkn + const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`; + const body = new URLSearchParams(bodyParams).toString(); + + const ret = await RequestUtil.HttpGetJson( + url, + 'POST', + body, + { + Cookie: cookieToString(cookieObject), + 'Content-Type': 'application/x-www-form-urlencoded' + }, + true, + false + ); + return ret; + } catch (e) { + log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); + return undefined; + } +} + +/** + * 获取群公告列表 Web API + */ +export async function getGroupNoticeWebAPI( + cookieObject: Record, + groupCode: string, + start: number = -1, // -1 表示第一页 + count: number = 20 // 抓包中是 10,你可以根据需要调整 +): Promise { + try { + const skey = cookieObject['skey'] || ''; + const pskey = cookieObject['p_skey'] || skey; + + const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn + const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn + + const bodyParams = new URLSearchParams({ + qid: groupCode, + bkn: bodyBkn, // Body 中传入 p_skey 计算结果 + ft: '23', + s: start.toString(), // 分页游标 + n: count.toString(), // 获取数量 + i: '1', + ni: '1' + }).toString(); + + const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`; + + const ret = await RequestUtil.HttpGetJson( + url, + 'POST', + bodyParams, + { + Cookie: cookieToString(cookieObject), + 'Content-Type': 'application/x-www-form-urlencoded', + 'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148' + }, + true, + false + ); + // console.log(JSON.stringify(ret, null, 2)); + return ret?.ec === 0 ? ret : undefined; + } catch (e) { + log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); + return undefined; + } +} +/** + * 上传群公告图片 Web API + */ +export async function uploadGroupNoticeImage( + cookieObject: Record, + imageBuffer: Buffer +): Promise<{ id: string; width: number; height: number } | undefined> { + try { + const bkn = calculateBkn(cookieObject['skey']); + const boundary = `-----------------------------${Date.now()}`; + + const parts: Buffer[] = []; + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`)); + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`)); + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`)); + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`)); + parts.push(imageBuffer); + parts.push(Buffer.from(`\r\n--${boundary}--\r\n`)); + + const body = Buffer.concat(parts); + + const options = { + hostname: 'web.qun.qq.com', + path: '/cgi-bin/announce/upload_img', + method: 'POST', + headers: { + 'Content-Type': `multipart/form-data; boundary=${boundary}`, + 'Content-Length': body.length, + 'Cookie': cookieToString(cookieObject), + }, + }; + + return new Promise((resolve) => { + const req = https.request(options, (res) => { + let data = ''; + res.on('data', (chunk) => { data += chunk; }); + res.on('end', () => { + try { + const result = JSON.parse(data) as UploadImageRetSuccess; + if (result.ec === 0 && result.id) { + const unescapedIdStr = result.id.replace(/"/g, '"'); + + const idObj = JSON.parse(unescapedIdStr); + resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) }); + } else { + resolve(undefined); + } + } catch { + resolve(undefined); + } + }); + }); + req.on('error', (err) => { + log.warn('uploadGroupNoticeImage transport error: %s', err.message); + resolve(undefined); + }); + req.write(body); + req.end(); + }); + } catch (e) { + log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); + return undefined; + } +} + +/** + * 删除群公告 Web API + */ +export async function deleteGroupNotice( + cookieObject: Record, + groupCode: string, + fid: string +): Promise { + try { + const skey = cookieObject['skey'] || ''; + const pskey = cookieObject['p_skey'] || skey; + + const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn + const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn + + const params = new URLSearchParams({ + bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn + fid: fid, + qid: groupCode, + }).toString(); + + // 注意这里:URL 拼接 urlBkn + const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`; + + const ret = await RequestUtil.HttpGetJson( + url, + 'POST', + params, + { + Cookie: cookieToString(cookieObject), + 'Content-Type': 'application/x-www-form-urlencoded' + }, + true, + false + ); + return ret?.ec === 0; + } catch (e) { + log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e)); + return false; + } +} \ No newline at end of file diff --git a/packages/bridge/src/web/request-util.ts b/packages/bridge/src/web/request-util.ts new file mode 100644 index 00000000..60f28d8f --- /dev/null +++ b/packages/bridge/src/web/request-util.ts @@ -0,0 +1,127 @@ +import https from 'node:https'; +import http from 'node:http'; + +export class RequestUtil { + static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> { + const client = url.startsWith('https') ? https : http; + return new Promise((resolve, reject) => { + const req = client.get(url, (res) => { + const cookies: { [key: string]: string; } = {}; + + res.on('data', () => { }); // 必须消耗流 + res.on('end', () => { + this.handleRedirect(res, url, cookies) + .then(resolve) + .catch(reject); + }); + + if (res.headers['set-cookie']) { + this.extractCookies(res.headers['set-cookie'], cookies); + } + }); + + req.on('error', (error: Error) => { + reject(error); + }); + }); + } + + private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> { + if (res.statusCode === 301 || res.statusCode === 302) { + if (res.headers.location) { + const redirectUrl = new URL(res.headers.location, url); + const redirectCookies = await this.HttpsGetCookies(redirectUrl.href); + return { ...cookies, ...redirectCookies }; + } + } + return cookies; + } + + private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) { + setCookieHeaders.forEach((cookie) => { + const parts = cookie.split(';')[0]?.split('='); + if (parts) { + const key = parts[0]; + const value = parts[1]; + if (key && value && key.length > 0 && value.length > 0) { + cookies[key] = value; + } + } + }); + } + + static async HttpGetJson(url: string, method: string = 'GET', data?: any, headers: { + [key: string]: string; + } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise { + const option = new URL(url); + const protocol = url.startsWith('https://') ? https : http; + const options = { + hostname: option.hostname, + port: option.port, + path: option.pathname + option.search, + method, + headers, + }; + + return new Promise((resolve, reject) => { + const req = protocol.request(options, (res: http.IncomingMessage) => { + if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) { + if (maxRedirects <= 0) { + reject(new Error('Too many redirects')); + return; + } + const redirectUrl = new URL(res.headers.location, url).href; + this.HttpGetJson(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1) + .then(resolve) + .catch(reject); + return; + } + + let responseBody = ''; + res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); }); + + res.on('end', () => { + try { + if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { + if (isJsonRet) { + resolve(JSON.parse(responseBody) as T); + } else { + resolve(responseBody as T); + } + } else { + reject(new Error(`Unexpected status code: ${res.statusCode}`)); + } + } catch (parseError: any) { + reject(new Error(parseError.message)); + } + }); + }); + + req.on('error', (error: Error) => reject(error)); + if (method === 'POST' || method === 'PUT' || method === 'PATCH') { + req.write(isArgJson ? JSON.stringify(data) : data); + } + req.end(); + }); + } + + static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) { + return this.HttpGetJson(url, method, data, headers, false, false); + } +} + +export function cookieToString(cookieObject: Record): string { + return Object.entries(cookieObject) + .map(([key, value]) => `${key}=${value}`) + .join('; '); +} + + +export function getBknFromCookie(cookieObject: Record): string { + const skey = cookieObject['p_skey'] || cookieObject['skey'] || ''; + let hash = 5381; + for (let i = 0; i < skey.length; i++) { + hash += (hash << 5) + skey.charCodeAt(i); + } + return (hash & 2147483647).toString(); +} diff --git a/packages/bridge/tsconfig.json b/packages/bridge/tsconfig.json new file mode 100644 index 00000000..4cd329d7 --- /dev/null +++ b/packages/bridge/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"], + "noEmit": true + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/packages/bridge/vitest.config.ts b/packages/bridge/vitest.config.ts new file mode 100644 index 00000000..57df30aa --- /dev/null +++ b/packages/bridge/vitest.config.ts @@ -0,0 +1,21 @@ +// Vitest config — only used by `pnpm bench` to drive the perf +// micro-benchmarks under `bench/`. There are no `*.test.ts` files in +// this package (bridge tests live in @snowluma/core's test suite by +// historical accident); if/when they migrate over, point +// `test.include` at them here. +import protobufVitePlugin from '@snowluma/proton/vite'; +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + // proton's vite plugin inlines `protobuf_encode` / `protobuf_decode` + // call sites at build time. Required for tinybench-driven benches to + // hit the production code path rather than proton's runtime-fallback + // (which throws unless a runtime-map JSON is loaded). + plugins: [protobufVitePlugin()], + test: { + benchmark: { + include: ['bench/**/*.bench.ts'], + }, + environment: 'node', + }, +}); diff --git a/packages/common/package.json b/packages/common/package.json new file mode 100644 index 00000000..4e378c72 --- /dev/null +++ b/packages/common/package.json @@ -0,0 +1,54 @@ +{ + "name": "@snowluma/common", + "version": "1.9.1", + "private": true, + "type": "module", + "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/bridge, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./logger": { + "types": "./src/logger.ts", + "default": "./src/logger.ts" + }, + "./hex": { + "types": "./src/hex.ts", + "default": "./src/hex.ts" + }, + "./json": { + "types": "./src/json.ts", + "default": "./src/json.ts" + }, + "./log-file-transport": { + "types": "./src/log-file-transport.ts", + "default": "./src/log-file-transport.ts" + }, + "./log-summary": { + "types": "./src/log-summary.ts", + "default": "./src/log-summary.ts" + }, + "./packet-sender": { + "types": "./src/packet-sender.ts", + "default": "./src/packet-sender.ts" + }, + "./protocol-types": { + "types": "./src/protocol-types.ts", + "default": "./src/protocol-types.ts" + }, + "./runtime": { + "types": "./src/runtime.ts", + "default": "./src/runtime.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@types/node": "^24.12.2", + "typescript": "catalog:" + } +} diff --git a/packages/core/src/utils/hex.ts b/packages/common/src/hex.ts similarity index 100% rename from packages/core/src/utils/hex.ts rename to packages/common/src/hex.ts diff --git a/packages/common/src/json.ts b/packages/common/src/json.ts new file mode 100644 index 00000000..1097fa01 --- /dev/null +++ b/packages/common/src/json.ts @@ -0,0 +1,16 @@ +// Plain JSON value types — defined here (not in @snowluma/onebot/types +// where they used to live) so @snowluma/bridge can talk about JSON-shaped +// payloads without importing OneBot. The OneBot types module keeps the +// names exported via re-export, so existing call sites that say +// `import type { JsonValue } from '<…>/onebot/types'` continue to work +// unchanged after Phase 3. +// +// Anything actually OneBot-specific (ApiResponse, OneBotRequest, …) +// stays in @snowluma/onebot — only the plain JSON quartet moves here. + +export type JsonPrimitive = string | number | boolean | null; +export type JsonValue = JsonPrimitive | JsonObject | JsonArray; +export interface JsonObject { + [key: string]: JsonValue; +} +export type JsonArray = JsonValue[]; diff --git a/packages/core/src/utils/log-file-transport.ts b/packages/common/src/log-file-transport.ts similarity index 88% rename from packages/core/src/utils/log-file-transport.ts rename to packages/common/src/log-file-transport.ts index e716c35e..d028d6c4 100644 --- a/packages/core/src/utils/log-file-transport.ts +++ b/packages/common/src/log-file-transport.ts @@ -1,21 +1,3 @@ -// File transport for the SnowLuma logger. -// -// Writes plain text (ANSI stripped) to: -// /snowluma-YYYY-MM-DD.log (shared, all UINs) -// //snowluma-YYYY-MM-DD.log (per-account) -// -// Both pathways use the same daily rotation + per-file size cap. When the -// cap is hit the in-flight file is closed and writes continue in -// snowluma-YYYY-MM-DD.1.log, .2.log, ... -// at the same date. Files older than the retain window are unlinked on -// startup and on each day rollover. -// -// Disabled via SNOWLUMA_LOG_FILE=0. Per-UIN sub-files are additionally -// gated by SNOWLUMA_LOG_PER_UIN=0 (still keeps the shared file). Any I/O -// failure during init or write degrades silently to console-only — we -// deliberately do NOT use the logger from inside this module to avoid -// recursion. - import fs from 'node:fs'; import path from 'node:path'; @@ -81,7 +63,6 @@ class FileWriter { fs.mkdirSync(dir, { recursive: true }); } catch (err) { this.disabled = true; - // eslint-disable-next-line no-console console.error( `[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`, ); @@ -170,12 +151,10 @@ class FileWriter { } const stream = fs.createWriteStream(p, { flags: 'a' }); stream.on('error', (err) => { - // eslint-disable-next-line no-console console.error(`[logger] file write error on ${p}: ${err.message}`); }); return { stream, bytes, date, splitIndex, path: p }; } catch (err) { - // eslint-disable-next-line no-console console.error( `[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`, ); diff --git a/packages/core/src/utils/log-summary.ts b/packages/common/src/log-summary.ts similarity index 80% rename from packages/core/src/utils/log-summary.ts rename to packages/common/src/log-summary.ts index 94ef38b1..dcec49d6 100644 --- a/packages/core/src/utils/log-summary.ts +++ b/packages/common/src/log-summary.ts @@ -1,12 +1,3 @@ -// Compact one-line param summary for log output. -// -// OneBot action params can include large message arrays / nested -// payloads that would blow the line width to multiple kilobytes if we -// JSON.stringify them naively. This helper produces a flat -// `k1=v1 k2=v2 ...` rendering with per-field truncation and a hard -// total cap, designed to be grep-friendly without flooding the log -// file. - const MAX_FIELD = 40; const MAX_TOTAL = 200; diff --git a/packages/core/src/utils/logger.ts b/packages/common/src/logger.ts similarity index 96% rename from packages/core/src/utils/logger.ts rename to packages/common/src/logger.ts index ce25d0b0..d5eabc93 100644 --- a/packages/core/src/utils/logger.ts +++ b/packages/common/src/logger.ts @@ -23,9 +23,6 @@ interface LogOptions { meta?: Record; } -// Fixed-width slot for the UIN tag in rendered output so the [Scope] -// column stays vertically aligned across lines with and without a UIN. -// Width covers `[1234567890]` (12 chars); anything longer just won't pad. const UIN_SLOT_WIDTH = 12; const LEVEL_WEIGHT: Record = { @@ -205,7 +202,7 @@ export interface Logger { * support (shown in the `[UIN]` slot and routed to a per-UIN file); * other keys are preserved on the options bag for forward compat. */ - child: (meta: { uin?: number; [k: string]: unknown }) => Logger; + child: (meta: { uin?: number;[k: string]: unknown }) => Logger; } function makeLogger(opts: LogOptions): Logger { diff --git a/packages/core/src/protocol/packet-sender.ts b/packages/common/src/packet-sender.ts similarity index 100% rename from packages/core/src/protocol/packet-sender.ts rename to packages/common/src/packet-sender.ts diff --git a/packages/core/src/protocol/types.ts b/packages/common/src/protocol-types.ts similarity index 62% rename from packages/core/src/protocol/types.ts rename to packages/common/src/protocol-types.ts index 8364ff87..ce34f342 100644 --- a/packages/core/src/protocol/types.ts +++ b/packages/common/src/protocol-types.ts @@ -8,9 +8,4 @@ export interface PacketInfo { fromClient: boolean; body: Uint8Array; } - -/** - * Packet sink injected into HookSession / HookManager. The default - * wiring forwards to BridgeManager.onPacket, but tests inject spies. - */ export type PacketSink = (packet: PacketInfo) => void; diff --git a/packages/core/src/common/runtime.ts b/packages/common/src/runtime.ts similarity index 100% rename from packages/core/src/common/runtime.ts rename to packages/common/src/runtime.ts diff --git a/packages/common/tsconfig.json b/packages/common/tsconfig.json new file mode 100644 index 00000000..4cd329d7 --- /dev/null +++ b/packages/common/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"], + "noEmit": true + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/packages/core/bench/proton-vs-legacy.ts b/packages/core/bench/proton-vs-legacy.ts deleted file mode 100644 index 3f8eb304..00000000 --- a/packages/core/bench/proton-vs-legacy.ts +++ /dev/null @@ -1,172 +0,0 @@ -// Proton vs legacy runtime ProtoSchema encoder/decoder benchmark. -// -// Compares the codec functions generated at build time by @snowluma/proton -// against the runtime schema-walking implementation in src/protobuf/decode.ts, -// using the actual long-message schemas already in the codebase. -// -// Methodology: -// - Proton codecs are produced by calling its `analyzeSource` + `generateCode` -// API on the existing proto/proton/longmsg.ts source file, then `new -// Function`-eval'd into a callable. This is identical to what the Vite -// plugin does at build time, minus the file-replacement step. -// - Legacy codecs are the existing `protoEncode` / `protoDecode` functions -// called against the existing `*Schema` constants. -// - Each measurement does 2 000 warmup iterations, then N timed iterations. -// - Operation cost is reported as ops/sec and ns/op. The first row's -// ops/sec is the relative baseline. -// -// Run: -// pnpm --filter @snowluma/core exec tsx bench/proton-vs-legacy.ts - -import { readFileSync } from 'fs'; -import { resolve, dirname } from 'path'; -import { fileURLToPath } from 'url'; -import { analyzeSource, generateCode } from '@snowluma/proton/vite'; -import { protoEncode, protoDecode } from '../src/protobuf/decode'; -import { - LongMsgSettingsSchema, - SendLongMsgRespSchema, - SendLongMsgReqSchema, - RecvLongMsgRespSchema, -} from '../src/bridge/proto/longmsg'; - -// ── proton codec materialisation ───────────────────────────────────── - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const protonSchemaPath = resolve(__dirname, '..', 'src', 'bridge', 'proto', 'proton', 'longmsg.ts'); -const protonSchemaSource = readFileSync(protonSchemaPath, 'utf-8'); - -function materialiseProton(messageNames: readonly string[]): Record Uint8Array; decode: (b: Uint8Array) => unknown }> { - // Append synthetic call sites so the registry actually contains the messages - // we want — `selectUsedRegistry` only retains call-site roots, and the - // proton/longmsg.ts source itself has no `protobuf_encode` calls. - const callSites = messageNames - .map((n) => `protobuf_encode<${n}>({} as any); protobuf_decode<${n}>(new Uint8Array());`) - .join('\n'); - const sourceWithCallSites = protonSchemaSource + `\n\n// synthetic call sites for bench codegen\n` + callSites; - - const registry = analyzeSource(sourceWithCallSites, protonSchemaPath); - const code = generateCode(registry); - const factoryBody = ` - ${code} - const out = {}; - ${messageNames.map(n => `out.${n} = { encode: protobuf_encode_${n}, decode: protobuf_decode_${n} };`).join('\n')} - return out; - `; - return new Function(factoryBody)() as Record Uint8Array; decode: (b: Uint8Array) => unknown }>; -} - -const proton = materialiseProton([ - 'LongMsgSettings', - 'SendLongMsgResp', - 'SendLongMsgReq', - 'RecvLongMsgResp', -]); - -// ── bench harness ──────────────────────────────────────────────────── - -interface BenchResult { name: string; opsPerSec: number; nsPerOp: number; } - -function bench(name: string, fn: () => void, iterations: number): BenchResult { - for (let i = 0; i < 2000; i++) fn(); - const start = performance.now(); - for (let i = 0; i < iterations; i++) fn(); - const ms = performance.now() - start; - return { - name, - opsPerSec: Math.round((iterations / ms) * 1000), - nsPerOp: Math.round((ms / iterations) * 1_000_000), - }; -} - -function printSection(title: string, results: BenchResult[]) { - console.log(`\n## ${title}`); - console.log('| Encoder | ops/sec | ns/op | relative |'); - console.log('|------------|-------------|--------|----------|'); - const baseline = results[0].opsPerSec; - for (const r of results) { - const rel = r.opsPerSec / baseline; - const relStr = r === results[0] ? '1.00×' : `${rel.toFixed(2)}×`; - console.log( - `| ${r.name.padEnd(10)} | ${r.opsPerSec.toLocaleString().padStart(11)} | ${String(r.nsPerOp).padStart(6)} | ${relStr.padStart(8)} |`, - ); - } -} - -// ── workloads ──────────────────────────────────────────────────────── - -const settingsObj = { field1: 4, field2: 1, field3: 7, field4: 2 }; - -const sendRespObj = { result: { resId: 'res-001' } }; - -const sendReqObj = { - info: { - type: 1, - uid: { uid: 'u_test' }, - groupUin: 123456, - payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]), - }, - settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, -}; - -const recvRespObj = { - result: { resId: 'r-1', payload: new Uint8Array(64).fill(0x42) }, - settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, -}; - -// Pre-encoded bytes for decode benches (use proton output so both sides see -// identical, proto3-conforming input). -const settingsBytes = proton.LongMsgSettings.encode(settingsObj); -const sendRespBytes = proton.SendLongMsgResp.encode(sendRespObj); -const sendReqBytes = proton.SendLongMsgReq.encode(sendReqObj); -const recvRespBytes = proton.RecvLongMsgResp.encode(recvRespObj); - -// ── run ────────────────────────────────────────────────────────────── - -console.log('# @snowluma/proton vs legacy runtime benchmark\n'); -console.log(`Node ${process.version} | ${process.platform} ${process.arch}`); -console.log(`Date: ${new Date().toISOString().slice(0, 19).replace('T', ' ')}`); - -const N = 300_000; - -printSection('Encode — LongMsgSettings (4× uint32)', [ - { ...bench('proton', () => proton.LongMsgSettings.encode(settingsObj), N) }, - { ...bench('legacy', () => protoEncode(settingsObj, LongMsgSettingsSchema), N) }, -]); - -printSection('Decode — LongMsgSettings (4× uint32)', [ - { ...bench('proton', () => proton.LongMsgSettings.decode(settingsBytes), N) }, - { ...bench('legacy', () => protoDecode(settingsBytes, LongMsgSettingsSchema), N) }, -]); - -printSection('Encode — SendLongMsgResp (1 nested message, 1 string)', [ - { ...bench('proton', () => proton.SendLongMsgResp.encode(sendRespObj), N) }, - { ...bench('legacy', () => protoEncode(sendRespObj, SendLongMsgRespSchema), N) }, -]); - -printSection('Decode — SendLongMsgResp', [ - { ...bench('proton', () => proton.SendLongMsgResp.decode(sendRespBytes), N) }, - { ...bench('legacy', () => protoDecode(sendRespBytes, SendLongMsgRespSchema), N) }, -]); - -printSection('Encode — SendLongMsgReq (deeply nested, bytes + uint32 + string)', [ - { ...bench('proton', () => proton.SendLongMsgReq.encode(sendReqObj), N) }, - { ...bench('legacy', () => protoEncode(sendReqObj, SendLongMsgReqSchema), N) }, -]); - -printSection('Decode — SendLongMsgReq', [ - { ...bench('proton', () => proton.SendLongMsgReq.decode(sendReqBytes), N) }, - { ...bench('legacy', () => protoDecode(sendReqBytes, SendLongMsgReqSchema), N) }, -]); - -printSection('Encode — RecvLongMsgResp (64-byte payload + settings)', [ - { ...bench('proton', () => proton.RecvLongMsgResp.encode(recvRespObj), N) }, - { ...bench('legacy', () => protoEncode(recvRespObj, RecvLongMsgRespSchema), N) }, -]); - -printSection('Decode — RecvLongMsgResp', [ - { ...bench('proton', () => proton.RecvLongMsgResp.decode(recvRespBytes), N) }, - { ...bench('legacy', () => protoDecode(recvRespBytes, RecvLongMsgRespSchema), N) }, -]); - -console.log(''); diff --git a/packages/core/package.json b/packages/core/package.json index 62b4008d..0a2b6dd1 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,10 +1,36 @@ { "name": "@snowluma/core", - "version": "1.9.0", + "version": "1.9.1", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", "main": "../../dist/index.mjs", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "../../dist/index.mjs" + }, + "./bridge": { + "types": "./src/bridge/bridge.ts", + "default": "./src/bridge/bridge.ts" + }, + "./bridge-interface": { + "types": "./src/bridge/bridge-interface.ts", + "default": "./src/bridge/bridge-interface.ts" + }, + "./bridge-context": { + "types": "./src/bridge/bridge-context.ts", + "default": "./src/bridge/bridge-context.ts" + }, + "./manager": { + "types": "./src/bridge/manager.ts", + "default": "./src/bridge/manager.ts" + }, + "./apis": { + "types": "./src/bridge/apis/index.ts", + "default": "./src/bridge/apis/index.ts" + } + }, "scripts": { "build": "vite build", "build:all": "cross-env BUILD_WEBUI=true vite build", @@ -14,7 +40,12 @@ "typecheck": "tsc --noEmit" }, "dependencies": { + "@snowluma/bridge": "workspace:*", + "@snowluma/common": "workspace:*", + "@snowluma/onebot": "workspace:*", + "@snowluma/proto-defs": "workspace:*", "@snowluma/proton": "workspace:*", + "@snowluma/sqlite": "workspace:*", "@snowluma/websocket": "workspace:*" }, "devDependencies": { diff --git a/packages/core/src/bridge/actions/extras.ts b/packages/core/src/bridge/actions/extras.ts deleted file mode 100644 index ae8e2a6f..00000000 --- a/packages/core/src/bridge/actions/extras.ts +++ /dev/null @@ -1,137 +0,0 @@ -// Tier-2 napcat-parity actions ported as pure oidb calls. Each function -// here corresponds to one napcat PacketApi.pkt.operation.* entry; the -// schemas live in proto/oidb-action.ts. Nothing in this file touches -// the NTQQ NodeIKernel — every wire trip is one runOidb round-trip. - -import type { Bridge } from '../bridge'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; -import type { - OidbAiVoiceListReq, - OidbAiVoiceListResp, - OidbAiVoiceReq, - OidbAiVoiceResp, - OidbGroupTodo, - OidbStrangerStatusReq, - OidbStrangerStatusResp, -} from '../proto/proton/oidb-action'; -import type { MediaIndexNode } from './shared'; - -// ─────────────── Group todo (0xF90) ─────────────── - -export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - const env = makeOidbEnvelope(0xF90, 1, { groupUin: groupId, msgSeq }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', encodeOidbEnv(env)); -} - -export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - const env = makeOidbEnvelope(0xF90, 2, { groupUin: groupId, msgSeq }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', encodeOidbEnv(env)); -} - -export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - const env = makeOidbEnvelope(0xF90, 3, { groupUin: groupId, msgSeq }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', encodeOidbEnv(env)); -} - -// ─────────────── Stranger online/ext status (0xFE1_2) ─────────────── - -export interface StrangerStatus { - status: number; - ext_status: number; -} - -/** - * Mirror napcat's GetStrangerStatus: decode the extBigInt status word. - * Values ≤10 fold into a 10×status; everything else is split into the - * high-byte / low-byte ext_status the OneBot dialect uses. - * - * Returns null on transport / decode failure rather than throwing, so - * the OneBot action can produce a clean retcode without try/catch - * gymnastics. - */ -export async function getStrangerStatus(bridge: Bridge, uin: number): Promise { - try { - const env = makeOidbEnvelope( - 0xFE1, 2, - { uin, key: [{ key: 27372 }] } as any, - // Same UIN-form flag fetchUserProfile sets — without it newer - // QQ NT rejects with `[oidb] one of uid/openid is invaild`. - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - const raw = resp?.data?.status?.value; - if (raw === undefined || raw === null) return null; - const extBig = typeof raw === 'bigint' ? raw : BigInt(raw); - if (extBig <= 10n) { - return { status: Number(extBig) * 10, ext_status: 0 }; - } - const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn)); - return { status: 10, ext_status: status }; - } catch { - return null; - } -} - -// ─────────────── AI voice (0x929D / 0x929B) ─────────────── - -export const AiVoiceChatType = { - Unknown: 0, - Sound: 1, - Sing: 2, -} as const; -export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType]; - -export interface AiVoiceItem { - voiceId: string; - voiceDisplayName: string; - voiceExampleUrl: string; -} - -export interface AiVoiceCategory { - category: string; - voices: AiVoiceItem[]; -} - -export async function fetchAiVoiceList( - bridge: Bridge, - groupId: number, - chatType: AiVoiceChatType, -): Promise { - const env = makeOidbEnvelope(0x929D, 0, { groupUin: groupId, chatType }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - return (resp?.content as AiVoiceCategory[] | undefined) ?? []; -} - -/** - * Trigger AI voice synthesis. Server may return an empty msgInfo while - * the render is in-flight; we retry until a node materialises or the - * cap is hit. napcat uses the same 30-retry budget. - * - * The returned MediaIndexNode plugs directly into - * `bridge.fetchGroupPttUrlByNode`, which already handles every other - * download-URL fetch in SnowLuma. - */ -export async function fetchAiVoice( - bridge: Bridge, - groupId: number, - voiceId: string, - text: string, - chatType: AiVoiceChatType, - maxRetries = 30, -): Promise { - // Random 32-bit session id — server uses this to deduplicate polls. - const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0; - for (let i = 0; i < maxRetries; i++) { - const env = makeOidbEnvelope( - 0x929B, 0, - { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined; - if (node) return node; - } - throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); -} diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts deleted file mode 100644 index ddca085b..00000000 --- a/packages/core/src/bridge/actions/forward.ts +++ /dev/null @@ -1,480 +0,0 @@ -// Forward-message upload / download via the long-message service. -// Uses gzipped protobufs over `trpc.group.long_msg_interface`. -// An in-memory cache keeps res_ids stable across rapid re-fetches -// from the same OneBot client (avoids re-decoding the same payload). - -import type { Bridge } from '../bridge'; -import { gunzipSync, gzipSync } from 'zlib'; -import { randomUUID } from 'crypto'; -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; -import { buildSendElems } from '../element-builder'; -import { parseMsgPush } from '../msg-push'; -import type { ForwardNodePayload, MessageElement } from '../events'; -import type { PacketInfo } from '../../protocol/types'; -import type { - LongMsgResult, - RecvLongMsgReq, - RecvLongMsgResp, - SendLongMsgReq, - SendLongMsgResp, -} from '../proto/proton/longmsg'; -import type { FileExtra, PushMsg, PushMsgBody } from '../proto/proton/message'; -import { resolveSelfUid, toInt } from './shared'; - -// Module-scoped cache, keyed by res_id. Survives only for the lifetime -// of the process — that's enough because OneBot clients typically -// resolve a forward immediately after receiving the parent message. -const forwardResCache = new Map(); - -async function buildForwardPushBody( - bridge: Bridge, - node: ForwardNodePayload, - groupId?: number, - userUid?: string, -): Promise { - const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin); - if (fromUin <= 0) throw new Error('forward node user uin is invalid'); - - const nickname = node.nickname.trim() || String(fromUin); - // image/record/video upload inside a forward node must be scoped to the - // forward's recipient: group → groupId, private → recipient uid. - // Without this the OIDB upload (0x11c4/0x11c5) has no scene and the - // element builder throws "private image target uid is missing". - // - // `forwardFake: true` keeps `{type:'file'}` segments in the - // long-msg payload: group → emitted as transElem(24) in elems[], - // c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }). - // The QQ-NT live-send pipeline would reject these (transElem(24) → - // result=79; notOnlineFile via PbSendMsg doesn't render), but the - // long-msg upload service stores the bytes verbatim and the - // receiver decodes them through the normal msg-push path. - const sendCtx = groupId !== undefined - ? { bridge, groupId, forwardFake: true } - : userUid - ? { bridge, userUid, forwardFake: true } - : { bridge, forwardFake: true }; - const elems = await buildSendElems(node.elements, sendCtx); - const now = Math.floor(Date.now() / 1000); - const random = Math.floor(Math.random() * 0x7fffffff) >>> 0; - const seq = Math.floor(Math.random() * 9000000) + 1000000; - - // c2c-file in a forward node — element-builder intentionally skips - // it (RichText.notOnlineFile + msgContent live outside elems[]). For - // forward fake-send we mirror what an inbound c2c file message looks - // like on the wire: serialise the FileExtra blob and ride it on - // `body.msgContent`. The receiver's rich-body-decoder reads from - // `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so - // the bubble renders with the right file name + size when the - // forward is expanded. Only the FIRST c2c file in a node ships — - // QQ NT's bubble can only carry one msgContent payload, same as - // a live c2c send. Group nodes ignore this branch entirely (the - // transElem(24) elems[] entry above covers them). - let msgContent: Uint8Array | undefined; - if (groupId === undefined) { - const fileEl = node.elements.find(e => e.type === 'file' && e.fileId); - if (fileEl) { - // Honour inline segment fields first; fall back to the upload - // metadata cache (populated by upload_private_file). Without - // size/md5 the receiver would render "0 B" so prefer recovering - // them — see same logic in modules/message-actions.ts. - const cached = bridge.recallUploadedFile(fileEl.fileId ?? ''); - const fileMd5 = fileEl.md5Hex - ? hexToBytesLocal(fileEl.md5Hex) - : (cached?.fileMd5 ?? new Uint8Array(0)); - const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0; - const fileName = fileEl.fileName ?? cached?.fileName ?? 'file'; - const fileHash = fileEl.fileHash ?? cached?.fileHash ?? ''; - const sevenDays = 7 * 24 * 60 * 60; - msgContent = protobuf_encode({ - file: { - fileType: 0, - fileUuid: fileEl.fileId!, - fileMd5, - fileName, - fileSize: BigInt(fileSize), - subcmd: 1, - dangerEvel: 0, - expireTime: now + sevenDays, - fileHash, - }, - }); - } - } - - return { - responseHead: { - fromUin, - toUid: bridge.identity.selfUid ?? '', - forward: { - friendName: nickname, - }, - }, - contentHead: { - msgType: 9, - subType: 4, - msgId: random, - sequence: seq, - timestamp: now, - divSeq: 0, - }, - body: { - richText: { - elems, - }, - ...(msgContent ? { msgContent } : {}), - }, - }; -} - -// Local hex-decode helper — avoids importing the heavyweight `pipeline` -// module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`. -function hexToBytesLocal(hex: string): Uint8Array { - const s = hex.trim(); - if (!s) return new Uint8Array(0); - const len = s.length >> 1; - const out = new Uint8Array(len); - for (let i = 0; i < len; i++) { - out[i] = parseInt(s.substr(i * 2, 2), 16); - } - return out; -} - -// Per-layer piggyback entry. Each level of a nested forward attaches -// its own msgBody under a uuid `actionCommand`, so when the receiver -// fetches the outermost res_id it gets every layer in one shot -// (modelled on NapCat's `uploadForwardedNodesPacket` — see -// `dev/NapCatQQ/.../SendMsg.ts:208-347`). Lagrange.Core master + V2 -// both ship a single-action model and silently break when the -// recipient is a NapCat instance trying to walk the tree. -interface ForwardInnerAction { - uuid: string; - msgBody: PushMsgBody[]; -} - -interface ForwardUploadResult { - resId: string; - // The current level's msgBody + uuid — what an outer caller would - // piggyback to expose this layer through the tree. - msgBody: PushMsgBody[]; - uuid: string; - // All accumulated piggyback entries from deeper levels. Outer - // callers concatenate these to their own actions list so the - // outermost upload carries the full tree. - innerActions: ForwardInnerAction[]; -} - -export async function uploadForwardNodes( - bridge: Bridge, - nodes: ForwardNodePayload[], - groupId?: number, - userId?: number, -): Promise { - const { resId } = await uploadForwardNodesRecursive(bridge, nodes, groupId, userId); - return resId; -} - -/** - * Recursive upload with NapCat-style piggyback. Each invocation: - * 1. Walks `nodes`. For any node whose `innerForward` is set, - * recursively uploads that inner chain first (which itself runs - * this same recursion). - * 2. Replaces the node's `elements` with an ARK preview pointing at - * the inner res_id (and inner uuid for receiver-side walking). - * 3. Accumulates the inner level's `{uuid, msgBody}` plus all of - * ITS accumulated `innerActions` into this level's piggyback list. - * 4. Encodes this level's long-msg payload as - * `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it, - * returns `{resId, msgBody, uuid, innerActions}` so an outer - * caller can keep piggybacking up the tree. - */ -async function uploadForwardNodesRecursive( - bridge: Bridge, - nodes: ForwardNodePayload[], - groupId?: number, - userId?: number, -): Promise { - if (!Array.isArray(nodes) || nodes.length === 0) { - throw new Error('forward nodes are required'); - } - - // For a private forward to `userId`, any image/record/video inside a node - // needs the recipient's uid as upload scene. Resolve it once up-front, - // and only when at least one node actually contains media (saves an RPC - // for text-only forwards). Also need it when a node is itself a nested - // forward — the inner upload uses the same scene. - let userUid: string | undefined; - if (groupId === undefined && userId !== undefined && userId > 0) { - const needsUid = nodes.some(node => !!node.innerForward - || node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video')); - if (needsUid) { - const resolved = await bridge.resolveUserUid(userId); - if (resolved) userUid = resolved; - } - } - - // Walk nodes and resolve nested forwards first (so we know their - // res_id / uuid before encoding the outer ARK previews). Build - // `processedNodes` with elements rewritten for nested layers, - // and collect every inner level's piggyback in `myInnerActions`. - const myInnerActions: ForwardInnerAction[] = []; - const processedNodes: ForwardNodePayload[] = []; - const isGroup = groupId !== undefined; - for (const node of nodes) { - if (node.innerForward && node.innerForward.length > 0) { - const inner = await uploadForwardNodesRecursive(bridge, node.innerForward, groupId, userId); - // NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}` - // + the entire `inner.innerPacketMsg` array up to its caller. We - // mirror that — `inner.uuid` indexes the inner level itself, - // and `inner.innerActions` already contains deeper layers. - myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody }); - myInnerActions.push(...inner.innerActions); - // Replace the inner placeholder element with a forward preview - // pointing at the inner res_id. The wire-side element builder - // turns this into the same XML m_resid blob it already produced - // for top-level forwards — see `makeForwardElem` in - // element-builder.ts:153. - const previewElement: MessageElement = { - type: 'forward', - resId: inner.resId, - forwardSource: deriveInnerSource(node.innerForward, isGroup), - forwardSummary: `查看${node.innerForward.length}条转发消息`, - forwardPrompt: '[聊天记录]', - forwardNews: previewLinesFromNodes(node.innerForward), - forwardTSum: node.innerForward.length, - }; - processedNodes.push({ - userUin: node.userUin, - nickname: node.nickname, - elements: [previewElement], - time: node.time, - msgId: node.msgId, - msgSeq: node.msgSeq, - groupId: node.groupId, - senderCard: node.senderCard, - messageType: node.messageType, - }); - } else { - processedNodes.push(node); - } - } - - // Encode this level's msgBody. - const msgBody = await Promise.all(processedNodes.map( - node => buildForwardPushBody(bridge, node, groupId, userUid), - )); - - // Compose the action list: own MultiMsg + piggybacked inner actions. - const longMsgResult = protobuf_encode({ - action: [ - { actionCommand: 'MultiMsg', actionData: { msgBody } }, - ...myInnerActions.map(a => ({ - actionCommand: a.uuid, - actionData: { msgBody: a.msgBody }, - })), - ], - }); - - const selfUid = await resolveSelfUid(bridge); - const info: SendLongMsgReq['info'] = { - type: groupId ? 3 : 1, - uid: { uid: groupId ? String(groupId) : selfUid }, - payload: gzipSync(Buffer.from(longMsgResult)), - }; - if (groupId) info.groupUin = groupId; - - const request = protobuf_encode({ - info, - settings: { - field1: 4, - field2: 1, - field3: 7, - field4: 0, - }, - }); - - const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'upload forward message failed'); - } - - const resp = protobuf_decode(result.responseData); - const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : ''; - if (!resId) { - throw new Error('upload forward message response missing res_id'); - } - - forwardResCache.set(resId, processedNodes.map(node => ({ - userUin: node.userUin, - nickname: node.nickname, - elements: [...node.elements], - time: node.time, - msgId: node.msgId, - msgSeq: node.msgSeq, - groupId: node.groupId ?? groupId, - senderCard: node.senderCard, - messageType: node.messageType ?? (groupId ? 'group' : 'private'), - }))); - - return { - resId, - msgBody, - uuid: randomUUID(), - innerActions: myInnerActions, - }; -} - -// Inner forward preview metadata — kept minimal here (the OneBot -// `parseForwardNodes` caller can override these on the top-level -// node by passing custom forwardSource/forwardSummary on the -// non-nested send path; nested levels just get sensible defaults -// since they're synthesised by us and never reach OneBot input). -function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string { - const nicks: string[] = []; - const seen = new Set(); - for (const node of innerNodes) { - const name = (node.nickname ?? '').trim(); - if (name && !seen.has(name)) { - seen.add(name); - nicks.push(name); - } - if (nicks.length >= 4) break; - } - if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录'; - return `${nicks.join('和')}的聊天记录`; -} - -function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> { - return innerNodes.slice(0, 4).map(node => { - const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户'); - const previewText = previewFromElements(node.elements); - return { text: previewText ? `${name}: ${previewText}` : name }; - }); -} - -function previewFromElements(elements: MessageElement[]): string { - for (const elem of elements) { - if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30); - if (elem.type === 'image') return '[图片]'; - if (elem.type === 'record') return '[语音]'; - if (elem.type === 'video') return '[视频]'; - if (elem.type === 'file') return '[文件]'; - if (elem.type === 'forward') return '[聊天记录]'; - if (elem.type === 'face') return '[表情]'; - } - return ''; -} - -export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise { - const cached = forwardResCache.get(resId); - if (cached) { - return cached.map(node => ({ - userUin: node.userUin, - nickname: node.nickname, - elements: [...node.elements], - time: node.time, - msgId: node.msgId, - msgSeq: node.msgSeq, - groupId: node.groupId, - senderCard: node.senderCard, - messageType: node.messageType, - })); - } - - const selfUid = await resolveSelfUid(bridge); - const request = protobuf_encode({ - info: { - uid: { uid: selfUid }, - resId, - acquire: true, - }, - settings: { - field1: 2, - field2: 0, - field3: 0, - field4: 0, - }, - }); - - const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'download forward message failed'); - } - - const resp = protobuf_decode(result.responseData); - const payload = resp?.result?.payload; - if (!(payload instanceof Uint8Array) || payload.length === 0) { - throw new Error('download forward message payload is empty'); - } - - const inflate = gunzipSync(Buffer.from(payload)); - const longMsg = protobuf_decode(inflate); - const action = longMsg?.action?.find((item) => item?.actionCommand === 'MultiMsg'); - const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : []; - - const nodes: ForwardNodePayload[] = []; - for (const msgBody of msgBodyList) { - const wrapped = protobuf_encode({ message: msgBody }); - const pkt: PacketInfo = { - pid: 0, - uin: bridge.identity.uin, - serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', - seqId: 0, - retCode: 0, - fromClient: false, - body: wrapped, - }; - const events = parseMsgPush(pkt, bridge.identity); - const event = events.find(e => - e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message'); - if (!event) continue; - - if (event.kind === 'group_message') { - nodes.push({ - userUin: event.senderUin, - nickname: event.senderCard || event.senderNick, - elements: event.elements, - time: event.time, - msgId: event.msgId, - msgSeq: event.msgSeq, - groupId: event.groupId, - senderCard: event.senderCard, - messageType: 'group', - }); - } else if (event.kind === 'friend_message') { - nodes.push({ - userUin: event.senderUin, - nickname: event.senderNick, - elements: event.elements, - time: event.time, - msgId: event.msgId, - msgSeq: event.msgSeq, - messageType: 'private', - }); - } else { - nodes.push({ - userUin: event.senderUin, - nickname: event.senderNick, - elements: event.elements, - time: event.time, - msgSeq: event.msgSeq, - groupId: event.groupId, - messageType: 'private', - }); - } - } - - if (nodes.length > 0) { - forwardResCache.set(resId, nodes.map(node => ({ - userUin: node.userUin, - nickname: node.nickname, - elements: [...node.elements], - time: node.time, - msgId: node.msgId, - msgSeq: node.msgSeq, - groupId: node.groupId, - senderCard: node.senderCard, - messageType: node.messageType, - }))); - } - return nodes; -} diff --git a/packages/core/src/bridge/actions/friend.ts b/packages/core/src/bridge/actions/friend.ts deleted file mode 100644 index c4ff1510..00000000 --- a/packages/core/src/bridge/actions/friend.ts +++ /dev/null @@ -1,52 +0,0 @@ -// Friend-list operations: accept/reject add request, delete, set the -// local remark label. Each one resolves a UID first because the OIDB -// protocol uses opaque UIDs rather than QQ uin numbers. - -import type { Bridge } from '../bridge'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb'; -import type { - OidbDeleteFriend, - OidbFriendRequestAction, - OidbSetFriendRemark, -} from '../proto/proton/oidb-action'; - -export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise { - let targetUid = uidOrFlag; - if (/^\d+$/.test(uidOrFlag)) { - targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10)); - } - const env = makeOidbEnvelope(0xB5D, 44, { accept: approve ? 3 : 5, targetUid }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', encodeOidbEnv(env)); -} - -export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise { - const targetUid = await bridge.resolveUserUid(userId); - const env = makeOidbEnvelope(0x126B, 0, { - field1: { - targetUid, - field2: { - field1: 130, - field2: 109, - field3: { - field1: 8, - field2: 8, - field3: 50, - }, - }, - block, - field4: false, - }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x126b_0', encodeOidbEnv(env)); - - // Refresh friend cache after deletion so subsequent reads don't - // surface a ghost entry. Best-effort: a transient OIDB hiccup here - // shouldn't make the delete itself look failed. - try { await bridge.fetchFriendList(); } catch { /* ignore */ } -} - -export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise { - const uid = await bridge.resolveUserUid(userId); - const env = makeOidbEnvelope(0xB6E, 2, { targetUid: uid, remark }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', encodeOidbEnv(env)); -} diff --git a/packages/core/src/bridge/actions/group-admin.ts b/packages/core/src/bridge/actions/group-admin.ts deleted file mode 100644 index 25b2eafd..00000000 --- a/packages/core/src/bridge/actions/group-admin.ts +++ /dev/null @@ -1,165 +0,0 @@ -// Group admin actions: mute/kick/leave/role/profile + join-request approval. -// Every function ultimately routes through one OIDB schema; the function -// names match the OneBot action names (set_group_kick, set_group_ban, ...) -// so callers can grep across the two layers. - -import type { Bridge } from '../bridge'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; -import type { - Oidb0x89a_0AddOption, - Oidb0x89a_0Search, - Oidb0x8a0Req, - Oidb0x8a7Req, - Oidb0x8a7Resp, - Oidb0xf16Req, - OidbGroupRequestAction, - OidbKickMember, - OidbLeaveGroup, - OidbMuteAll, - OidbMuteMember, - OidbRenameGroup, - OidbRenameMember, - OidbSetAdmin, - OidbSpecialTitle, -} from '../proto/proton/oidb-action'; - -// ─────────────── mute / un-mute ─────────────── - -export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise { - const uid = await bridge.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x1253, 1, { - groupUin: groupId, type: 1, body: { targetUid: uid, duration }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x1253_1', encodeOidbEnv(env)); -} - -export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise { - const env = makeOidbEnvelope(0x89A, 0, { - groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env)); -} - -// ─────────────── join-policy ─────────────── - -export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise { - const env = makeOidbEnvelope(0x89A, 0, { - groupUin: BigInt(groupId), settings: { addType }, field12: 0, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env)); -} - -export async function setGroupSearch(bridge: Bridge, groupId: number): Promise { - const env = makeOidbEnvelope(0x89A, 0, { - groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env)); -} - -export async function setGroupAddRequest( - bridge: Bridge, groupId: number, sequence: number, eventType: number, - approve: boolean, reason = '', filtered = false, -): Promise { - const subCmd = filtered ? 2 : 1; - const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1'; - const env = makeOidbEnvelope( - 0x10C8, subCmd, - { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, - true, - ); - await runOidb(bridge, cmd, encodeOidbEnv(env)); -} - -// ─────────────── kick / leave ─────────────── - -export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise { - const uid = await bridge.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x8A0, 1, { - groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv(env)); -} - -export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise { - const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId))); - const env = makeOidbEnvelope(0x8A0, 1, { - groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv(env)); -} - -export async function leaveGroup(bridge: Bridge, groupId: number): Promise { - const env = makeOidbEnvelope(0x1097, 1, { groupUin: groupId }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x1097_1', encodeOidbEnv(env)); -} - -// ─────────────── role / display name ─────────────── - -export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise { - const uid = await bridge.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x1096, 1, { groupUin: groupId, uid, isAdmin: enable }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x1096_1', encodeOidbEnv(env)); -} - -export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise { - const uid = await bridge.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x8FC, 3, { - groupUin: groupId, body: { targetUid: uid, targetName: card }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_3', encodeOidbEnv(env)); -} - -export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise { - const env = makeOidbEnvelope(0x89A, 15, { groupUin: groupId, body: { targetName: name } }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_15', encodeOidbEnv(env)); -} - -export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise { - const uid = await bridge.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x8FC, 2, { - groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_2', encodeOidbEnv(env)); -} - -// ─────────────── personal-side metadata ─────────────── - -// setGroupRemark is the bot's local-only label for the group; it lives -// here rather than in friend.ts because the semantic is "operate on a -// group" rather than "operate on a contact list". -export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise { - const env = makeOidbEnvelope(0xF16, 1, { inner: { groupId: BigInt(groupId), remark }, field12: 0 }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf16_1', encodeOidbEnv(env)); -} - -// ─────────────── group-level quota query ─────────────── - -export async function getGroupAtAllRemain( - bridge: Bridge, - groupId: number, -) { - const req = { - basic1: 1, - basic2: 2, - basic3: 1, - uin: BigInt(bridge.identity.uin), - groupId: BigInt(groupId), - type: 0, - }; - - const env = makeOidbEnvelope(0x8A7, 0, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a7_0', encodeOidbEnv(env)); - const result = decodeOidbEnv(respBytes).body; - - if (!result) { - throw new Error('get group at all remain result empty'); - } - - // Cast numbers to plain Number: the OIDB layer may surface uint32 as - // BigInt and the WebUI JSON serializer chokes on those. - return { - can_at_all: !!result.canAtAll, - remain_at_all_count_for_group: Number(result.groupRemain || 0), - remain_at_all_count_for_uin: Number(result.uinRemain || 0), - }; -} diff --git a/packages/core/src/bridge/actions/group-album.ts b/packages/core/src/bridge/actions/group-album.ts deleted file mode 100644 index 75c8e135..00000000 --- a/packages/core/src/bridge/actions/group-album.ts +++ /dev/null @@ -1,289 +0,0 @@ -// Group album actions via TRPC protocol. -// -// Unlike the OIDB action family, these endpoints speak raw TRPC -// (service command `QunAlbum.trpc.qzone.webapp_qun_*`) without an -// `OidbBase` envelope. We hit `bridge.sendRawPacket` directly with -// proton-encoded bodies and decode the responses through proton's -// monomorphized codecs. - -import type { Bridge } from '../bridge'; -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; -import type { - GetMediaListRequest, - GetMediaListResponse, - DoQunCommentRequest, - DoQunCommentResponse, - DoQunLikeRequest, - DoQunLikeResponse, - DeleteMediasRequest, - DeleteMediasResponse, -} from '../proto/proton/oidb-action'; - -export interface GroupAlbumMediaResult { - mediaList: any[]; - nextAttachInfo: string; -} - -export interface GroupAlbumCommentResult { - id: string; - user: { uin: string }; - content: Array<{ type: number; content: string }>; - time: string; - clientKey: string; -} - -function convertBigIntToString(obj: any): any { - if (obj === null || obj === undefined) return obj; - if (typeof obj === 'bigint') return obj.toString(); - if (Array.isArray(obj)) return obj.map(convertBigIntToString); - if (typeof obj === 'object') { - const result: any = {}; - for (const key in obj) { - result[key] = convertBigIntToString(obj[key]); - } - return result; - } - return obj; -} - -export async function getGroupAlbumMediaList( - bridge: Bridge, - groupId: number, - albumId: string, - attachInfo: string = '' -): Promise { - const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - - const body = protobuf_encode({ - field1: 0, - field2: new Uint8Array(0), - field3: new Uint8Array(0), - reqInfo: { - groupId: groupId.toString(), - albumId: albumId, - field3: 0, - attachInfo: attachInfo, - field5: '', - }, - traceId: traceId, - extMap: [{ key: 'fc-appid', value: '100' }], - }); - - const result = await bridge.sendRawPacket( - 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList', - body, - 15000 - ); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'failed to get album media list'); - } - - const resp = protobuf_decode(result.responseData); - - if (resp.field1 !== 0) { - throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`); - } - - const data = resp.data ?? {}; - const mediaList = data.mediaList ?? []; - const nextAttachInfo = data.nextAttachInfo ?? ''; - - return convertBigIntToString({ - mediaList, - nextAttachInfo, - }); -} - - - -export async function commentGroupAlbumMedia( - bridge: Bridge, - groupId: number, - albumId: string, - lloc: string, - content: string -): Promise { - const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - const clientKey = Date.now().toString(); - const uin = bridge.identity.uin; - - const body = protobuf_encode({ - field1: 8527, - field2: new Uint8Array(0), - field3: new Uint8Array(0), - body: { - groupId: groupId.toString(), - field3: 2, - reqBody: { - field1: { field3: 0, field4: "" }, - field2: { - field1: { uin } - }, - field5: { - field1: { - field2: { - field1: 0, field2: "", - lloc, - field4: "", field6: "", field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0 - } - }, - albumId, - field5: 0 - }, - }, - field5: { - field2: { uin }, - field3: { - field1: 0, - field2: content, - field3: "", field4: "", field5: 0, field6: "" - }, - clientKey, - } - }, - traceId, - extMap: [{ key: 'fc-appid', value: '100' }], - }); - - const result = await bridge.sendRawPacket( - 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment', - body, - 15000 - ); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'failed to comment on album media'); - } - - const resp = protobuf_decode(result.responseData); - - const resCode = resp.field1; - if (resCode !== 0 && resCode !== 8527 && !resp.comment) { - throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`); - } - - const commentData = resp.comment?.data ?? {}; - - return convertBigIntToString({ - id: commentData.id ?? '', - user: { uin: commentData.user?.uin ?? '' }, - content: commentData.content ?? [], - time: commentData.time ?? '0', - clientKey: commentData.clientKey ?? '', - }); -} - -export async function likeGroupAlbumMedia( - bridge: Bridge, - groupId: number, - albumId: string, - batchId: string, - lloc: string | undefined, - isLike: boolean -): Promise { - const uin = bridge.identity.uin; - const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - - const type = isLike ? 2 : 1; - const status = isLike ? 0 : 1; - - let id = ''; - if (lloc) { - id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`; - } else { - id = `421_1_0_${groupId}|${albumId}|${batchId}`; - } - - const body = protobuf_encode({ - field1: 5495, - field2: "h5_test", - field3: "h5_test", - body: { - type, - like: { id, status }, - publish: { - cellCommon: { - time: BigInt(Date.now()), - feedId: `422_0_${batchId}` - }, - cellUserInfo: { - user: { uin } - }, - cellMedia: { - albumId: albumId, - batchId: BigInt(batchId) - }, - cellQunInfo: { - qunId: groupId.toString() - } - }, - clientKey - }, - extMap: [{ key: 'fc-appid', value: '100' }], - }); - - const result = await bridge.sendRawPacket( - 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike', - body, - 15000 - ); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'failed to like album media'); - } - - const resp = protobuf_decode(result.responseData); - const resCode = resp.field1; - - if (resCode !== 5495) { - throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`); - } - - return convertBigIntToString(resp.body?.like ?? {}); -} - -export async function deleteGroupAlbumMedia( - bridge: Bridge, - groupId: number, - albumId: string, - lloc: string -): Promise { - const uin = bridge.identity.uin; - const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - - const body = protobuf_encode({ - field1: 8694, - field2: "h5_test", - field3: "h5_test", - body: { - groupId: groupId.toString(), - albumId: albumId, - lloc: lloc, - }, - traceId: clientKey, - extMap: [{ key: 'fc-appid', value: '100' }], - }); - - const result = await bridge.sendRawPacket( - 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias', - body, - 15000 - ); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'failed to delete album media'); - } - - const resp = protobuf_decode(result.responseData); - const resCode = resp.field1; - const errCode = resp.field2; - const errMsg = resp.field3; - - if (resCode !== 8694 || errCode) { - throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`); - } - - return { success: true }; -} - diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts deleted file mode 100644 index 4d3aab82..00000000 --- a/packages/core/src/bridge/actions/group-file.ts +++ /dev/null @@ -1,983 +0,0 @@ -// Group + private file operations: upload (with highway fast-path), -// folder management, file listing, file/media URL fetch. All upload -// paths share the same shape (resolve target → OIDB metadata exchange -// → highway HTTP PUT if the server says we must), but the OIDB schemas -// and field layouts differ enough between group and private that they -// stay as separate functions. - -import type { Bridge } from '../bridge'; -import { protobuf_encode } from '@snowluma/proton'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; -import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; -import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils'; -import type { - OidbGroupFileCountViewReq, - OidbGroupFileCountViewResp, - OidbGroupFileFolderReq, - OidbGroupFileFolderResp, - OidbGroupFileReq, - OidbGroupFileResp, - OidbGroupFileViewReq, - OidbGroupFileViewResp, - OidbGroupSendFileReq, - OidbPrivateFileDownloadReq, - OidbPrivateFileDownloadResp, - OidbPrivateFileUploadReq, - OidbPrivateFileUploadResp, - NTV2RichMediaReq, - NTV2RichMediaResp, -} from '../proto/proton/oidb-action'; -import type { FileUploadExt } from '../proto/proton/highway'; -import { toHexUpper } from '../../utils/hex'; -import { createLogger } from '../../utils/logger'; -import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared'; - -const log = createLogger('GroupFile'); - -// ─────────────── public result types ─────────────── - -export interface GroupFileInfo { - fileId: string; - fileName: string; - busId: number; - fileSize: number; - uploadTime: number; - deadTime: number; - modifyTime: number; - downloadTimes: number; - uploader: number; - uploaderName: string; -} - -export interface GroupFolderInfo { - folderId: string; - folderName: string; - createTime: number; - creator: number; - creatorName: string; - totalFileCount: number; -} - -export interface GroupFilesResult { - files: GroupFileInfo[]; - folders: GroupFolderInfo[]; -} - -export interface UploadFileResult { - fileId: string | null; - fileHash?: string | null; -} - -// Re-export so this file is a one-stop-shop for the file API surface -// (bridge.ts imports MediaIndexNode through here for type symmetry). -export type { MediaIndexNode } from './shared'; - -// ─────────────── file-specific helpers ─────────────── - -function normalizeDirectory(dir?: string): string { - if (!dir || !dir.trim()) return '/'; - return dir; -} - -function bytesToHexUpper(data: unknown): string { - if (!(data instanceof Uint8Array) || data.length === 0) return ''; - return toHexUpper(data); -} - -// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives -// little-endian-packed (byte0 = first dotted octet) and we unpack it the -// same way. Force-unsigned the shift to keep negative ints (high bit set) -// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000 -// into a negative number. -function int32ToIpv4Dotted(value: number): string { - const b1 = value & 0xFF; - const b2 = (value >>> 8) & 0xFF; - const b3 = (value >>> 16) & 0xFF; - const b4 = (value >>> 24) & 0xFF; - return `${b1}.${b2}.${b3}.${b4}`; -} - -function normalizeUploadFileName(name: string, fallback: string): string { - const trimmed = name.trim(); - if (trimmed) return trimmed; - const safeFallback = fallback.trim(); - return safeFallback || 'file.bin'; -} - -function md5First10MB(bytes: Uint8Array): Uint8Array { - const limit = Math.min(bytes.length, 10 * 1024 * 1024); - return computeMd5(bytes.subarray(0, limit)); -} - -function buildGroupFileUploadExt( - senderUin: number, - groupId: number, - fileName: string, - fileSize: number, - md5: Uint8Array, - fileId: string, - uploadKey: Uint8Array, - checkKey: Uint8Array, - uploadHost: string, - uploadPort: number, -): Uint8Array { - return protobuf_encode({ - unknown1: 100, - unknown2: 1, - entry: { - busiBuff: { - busId: 102, - senderUin: BigInt(senderUin), - receiverUin: BigInt(groupId), - groupCode: BigInt(groupId), - }, - fileEntry: { - fileSize: BigInt(Math.max(0, fileSize)), - md5, - md5S2: md5, - checkKey, - fileId, - uploadKey, - }, - clientInfo: { - clientType: 3, - appId: '100', - terminalType: 3, - clientVer: '1.1.1', - unknown: 4, - }, - fileNameInfo: { - fileName, - }, - host: { - hosts: [ - { - url: { - host: uploadHost, - unknown: 1, - }, - port: uploadPort, - }, - ], - }, - }, - unknown200: 0, - }); -} - -function buildPrivateFileUploadExt( - senderUin: number, - fileName: string, - fileSize: number, - md5: Uint8Array, - sha1: Uint8Array, - fileId: string, - uploadKey: Uint8Array, - uploadHost: string, - uploadPort: number, -): Uint8Array { - return protobuf_encode({ - unknown1: 100, - unknown2: 1, - entry: { - busiBuff: { - busId: 102, - senderUin: BigInt(senderUin), - receiverUin: 0n, - groupCode: 0n, - }, - fileEntry: { - fileSize: BigInt(Math.max(0, fileSize)), - md5, - md5S2: md5, - checkKey: sha1, - fileId, - uploadKey, - }, - clientInfo: { - clientType: 3, - appId: '100', - terminalType: 3, - clientVer: '1.1.1', - unknown: 4, - }, - fileNameInfo: { - fileName, - }, - host: { - hosts: [ - { - url: { - host: uploadHost, - unknown: 1, - }, - port: uploadPort, - }, - ], - }, - }, - unknown3: 0, - unknown200: 1, - }); -} - -function normalizeMediaNode(node: MediaIndexNode): Record { - const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : ''; - if (!fileUuid) throw new Error('media node fileUuid is required'); - - const info = node.info ?? {}; - const type = info.type ?? {}; - - return { - info: { - fileSize: toInt(info.fileSize), - fileHash: typeof info.fileHash === 'string' ? info.fileHash : '', - fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '', - fileName: typeof info.fileName === 'string' ? info.fileName : '', - type: { - type: toInt(type.type), - picFormat: toInt(type.picFormat), - videoFormat: toInt(type.videoFormat), - voiceFormat: toInt(type.voiceFormat), - }, - width: toInt(info.width), - height: toInt(info.height), - time: toInt(info.time), - original: toInt(info.original), - }, - fileUuid, - storeId: toInt(node.storeId), - uploadTime: toInt(node.uploadTime), - ttl: toInt(node.ttl), - subType: toInt(node.subType), - }; -} - -async function fetchNtv2DownloadUrl( - bridge: Bridge, - serviceCmd: string, - oidbCmd: number, - payload: Record, -): Promise { - const env = makeOidbEnvelope(oidbCmd, 200, payload as any, true); - const respBytes = await runOidb(bridge, serviceCmd, encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined); - const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : ''; - const path = typeof resp?.download?.info?.urlPath === 'string' ? resp.download.info.urlPath : ''; - const rKeyParam = typeof resp?.download?.rKeyParam === 'string' ? resp.download.rKeyParam : ''; - - if (!domain || !path) { - throw new Error('ntv2 download response invalid'); - } - return `https://${domain}${path}${rKeyParam}`; -} - -// ─────────────── publish (group file → chat) ─────────────── - -/** - * Publish a previously-uploaded group file as a chat message. - * - * Wire is OIDB `OidbSvcTrpcTcp.0x6d9_4` — NOT `MessageSvc.PbSendMsg`. - * Lagrange.Core V2 splits these two roles: the file UPLOAD path goes - * via 0x6D6_0 + highway PUT, then a SECOND OIDB hop (this one) tells - * the QQ server "now publish that staged blob as a chat message" so - * everyone in the group can see the file bubble. - * - * The old approach — wrap the file as `TransElem(elemType=24)` inside - * `richText.elems[]` and ship it via PbSendMsg — works for INCOMING - * messages (the receive decoder unpacks transElem(24) into a - * FileEntity) but the QQ-NT server REJECTS it on outgoing with - * `result=79` ("invalid element on send-side"). Mirror Lagrange's - * dedicated GroupSendFileService instead. - * - * The unused `field4` slot and the `field3=random` value match - * Lagrange's send-side defaults (`OidbSvcTrpcTcp0x6D9_4.cs` + the - * `Random.Shared.Next()` call in `GroupSendFileService.cs`). Field 5 - * is the `Field5=true` flag the receiver's deserializer expects. - */ -export async function sendGroupFileMessage(bridge: Bridge, groupId: number, fileId: string): Promise { - if (!fileId) throw new Error('sendGroupFileMessage requires fileId'); - const env = makeOidbEnvelope(0x6D9, 4, { - body: { - groupUin: groupId, - type: 2, - info: { - busiType: 102, - fileId, - field3: Math.floor(Math.random() * 0x7fffffff) >>> 0, - field5: true, - }, - }, - }); - // The envelope-level errorCode peek inside `runOidb` covers the - // happy-path validation; failures surface as a thrown OIDB error. - await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d9_4', encodeOidbEnv(env)); -} - -// ─────────────── file count ─────────────── - -export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> { - const env = makeOidbEnvelope( - 0x6D8, 3, - { count: { groupUin: groupId, appId: 7, busId: 0 } }, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - return { - fileCount: toInt(resp?.count?.fileCount ?? 0), - maxCount: toInt(resp?.count?.maxCount ?? 10000), - }; -} - -// ─────────────── upload ─────────────── - -export async function uploadGroupFile( - bridge: Bridge, - groupId: number, - source: string, - name = '', - folderId = '/', - uploadFile = true, -): Promise { - // Group/private files may legitimately be up to 4 GiB on QQ's wire, - // so override the default 1 GiB cap with the protocol ceiling. - const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); - if (!loaded.bytes.length) throw new Error('group file is empty'); - - const fileName = normalizeUploadFileName(name, loaded.fileName); - const hashes = computeHashes(loaded.bytes); - - const env = makeOidbEnvelope( - 0x6D6, 0, - { - file: { - groupUin: groupId, - appId: 4, - busId: 102, - entrance: 6, - targetDirectory: normalizeDirectory(folderId), - fileName, - localDirectory: `/${fileName}`, - fileSize: BigInt(loaded.bytes.length), - fileSha1: hashes.sha1, - fileSha3: new Uint8Array(0), - fileMd5: hashes.md5, - field15: true, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const upload = resp?.upload; - if (!upload) throw new Error('group file upload response missing'); - ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording); - - const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null; - if (!fileId) throw new Error('group file upload response missing file_id'); - - // Remember the upload so a later `send_group_msg` carrying just the - // file_id can route via `sendGroupFileMessage` without forcing the - // OneBot caller to thread fileName/size/md5 separately. For groups - // the wire publish (OIDB 0x6d9_4) only needs the file_id itself, so - // this is mainly for log-line correctness; the c2c counterpart in - // `uploadPrivateFile` is where the cache is actually load-bearing. - bridge.rememberUploadedFile({ - fileId, - scope: 'group', - groupId, - fileName, - fileSize: loaded.bytes.length, - fileMd5: hashes.md5, - fileSha1: hashes.sha1, - rememberedAt: Date.now(), - }); - - if (!upload.boolFileExist && uploadFile) { - const senderUin = toInt(bridge.identity.uin); - if (senderUin <= 0) throw new Error('invalid self uin for group file upload'); - - const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp) - || (typeof upload.serverDns === 'string' && upload.serverDns) - || ''; - const uploadPort = toInt(upload.uploadPort); - if (!uploadHost || uploadPort <= 0) { - throw new Error('group file upload host is invalid'); - } - - const ext = buildGroupFileUploadExt( - senderUin, - groupId, - fileName, - loaded.bytes.length, - hashes.md5, - fileId, - upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0), - upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0), - uploadHost, - uploadPort, - ); - - const session = await fetchHighwaySession(bridge); - await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext); - } - - // Stage 3: file is on the server, now publish it as a chat message. - // - // Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes — - // the chat shows nothing. The publish step goes via a dedicated OIDB - // call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24) - // payload — the QQ-NT server rejects that with `result=79`. Mirrors - // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the - // caller opts out via `uploadFile=false` (treat that as "I only - // wanted the slot allocated, hold the chat post"). Routes through - // the public bridge method (rather than the local `sendGroupFileMessage`) - // so tests can mock at the bridge boundary, matching the pattern - // `uploadPrivateFile` uses with `bridge.sendC2cFileMessage`. - if (uploadFile) { - try { - await bridge.sendGroupFileMessage(groupId, fileId); - } catch (err) { - // The bytes are already on the server and the fileId is valid — - // fail loud but don't lose the upload result the action handler - // committed to returning. Callers can still resolve the file by - // id; they'll just have to re-publish it themselves. - log.warn('group file uploaded (fileId=%s) but chat post failed: %s', - fileId, err instanceof Error ? err.message : String(err)); - } - } - - return { fileId }; -} - -export async function uploadPrivateFile( - bridge: Bridge, - userId: number, - source: string, - name = '', - uploadFile = true, -): Promise { - // Group/private files may legitimately be up to 4 GiB on QQ's wire, - // so override the default 1 GiB cap with the protocol ceiling. - const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); - if (!loaded.bytes.length) throw new Error('private file is empty'); - - const targetUid = await bridge.resolveUserUid(userId); - let selfUid = bridge.identity.selfUid; - if (!selfUid) { - const selfUin = toInt(bridge.identity.uin); - if (selfUin > 0) { - selfUid = await bridge.resolveUserUid(selfUin); - } - } - if (!selfUid) throw new Error('self uid is unavailable'); - - const senderUin = toInt(bridge.identity.uin); - if (senderUin <= 0) throw new Error('invalid self uin for private file upload'); - - const fileName = normalizeUploadFileName(name, loaded.fileName); - const hashes = computeHashes(loaded.bytes); - - const env = makeOidbEnvelope(0xE37, 1700, { - command: 1700, - seq: 0, - upload: { - senderUid: selfUid, - receiverUid: targetUid, - fileSize: loaded.bytes.length, - fileName, - md510MCheckSum: md5First10MB(loaded.bytes), - sha1CheckSum: hashes.sha1, - localPath: '/', - md5CheckSum: hashes.md5, - sha3CheckSum: new Uint8Array(0), - }, - businessId: 3, - clientType: 1, - flagSupportMediaPlatform: 1, - }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const upload = resp?.upload; - if (!upload) throw new Error('private file upload response missing'); - ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined); - - const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null; - const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null; - if (!fileId) throw new Error('private file upload response missing file_id'); - - // Cache the metadata so a later `send_private_msg` carrying just - // `{type:'file', file_id}` can resurrect the full c2c-file packet - // (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without - // this the recipient sees a 0-byte file because the OneBot send path - // has no way to recover those fields from the file_id alone. - bridge.rememberUploadedFile({ - fileId, - scope: 'private', - userId, - fileName, - fileSize: loaded.bytes.length, - fileMd5: hashes.md5, - fileSha1: hashes.sha1, - fileHash: fileHash ?? '', - rememberedAt: Date.now(), - }); - - if (!upload.boolFileExist && uploadFile) { - // Host selection. - // - // Current QQ-NT server rollout has stopped populating the legacy - // `uploadIp` (field 60) entirely. The host now arrives as the first - // entry of `rtpMediaPlatformUploadAddress` (field 210, repeated - // IPv4 message) — same place acidify reads it from since their - // 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort` - // (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN); - // acidify uses `inIP`/`inPort` exclusively and so do we, because - // that's the address the highway PUT actually needs to reach. - // - // The 32-bit IPs are little-endian-packed (byte0 = first octet) - // per acidify's `Int.toIpString()`. Cross-checked the byte order - // by inspecting their highway flow — there's no separate htonl - // step, so the integer is already in network-octet-first order. - // - // Older server versions still populate the legacy string fields - // (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain / - // uploadDns), so we fall through to those after rtpMediaPlatform. - // Pair an HTTPS-flavored host with `uploadHttpsPort` if that's - // what we picked. - const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress) - && upload.rtpMediaPlatformUploadAddress[0]) - ? upload.rtpMediaPlatformUploadAddress[0] : null; - const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0 - ? int32ToIpv4Dotted(rtpFirst.inIP) : ''; - const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number' - ? rtpFirst.inPort : 0; - const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0]) - ? upload.uploadIpList[0] : ''; - const uploadHost = (rtpInIP) - || (typeof upload.uploadIp === 'string' && upload.uploadIp) - || (typeof upload.uploadDomain === 'string' && upload.uploadDomain) - || (ipListFirst) - || (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain) - || (typeof upload.uploadDns === 'string' && upload.uploadDns) - || ''; - const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst - && typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain; - const uploadPort = rtpInIP && rtpInPort > 0 - ? rtpInPort - : httpsHostUsed && toInt(upload.uploadHttpsPort) > 0 - ? toInt(upload.uploadHttpsPort) - : toInt(upload.uploadPort); - if (!uploadHost || uploadPort <= 0) { - // Surface every host-bearing field we know about so a user - // hitting this can show us exactly which slot the server filled - // (or whether it returned nothing at all — which would point at - // a request mismatch rather than a missing decoder). - const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress) - ? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({ - outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort, - iPType: e.iPType, - }))) - : '[]'; - log.warn( - 'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s', - rtpDump, - upload.uploadIp ?? '', upload.uploadDomain ?? '', - JSON.stringify(upload.uploadIpList ?? []), - upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '', - upload.uploadLanip ?? '', upload.uploadPort ?? 0, - upload.uploadHttpsPort ?? 0, - ); - throw new Error('private file upload host is invalid'); - } - - const ext = buildPrivateFileUploadExt( - senderUin, - fileName, - loaded.bytes.length, - hashes.md5, - hashes.sha1, - fileId, - upload.mediaPlatformUploadKey instanceof Uint8Array - ? upload.mediaPlatformUploadKey - : (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)), - uploadHost, - uploadPort, - ); - - const session = await fetchHighwaySession(bridge); - await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext); - } - - // Stage 3: publish the file as a c2c chat message. C2C files use - // `RichText.notOnlineFile` (parallel to `elems`), so we go through - // the dedicated `sendC2cFileMessage` instead of `sendPrivateMessage` - // which only knows about elems[]. NapCat does the same atomic - // upload+send dance — without it the file sits on the server and - // the recipient sees nothing. - if (uploadFile) { - try { - await bridge.sendC2cFileMessage(userId, targetUid, { - fileId, - fileName, - fileSize: loaded.bytes.length, - fileMd5: hashes.md5, - fileHash: fileHash ?? '', - }); - } catch (err) { - log.warn('private file uploaded (fileId=%s) but chat post failed: %s', - fileId, err instanceof Error ? err.message : String(err)); - } - } - - return { fileId, fileHash }; -} - -// ─────────────── list ─────────────── - -export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId = '/'): Promise { - const targetDirectory = normalizeDirectory(folderId); - const files: GroupFileInfo[] = []; - const folders: GroupFolderInfo[] = []; - - const pageSize = 20; - let startIndex = 0; - for (let page = 0; page < 200; page++) { - const env = makeOidbEnvelope( - 0x6D8, 1, - { - list: { - groupUin: groupId, - appId: 7, - targetDirectory, - fileCount: pageSize, - sortBy: 1, - startIndex, - field17: 2, - field18: 0, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_1', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const list = resp?.list; - if (!list) break; - ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording); - - for (const item of list.items ?? []) { - const type = toInt(item?.type); - if (type === 1 && item?.fileInfo) { - const file = item.fileInfo; - const uploader = toInt(file.uploaderUin); - const cached = bridge.identity.findGroupMember(groupId, uploader); - files.push({ - fileId: typeof file.fileId === 'string' ? file.fileId : '', - fileName: typeof file.fileName === 'string' ? file.fileName : '', - busId: toInt(file.busId), - fileSize: toInt(file.fileSize), - uploadTime: toInt(file.uploadedTime), - deadTime: toInt(file.expireTime), - modifyTime: toInt(file.modifiedTime), - downloadTimes: toInt(file.downloadedTimes), - uploader, - uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName) - || cached?.card - || cached?.nickname - || '', - }); - } else if (type === 2 && item?.folderInfo) { - const folder = item.folderInfo; - const creator = toInt(folder.creatorUin); - const cached = bridge.identity.findGroupMember(groupId, creator); - folders.push({ - folderId: typeof folder.folderId === 'string' ? folder.folderId : '', - folderName: typeof folder.folderName === 'string' ? folder.folderName : '', - createTime: toInt(folder.createTime), - creator, - creatorName: (typeof folder.creatorName === 'string' && folder.creatorName) - || cached?.card - || cached?.nickname - || '', - totalFileCount: toInt(folder.totalFileCount), - }); - } - } - - if (list.isEnd) break; - startIndex += pageSize; - } - - return { files, folders }; -} - -// ─────────────── url fetch (group / private files) ─────────────── - -export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise { - const env = makeOidbEnvelope( - 0x6D6, 2, - { - download: { - groupUin: groupId, - appId: 7, - busId, - fileId, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const download = resp?.download; - if (!download) throw new Error('group file url response missing'); - ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording); - - const dns = (typeof download.downloadDns === 'string' && download.downloadDns) - || (typeof download.downloadIp === 'string' && download.downloadIp) - || ''; - const hexUrl = bytesToHexUpper(download.downloadUrl); - if (!dns || !hexUrl) { - throw new Error('group file url response invalid'); - } - - // Keep the same behavior as Lagrange: append file_id after ?fname= - return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`; -} - -export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise { - const uid = await bridge.resolveUserUid(userId); - const env = makeOidbEnvelope(0xE37, 1200, { - subCommand: 1200, - field2: 1, - body: { - receiverUid: uid, - fileUuid: fileId, - type: 2, - fileHash, - t2: 0, - }, - field101: 3, - field102: 103, - field200: 1, - field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), - }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1200', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const result = resp?.body?.result; - const server = typeof result?.server === 'string' ? result.server : ''; - const port = toInt(result?.port); - const url = typeof result?.url === 'string' ? result.url : ''; - if (!server || !port || !url) { - throw new Error('private file url response invalid'); - } - return `http://${server}:${port}${url}&isthumb=0`; -} - -// ─────────────── delete / move ─────────────── - -export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise { - const env = makeOidbEnvelope( - 0x6D6, 3, - { - delete: { - groupUin: groupId, - busId: 102, - fileId, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const result = resp?.delete; - if (!result) throw new Error('group file delete response missing'); - ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording); -} - -export async function moveGroupFile( - bridge: Bridge, - groupId: number, - fileId: string, - parentDirectory: string, - targetDirectory: string, -): Promise { - const env = makeOidbEnvelope( - 0x6D6, 5, - { - move: { - groupUin: groupId, - appId: 7, - busId: 102, - fileId, - parentDirectory, - targetDirectory, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const result = resp?.move; - if (!result) throw new Error('group file move response missing'); - ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording); -} - -// ─────────────── folders ─────────────── - -export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise { - const env = makeOidbEnvelope( - 0x6D7, 0, - { - create: { - groupUin: groupId, - rootDirectory: normalizeDirectory(parentId), - folderName: name, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const result = resp?.create; - if (!result) throw new Error('group folder create response missing'); - ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording); -} - -export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise { - const env = makeOidbEnvelope( - 0x6D7, 1, - { - delete: { - groupUin: groupId, - folderId, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const result = resp?.delete; - if (!result) throw new Error('group folder delete response missing'); - ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording); -} - -export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise { - const env = makeOidbEnvelope( - 0x6D7, 2, - { - rename: { - groupUin: groupId, - folderId, - newFolderName, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const result = resp?.rename; - if (!result) throw new Error('group folder rename response missing'); - ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording); -} - -// ─────────────── rich-media URL by node ─────────────── - -export async function fetchGroupPttUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise { - const normalizedNode = normalizeMediaNode(node); - return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, { - reqHead: { - common: { requestId: 4, command: 200 }, - scene: { - requestType: 1, - businessType: 3, - sceneType: 2, - group: { groupUin: groupId }, - }, - client: { agentType: 2 }, - }, - download: { - node: normalizedNode, - download: { video: { busiType: 0, sceneType: 0 } }, - }, - }); -} - -export async function fetchPrivatePttUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise { - const selfUid = await resolveSelfUid(bridge); - const normalizedNode = normalizeMediaNode(node); - return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, { - reqHead: { - common: { requestId: 1, command: 200 }, - scene: { - requestType: 1, - businessType: 3, - sceneType: 1, - c2c: { - accountType: 2, - targetUid: selfUid, - }, - }, - client: { agentType: 2 }, - }, - download: { - node: normalizedNode, - download: { video: { busiType: 0, sceneType: 0 } }, - }, - }); -} - -export async function fetchGroupVideoUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise { - const normalizedNode = normalizeMediaNode(node); - return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, { - reqHead: { - common: { requestId: 1, command: 200 }, - scene: { - requestType: 2, - businessType: 2, - sceneType: 2, - group: { groupUin: groupId }, - }, - client: { agentType: 2 }, - }, - download: { - node: normalizedNode, - download: { video: { busiType: 0, sceneType: 0 } }, - }, - }); -} - -export async function fetchPrivateVideoUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise { - const selfUid = await resolveSelfUid(bridge); - const normalizedNode = normalizeMediaNode(node); - return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, { - reqHead: { - common: { requestId: 1, command: 200 }, - scene: { - requestType: 2, - businessType: 2, - sceneType: 1, - c2c: { - accountType: 2, - targetUid: selfUid, - }, - }, - client: { agentType: 2 }, - }, - download: { - node: normalizedNode, - download: { video: { busiType: 0, sceneType: 0 } }, - }, - }); -} diff --git a/packages/core/src/bridge/actions/group-message.ts b/packages/core/src/bridge/actions/group-message.ts deleted file mode 100644 index 13da8dc2..00000000 --- a/packages/core/src/bridge/actions/group-message.ts +++ /dev/null @@ -1,101 +0,0 @@ -// Operations targeting an existing message: recall (group / private), -// mark-as-read (group / private), and the "essence" highlight toggle. -// All of these take a message identifier and modify server-side state -// without producing a downstream observable event. - -import type { Bridge } from '../bridge'; -import { protoEncode } from '../../protobuf/decode'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb'; -import { - C2CRecallRequestSchema, - GroupRecallRequestSchema, - SsoReadedReportReqSchema, -} from '../proto/oidb-action'; -import type { OidbEssence } from '../proto/proton/oidb-action'; - -export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise { - const request = protoEncode({ - type: 1, - groupUin: groupId, - info: { sequence, random: 0, field3: 0 }, - settings: { field1: 0 }, - }, GroupRecallRequestSchema); - const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request); - if (!result.success) throw new Error(result.errorMessage || 'recall group message failed'); -} - -export async function recallPrivateMessage( - bridge: Bridge, userUin: number, clientSeq: number, - msgSeq: number, random: number, timestamp: number, -): Promise { - const targetUid = await bridge.resolveUserUid(userUin); - const request = protoEncode({ - type: 1, - targetUid, - info: { - clientSequence: clientSeq, - random, - messageId: BigInt((0x01000000 * 0x100000000) + random), - timestamp, - field5: 0, - messageSequence: msgSeq, - }, - settings: { field1: false, field2: false }, - field6: false, - }, C2CRecallRequestSchema); - const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request); - if (!result.success) throw new Error(result.errorMessage || 'recall private message failed'); -} - -export async function markPrivateMessageRead( - bridge: Bridge, - userId: number, - msgSeq: number, - timestamp: number = Math.floor(Date.now() / 1000), -): Promise { - const uid = await bridge.resolveUserUid(userId); - - const request = protoEncode({ - c2cList: [ - { - uid, - lastReadTime: BigInt(timestamp), - lastReadSeq: BigInt(msgSeq), - }, - ], - }, SsoReadedReportReqSchema); - - const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request); - - if (!result.success) { - throw new Error(result.errorMessage || 'mark private message read failed'); - } -} - -export async function markGroupMessageRead( - bridge: Bridge, - groupId: number, - msgSeq: number, -): Promise { - const request = protoEncode({ - groupList: [ - { - groupUin: BigInt(groupId), - lastReadSeq: BigInt(msgSeq), - }, - ], - }, SsoReadedReportReqSchema); - - const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request); - - if (!result.success) { - throw new Error(result.errorMessage || 'mark group message read failed'); - } -} - -export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise { - const subCmd = enable ? 1 : 2; - const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2'; - const env = makeOidbEnvelope(0xEAC, subCmd, { groupUin: groupId, sequence, random }); - await runOidb(bridge, cmd, encodeOidbEnv(env)); -} diff --git a/packages/core/src/bridge/actions/interaction.ts b/packages/core/src/bridge/actions/interaction.ts deleted file mode 100644 index 17279e00..00000000 --- a/packages/core/src/bridge/actions/interaction.ts +++ /dev/null @@ -1,68 +0,0 @@ -// Lightweight social-interaction actions: poke, like, emoji reaction, -// and the related read-side "who reacted with X" query. None of these -// edit message content — they're purely social signals. - -import type { Bridge } from '../bridge'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; -import type { - Oidb0x9083Req, - Oidb0x9083Resp, - OidbGroupReaction, - OidbLike, - OidbPoke, -} from '../proto/proton/oidb-action'; - -export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise { - const env = makeOidbEnvelope(0xED3, 1, { - uin: targetUin ?? peerUin, - groupUin: isGroup ? peerUin : 0, - friendUin: isGroup ? 0 : peerUin, - ext: 0, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xed3_1', encodeOidbEnv(env)); -} - -export async function sendLike(bridge: Bridge, userId: number, count: number): Promise { - const env = makeOidbEnvelope(0x7E5, 104, { targetUin: userId, count }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x7e5_104', encodeOidbEnv(env)); -} - -export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise { - const subCmd = isSet ? 1 : 2; - const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2'; - // Same heuristic NapCat uses: QQ face ids are 1–3 digits ("76"), - // unicode codepoints are longer ("128516"). Server requires the - // type field to pick the right resolution table; omitting it makes - // unicode reactions silently fail. - const type = code.length > 3 ? 2 : 1; - const env = makeOidbEnvelope(0x9082, subCmd, { groupUin: groupId, sequence, code, type }); - await runOidb(bridge, cmd, encodeOidbEnv(env)); -} - -export async function getEmojiLikes( - bridge: Bridge, - groupId: number, - sequence: number, - emojiId: string, - emojiType: number = 1, - count: number = 10, - cookie: string = '', -): Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }> { - const req: any = { - groupId: BigInt(groupId), - sequence, - emojiType, - emojiId, - cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0), - field7: 0, - count, - field12: 1, - }; - const env = makeOidbEnvelope(0x9083, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - const uin = resp?.inner?.userInfo?.uin; - const users = uin ? [{ uin: Number(uin) }] : []; - const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : ''; - return { users, cookie: respCookie, isLast: !respCookie }; -} diff --git a/packages/core/src/bridge/actions/misc.ts b/packages/core/src/bridge/actions/misc.ts deleted file mode 100644 index b3b06f98..00000000 --- a/packages/core/src/bridge/actions/misc.ts +++ /dev/null @@ -1,158 +0,0 @@ -// Grab-bag: action verbs that don't share a theme with anything else. -// Kept together so the directory stays small; if any of these grow new -// related siblings, lift the whole group out into its own file. - -import type { Bridge } from '../bridge'; -import { protoDecode, protoEncode } from '../../protobuf/decode'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; -import { - MiniAppShareReqSchema, - MiniAppShareRespSchema, -} from '../proto/oidb-action'; -import type { - Oidb0x112eReq, - Oidb0x112eResp, - Oidb0x990Req, - Oidb0x990Resp, - Oidb0xeb7Req, - Oidb0xeb7Resp, -} from '../proto/proton/oidb-action'; - -export async function translateEn2Zh( - bridge: Bridge, - words: string[], -) { - const req = { - translateReq: { - srcLang: 'en', - dstLang: 'zh', - words: words, - }, - tag10: 1, - tag12: 1, - }; - - const env = makeOidbEnvelope(0x990, 2, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x990_2', encodeOidbEnv(env)); - const result = decodeOidbEnv(respBytes).body; - - const resp = result?.translateResp; - if (!resp) { - throw new Error('translate response empty'); - } - - return resp.dstWords || []; -} - -export async function getMiniAppArk( - bridge: Bridge, - type: string, - title: string, - desc: string, - picUrl: string, - jumpUrl: string, -) { - let appid = '1109937557'; // default: bilibili - let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg'; - - if (type === 'weibo') { - appid = '1109224783'; - iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg'; - } else if (type !== 'bili') { - throw new Error(`unsupported type: ${type}, only support bili and weibo`); - } - - const request = protoEncode({ - sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A', - body: { - appid, - title, - desc, - picUrl, - jumpUrl, - iconUrl, - }, - }, MiniAppShareReqSchema); - - const result = await bridge.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request); - - if (!result.success || !result.responseData) { - throw new Error(result.errorMessage || 'get mini app ark failed'); - } - - const decoded = protoDecode(result.responseData, MiniAppShareRespSchema); - const jsonStr = decoded?.body?.jsonStr; - - if (!jsonStr) { - throw new Error('mini app share json empty'); - } - - const parsed = JSON.parse(jsonStr); - - return { - data: { - ver: parsed.ver, - prompt: parsed.prompt, - config: parsed.config, - app: parsed.appName, - view: parsed.appView, - meta: parsed.metaData, - miniappShareOrigin: 3, - miniappOpenRefer: '10002', - }, - }; -} - -export async function clickInlineKeyboardButton( - bridge: Bridge, - groupId: number, - botAppid: number, - buttonId: string, - callbackData: string, - msgSeq: number, -) { - const req = { - botAppid: BigInt(botAppid), - msgSeq: BigInt(msgSeq), - buttonId: String(buttonId), - callbackData: String(callbackData || ''), - unknown7: 0, - groupId: BigInt(groupId), - unknown9: 1, - }; - - const env = makeOidbEnvelope(0x112E, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112e_1', encodeOidbEnv(env)); - const result = decodeOidbEnv(respBytes).body; - - if (!result) { - throw new Error('click inline keyboard button result empty'); - } - - return { - result: Number(result.result || 0), - errMsg: result.errMsg || '', - status: 0, - promptText: result.promptText || '', - promptType: 0, - promptIcon: 0, - }; -} - -export async function sendGroupSign( - bridge: Bridge, - groupId: number, -) { - const req = { - signInInfo: { - uin: String(bridge.identity.uin), - groupId: String(groupId), - version: '9.0.90', - }, - }; - - const env = makeOidbEnvelope(0xEB7, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xEB7_1', encodeOidbEnv(env)); - // Decode just to maintain the original behaviour of "consume the response". - decodeOidbEnv(respBytes); -} diff --git a/packages/core/src/bridge/actions/profile.ts b/packages/core/src/bridge/actions/profile.ts deleted file mode 100644 index b0284428..00000000 --- a/packages/core/src/bridge/actions/profile.ts +++ /dev/null @@ -1,302 +0,0 @@ -// Operations that touch the bot's own profile / status, plus the -// related queries about my profile likes and unidirectional friends. -// All of these read/write fields on the self-uin via OIDB. - -import type { Bridge } from '../bridge'; -import { protoDecode, protoEncode } from '../../protobuf/decode'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; -import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; -import { computeHashes, loadBinarySource } from '../highway/utils'; -import { - FaceroamOpReqSchema, - FaceroamOpRespSchema, - GroupAvatarExtraSchema, - SetStatusReqSchema, - SetStatusRespSchema, -} from '../proto/oidb-action'; -import type { - Oidb0x112aReq, - Oidb0x112aResp, - Oidb0x7edReq, - Oidb0x7edResp, - Oidb0xcd4Req, - Oidb0xcd4Resp, - Oidb0xe17Req, - Oidb0xe17Resp, - OidbSetProfile, -} from '../proto/proton/oidb-action'; -import { resolveSelfUid } from './shared'; - -// ─────────────── status / profile setters ─────────────── - -export async function setOnlineStatus( - bridge: Bridge, - status: number, - extStatus: number = 0, - batteryStatus: number = 100, -): Promise { - await dispatchSetStatus(bridge, { status, extStatus, batteryStatus }); -} - -/** - * DIY (custom) online status. napcat fixes status=10 / extStatus=2000 - * — the values QQ associates with "I have a custom status string" — - * and threads the faceId / wording / faceType through the customExt - * sub-message of the same SetStatus wire call. - */ -export async function setDiyOnlineStatus( - bridge: Bridge, - faceId: number, - wording: string, - faceType: number, -): Promise { - await dispatchSetStatus(bridge, { - status: 10, - extStatus: 2000, - batteryStatus: 0, - customExt: { faceId, text: wording, faceType }, - }); -} - -async function dispatchSetStatus( - bridge: Bridge, - value: { - status: number; - extStatus: number; - batteryStatus: number; - customExt?: { faceId: number; text: string; faceType: number }; - }, -): Promise { - const request = protoEncode(value, SetStatusReqSchema); - - const result = await bridge.sendRawPacket('trpc.qq_new_tech.status_svc.StatusService.SetStatus', request); - - if (!result.success) { - throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); - } - - if (result.responseData && result.responseData.length > 0) { - const resp = protoDecode(result.responseData, SetStatusRespSchema); - if (!resp) { - throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); - } - if (resp.errCode !== undefined && resp.errCode !== 0) { - throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`); - } - } -} - -export async function setProfile( - bridge: Bridge, - nickname?: string, - personalNote?: string, -): Promise { - const uin = BigInt(bridge.identity.uin); - const stringProfiles: any[] = []; - const intProfiles: any[] = []; - - if (nickname !== undefined) { - stringProfiles.push({ fieldId: 20002, value: nickname }); - } - - if (personalNote !== undefined) { - stringProfiles.push({ fieldId: 102, value: personalNote }); - } - - if (stringProfiles.length === 0 && intProfiles.length === 0) { - return; - } - - const req = { - uin, - stringProfiles, - }; - - const env = makeOidbEnvelope(0x112A, 2, req); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', encodeOidbEnv(env)); -} - -export async function setSelfLongNick( - bridge: Bridge, - longNick: string, -) { - const req = { - uin: BigInt(bridge.identity.uin), - profile: { - tag: 102, - value: String(longNick), - }, - }; - - const env = makeOidbEnvelope(0x112A, 2, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', encodeOidbEnv(env)); - // Decode just to maintain the original behaviour of "consume the response". - decodeOidbEnv(respBytes); -} - -export async function setInputStatus( - bridge: Bridge, - userId: number, - eventType: number, -) { - const targetUid = await bridge.resolveUserUid(userId); - - if (!targetUid) { - throw new Error('target uid not found'); - } - - const req = { - reqBody: { - uid: targetUid, - chatType: 0, - eventType: eventType, - }, - }; - - const env = makeOidbEnvelope(0xCD4, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', encodeOidbEnv(env)); - // Decode just to maintain the original behaviour of "consume the response". - decodeOidbEnv(respBytes); -} - -export async function setAvatar( - bridge: Bridge, - source: string, -): Promise { - const loaded = await loadBinarySource(source, 'avatar'); - if (!loaded.bytes.length) throw new Error('avatar file is empty'); - - const hashes = computeHashes(loaded.bytes); - const session = await fetchHighwaySession(bridge); - await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0)); -} - -/** - * Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar: - * - same highway HTTP upload as personal avatar - * - cmdId 3000 (instead of 90) - * - GroupAvatarExtra proto carried as the `extend` blob, with the - * four protocol-prescribed constants (type=101, field5=3, field6=1, - * field3.field1=1) and the target groupUin. - * - * Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar. - */ -export async function setGroupAvatar( - bridge: Bridge, - groupId: number, - source: string, -): Promise { - const loaded = await loadBinarySource(source, 'group-avatar'); - if (!loaded.bytes.length) throw new Error('group avatar file is empty'); - - const hashes = computeHashes(loaded.bytes); - const session = await fetchHighwaySession(bridge); - const extra = protoEncode({ - type: 101, - groupUin: groupId, - field3: { field1: 1 }, - field5: 3, - field6: 1, - }, GroupAvatarExtraSchema); - await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra); -} - -// ─────────────── queries on me / my contacts ─────────────── - -export async function getProfileLike( - bridge: Bridge, - userId?: number, - start: number = 0, - limit: number = 10, -) { - const isSelf = !userId; - const targetUid = isSelf - ? await resolveSelfUid(bridge) - : await bridge.resolveUserUid(userId); - - if (!targetUid) { - throw new Error('target uid not found'); - } - - const req = { - targetUid: targetUid, - basic: 1, - vote: 1, - favorite: 1, - start: start, - limit: limit, - }; - - const env = makeOidbEnvelope(0x7ED, 12, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', encodeOidbEnv(env)); - const result = decodeOidbEnv(respBytes).body; - - const data = result?.userLikeInfos?.[0]; - if (!data) { - throw new Error('get profile like info empty'); - } - - return { - uid: data.uid, - time: Number(data.time), - favoriteInfo: { - total_count: data.favoriteInfo?.totalCount || 0, - last_time: Number(data.favoriteInfo?.lastTime || 0), - today_count: data.favoriteInfo?.newCount || 0, - userInfos: [], - }, - voteInfo: { - total_count: data.voteInfo?.totalCount || 0, - new_count: data.voteInfo?.newCount || 0, - new_nearby_count: 0, - last_visit_time: Number(data.voteInfo?.lastTime || 0), - userInfos: [], - }, - }; -} - -export async function getUnidirectionalFriendList( - bridge: Bridge, -) { - const reqObj = { - uint64_uin: String(bridge.identity.uin), - uint64_top: 0, - uint32_req_num: 99, - bytes_cookies: '', - }; - - const req = { - jsonBody: JSON.stringify(reqObj), - }; - - const env = makeOidbEnvelope(0xE17, 0, req); - const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', encodeOidbEnv(env)); - const result = decodeOidbEnv(respBytes).body; - - if (!result || !result.jsonBody) { - throw new Error('get unidirectional friend list empty'); - } - - const parsed = JSON.parse(result.jsonBody); - return parsed.rpt_block_list || []; -} - -export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise { - const req = { - inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' }, - uin: BigInt(bridge.identity.uin), - field3: 1, - field6: 1, - }; - const request = protoEncode(req, FaceroamOpReqSchema); - const result = await bridge.sendRawPacket('Faceroam.OpReq', request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'fetch custom face failed'); - } - const resp = protoDecode(result.responseData, FaceroamOpRespSchema); - if (!resp || (resp as any).retCode !== 0) { - throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`); - } - const faceIds = (resp as any).item?.faceIds || []; - return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.identity.uin}/${id}/0`); -} diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts new file mode 100644 index 00000000..6f1ad964 --- /dev/null +++ b/packages/core/src/bridge/apis/contacts.ts @@ -0,0 +1,392 @@ +// ContactsApi — friend / group / member roster + user-profile + +// group-request-list + download-rkey OIDB calls. +// +// All implementations inlined from the previous `bridge-contacts.ts` +// (which gets removed alongside the rest of the actions/* facade +// shim in commit 13). The single non-trivial piece carried over is +// the per-group inflight + TTL cache for `fetchGroupMemberList`: +// without it a busy OneBot client (e.g. MaiBot calling +// `get_group_member_info` once per inbound message) would trigger +// one OIDB 0xfe7_3 per chat message, sustained >1k/h, which trips +// Tencent risk-control and gets the account banned for 7 days. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { + OidbBase, + OidbSvcTrpcTcp0x10C0Response, + OidbSvcTrpcTcp0xFD4_1Response, + OidbSvcTrpcTcp0xFE5_2Response, + OidbSvcTrpcTcp0xFE7_3Response, +} from '@snowluma/proto-defs/oidb'; +import type { + AvatarInfo, + OidbFriendListRequest, + OidbGroupListRequest, + OidbGroupMemberListRequest, + OidbGroupRequestList, + OidbUserInfoRequest, + OidbUserInfoResponse, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { + NTV2RichMediaReq, + NTV2RichMediaResp, +} from '@snowluma/proto-defs/oidb-actions/media'; +import type { BridgeContext } from '../bridge-context'; +import type { DownloadRKeyInfo } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; +import type { Bridge } from '../bridge'; +import type { + FriendInfo, + GroupMemberInfo, + GroupRequestInfo, + QQGroupInfo, + UserProfileInfo, +} from '@snowluma/bridge/qq-info'; + +// ─── Helpers (previously in bridge-contacts.ts) ─────────────────── + +export function buildFriendProperties(raw: any): Map { + const props = new Map(); + for (const additional of raw.additional ?? []) { + if ((additional.type ?? 0) !== 1 || !additional.layer1) continue; + for (const property of additional.layer1.properties ?? []) { + props.set(property.code ?? 0, property.value ?? ''); + } + } + return props; +} + +export function permissionToRole(permission: number): string { + switch (permission) { + case 1: return 'owner'; + case 2: return 'admin'; + default: return 'member'; + } +} + +// `runOidb` and the proto-defs helpers take `Bridge` (deep dependency +// inside the highway / sendRawPacket plumbing). At runtime `ctx` IS +// the Bridge that constructed this Api, so narrowing back via +// `ctx as Bridge` is safe — see the same pattern in `MessageApi` +// where buildSendElems also expects a Bridge. +function asBridge(ctx: BridgeContext): Bridge { + return ctx as unknown as Bridge; +} + +const MEMBER_LIST_TTL_MS = 60_000; + +export class ContactsApi { + /** + * Per-group inflight + last-fetch cache for `fetchGroupMemberList`. + * Keyed by groupId, lives for the lifetime of the Bridge (so the + * cache resets per account, as you'd expect for multi-account + * runtimes — `BridgeManager` builds one Bridge per uin and each + * gets its own ContactsApi). + */ + private memberListInflight = new Map>(); + private memberListLastFetch = new Map(); + + constructor(private readonly ctx: BridgeContext) {} + + async fetchFriendList(): Promise { + const bridge = asBridge(this.ctx); + const friends: FriendInfo[] = []; + let nextUin: number | null = null; + + do { + const body: any = { + friendCount: 300, + field4: 0, + field6: 1, + field7: 0x7FFFFFFF, + body: [ + { type: 1, number: { numbers: [103, 102, 20002, 27394] } }, + { type: 4, number: { numbers: [100, 101, 102] } }, + ], + field10002: [13578, 13579, 13573, 13572, 13568], + field10003: 4051, + }; + if (nextUin !== null) { + body.nextUin = { uin: nextUin }; + } + const env = makeOidbEnvelope(0xFD4, 1, body); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + if (resp?.friends) { + for (const raw of resp.friends) { + const props = buildFriendProperties(raw); + friends.push({ + uin: raw.uin ?? 0, + uid: raw.uid ?? '', + nickname: props.get(20002) ?? String(raw.uin ?? 0), + remark: props.get(103) ?? '', + }); + } + } + + nextUin = resp?.next?.uin ?? null; + if (nextUin === 0) nextUin = null; + } while (nextUin !== null); + + this.ctx.identity.rememberFriends(friends); + return friends; + } + + async fetchGroupList(): Promise { + const bridge = asBridge(this.ctx); + // The config flags ask QQ which per-group fields to include in + // the response. Asking for everything looks innocent on small + // accounts but on ~200+ groups it makes the QQ NT process write + // a payload large enough to blow the named-pipe write buffer — + // we then read EPIPE and the whole session dies. See issue #42. + // Keep `config1.*` mostly on but turn off the costly groups of + // bools that never map back to a decoded field. + const allTrue = true; + const body = { + config: { + config1: { + groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue, + groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue, + field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue, + field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue, + question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue, + field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue, + field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue, + field32: allTrue, field5001: allTrue, field5002: false, field5003: false, + }, + config2: { + field1: false, field2: false, field3: false, field4: false, + field5: false, field6: false, field7: false, field8: false, + }, + config3: { field5: allTrue, field6: allTrue }, + }, + }; + const env = makeOidbEnvelope(0xFE5, 2, body, true); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const groups: QQGroupInfo[] = []; + if (resp?.groups) { + for (const raw of resp.groups) { + groups.push({ + groupId: raw.groupUin ?? 0, + groupName: raw.info?.groupName ?? '', + remark: raw.customInfo?.remark ?? '', + memberCount: raw.info?.memberCount ?? 0, + memberMax: raw.info?.memberMax ?? 0, + members: new Map(), + }); + } + } + this.ctx.identity.rememberGroups(groups); + return groups; + } + + async fetchGroupMemberList( + groupId: number, + options: { force?: boolean } = {}, + ): Promise { + // Coalesce in-flight calls + serve a 60s-cached result. Without + // this, a busy OneBot client gets the bot 7-day banned within + // hours via Tencent risk-control. + const now = Date.now(); + const last = this.memberListLastFetch.get(groupId); + if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) { + return last.data; + } + const inflight = this.memberListInflight.get(groupId); + if (inflight) return inflight; + const task = (async () => { + try { + const data = await this.fetchGroupMemberListUncached(groupId); + this.memberListLastFetch.set(groupId, { at: Date.now(), data }); + return data; + } finally { + this.memberListInflight.delete(groupId); + } + })(); + this.memberListInflight.set(groupId, task); + return task; + } + + private async fetchGroupMemberListUncached(groupId: number): Promise { + const bridge = asBridge(this.ctx); + const members: GroupMemberInfo[] = []; + let token = ''; + + do { + const body: any = { + groupUin: groupId, + field2: 5, + field3: 2, + body: { + memberName: true, memberCard: true, level: true, field13: true, + field16: true, specialTitle: true, field18: true, field20: true, + field21: true, joinTimestamp: true, lastMsgTimestamp: true, + shutUpTimestamp: true, field103: true, field104: true, field105: true, + field106: true, permission: true, field200: true, field201: true, + }, + }; + if (token) body.token = token; + const env = makeOidbEnvelope(0xFE7, 3, body); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + if (resp?.members) { + for (const raw of resp.members) { + members.push({ + uin: raw.uin?.uin ?? 0, + uid: raw.uin?.uid ?? '', + nickname: raw.memberName ?? '', + card: raw.memberCard?.memberCard ?? '', + role: permissionToRole(raw.permission ?? 0), + level: raw.level?.level ?? 0, + title: raw.specialTitle ?? '', + joinTime: raw.joinTimestamp ?? 0, + lastSentTime: raw.lastMsgTimestamp ?? 0, + shutUpTime: raw.shutUpTimestamp ?? 0, + }); + } + } + token = resp?.token ?? ''; + } while (token); + + this.ctx.identity.rememberGroupMembers(groupId, members); + return members; + } + + async fetchUserProfile(uin: number): Promise { + const bridge = asBridge(this.ctx); + const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037]; + // Only `uin` and `keys` — see OidbUserInfoRequestSchema for why + // sending field 2 makes the server reject the request. + const body = { + uin, + keys: keys.map(k => ({ key: k })), + }; + // Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the + // name is historical, the wire semantic is "this is the UIN-form + // variant of the call"). Without it newer QQ NT versions take the + // UID-form validation path, find neither uid nor openid in the + // body and bounce the request with + // `[oidb] one of uid/openid is invaild`. Matches Lagrange.Core's + // FetchStrangerByUin (Reserved = 1). + const env = makeOidbEnvelope(0xFE1, 2, body, true); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + if (!resp?.body) throw new Error('user info response body missing'); + + const info: UserProfileInfo = { + uin: resp.body.uin ?? uin, + uid: resp.body.uid ?? '', + nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', + }; + + if (resp.body.properties) { + const bytesMap = new Map(); + const numMap = new Map(); + for (const bp of resp.body.properties.bytesProperties ?? []) { + bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0)); + } + for (const np of resp.body.properties.numberProperties ?? []) { + numMap.set(np.number1 ?? 0, np.number2 ?? 0); + } + const getString = (code: number) => { + const b = bytesMap.get(code); + return b ? Buffer.from(b).toString('utf8') : ''; + }; + info.nickname = getString(20002); + info.remark = getString(103); + info.qid = getString(27394); + info.sign = getString(102); + + const avatarBytes = bytesMap.get(101); + if (avatarBytes) { + const av = protobuf_decode(avatarBytes); + if (av?.url) info.avatar = av.url + '640'; + } + const sexNum = numMap.get(20009) ?? 0; + info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown'; + info.age = numMap.get(20037) ?? 0; + } + + this.ctx.identity.rememberUserProfile(info); + return info; + } + + async fetchGroupRequests(filtered = false): Promise { + const bridge = asBridge(this.ctx); + const subCmd = filtered ? 2 : 1; + const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1'; + const env = makeOidbEnvelope(0x10C0, subCmd, { count: 20, field2: 0 }); + const respBytes = await runOidb(bridge, cmd, protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const requests: GroupRequestInfo[] = []; + for (const raw of resp?.requests ?? []) { + requests.push({ + groupId: raw.group?.groupUin ?? 0, + groupName: raw.group?.groupName ?? '', + targetUid: raw.target?.uid ?? '', + targetUin: 0, + targetName: raw.target?.name ?? '', + invitorUid: raw.invitor?.uid ?? '', + invitorUin: 0, + invitorName: raw.invitor?.name ?? '', + operatorUid: raw.operatorUser?.uid ?? '', + operatorUin: 0, + operatorName: raw.operatorUser?.name ?? '', + sequence: Number(raw.sequence ?? 0), + state: raw.state ?? 0, + eventType: raw.eventType ?? 0, + comment: raw.comment ?? '', + filtered, + }); + } + this.ctx.identity.rememberGroupRequests(requests); + return requests; + } + + async fetchDownloadRKeys(): Promise { + const bridge = asBridge(this.ctx); + const PRIVATE_IMAGE = 10; + const GROUP_IMAGE = 20; + const FALLBACK_IMAGE = 2; + + const body = { + reqHead: { + common: { requestId: 1, command: 202 }, + scene: { requestType: 2, businessType: 1, sceneType: 0 }, + client: { agentType: 2 }, + }, + downloadRkey: { + types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE], + }, + }; + const env = makeOidbEnvelope(0x9067, 202, body, true); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) { + throw new Error(resp.respHead.message ?? 'fetch download rkey failed'); + } + + const result: DownloadRKeyInfo[] = []; + for (const entry of resp?.downloadRkey?.rkeys ?? []) { + const rkey = entry.rkey ?? ''; + const type = entry.type ?? 0; + if (rkey && type) { + result.push({ + rkey, + ttlSeconds: Number(entry.rkeyTtlSec ?? 0), + storeId: entry.storeId ?? 0, + createTime: entry.rkeyCreateTime ?? 0, + type, + }); + } + } + return result; + } +} diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/bridge/apis/extras.ts new file mode 100644 index 00000000..327b733e --- /dev/null +++ b/packages/core/src/bridge/apis/extras.ts @@ -0,0 +1,151 @@ +// ExtrasApi — Tier-2 napcat-parity surfaces that don't fit anywhere +// else: group todo CRUD, stranger online/ext status decode, AI voice +// list + synthesis. Inlined from `actions/extras.ts` (deleted alongside +// actions/* in commit 13). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupTodo, + OidbStrangerStatusReq, + OidbStrangerStatusResp, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { + OidbAiVoiceListReq, + OidbAiVoiceListResp, + OidbAiVoiceReq, + OidbAiVoiceResp, +} from '@snowluma/proto-defs/oidb-actions/media'; +import type { MediaIndexNode } from './shared'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +// ─────────────── public types (re-exported from bridge.ts as before) ─── + +export interface StrangerStatus { + status: number; + ext_status: number; +} + +export const AiVoiceChatType = { + Unknown: 0, + Sound: 1, + Sing: 2, +} as const; +export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType]; + +export interface AiVoiceItem { + voiceId: string; + voiceDisplayName: string; + voiceExampleUrl: string; +} + +export interface AiVoiceCategory { + category: string; + voices: AiVoiceItem[]; +} + +export class ExtrasApi { + constructor(private readonly ctx: BridgeContext) {} + + // ─────────────── Group todo (0xF90) ─────────────── + + async setGroupTodo(groupId: number, msgSeq: bigint): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0xF90, 1, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', protobuf_encode>(env)); + } + + async completeGroupTodo(groupId: number, msgSeq: bigint): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0xF90, 2, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', protobuf_encode>(env)); + } + + async cancelGroupTodo(groupId: number, msgSeq: bigint): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0xF90, 3, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', protobuf_encode>(env)); + } + + // ─────────────── Stranger online/ext status (0xFE1_2) ─────────────── + + /** + * Mirror napcat's GetStrangerStatus: decode the extBigInt status word. + * Values ≤10 fold into a 10×status; everything else is split into the + * high-byte / low-byte ext_status the OneBot dialect uses. + * + * Returns null on transport / decode failure rather than throwing, so + * the OneBot action can produce a clean retcode without try/catch + * gymnastics. + */ + async getStrangerStatus(uin: number): Promise { + const bridge = asBridge(this.ctx); + try { + const env = makeOidbEnvelope( + 0xFE1, 2, + { uin, key: [{ key: 27372 }] } as any, + // Same UIN-form flag fetchUserProfile sets — without it newer + // QQ NT rejects with `[oidb] one of uid/openid is invaild`. + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + const raw = resp?.data?.status?.value; + if (raw === undefined || raw === null) return null; + const extBig = typeof raw === 'bigint' ? raw : BigInt(raw); + if (extBig <= 10n) { + return { status: Number(extBig) * 10, ext_status: 0 }; + } + const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn)); + return { status: 10, ext_status: status }; + } catch { + return null; + } + } + + // ─────────────── AI voice (0x929D / 0x929B) ─────────────── + + async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x929D, 0, { groupUin: groupId, chatType }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + return (resp?.content as AiVoiceCategory[] | undefined) ?? []; + } + + /** + * Trigger AI voice synthesis. Server may return an empty msgInfo while + * the render is in-flight; we retry until a node materialises or the + * cap is hit. napcat uses the same 30-retry budget. + * + * The returned MediaIndexNode plugs directly into + * `apis.groupFile.getPttUrl`, which already handles every other + * download-URL fetch in SnowLuma. + */ + async fetchAiVoice( + groupId: number, + voiceId: string, + text: string, + chatType: AiVoiceChatType | number, + maxRetries = 30, + ): Promise { + const bridge = asBridge(this.ctx); + // Random 32-bit session id — server uses this to deduplicate polls. + const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0; + for (let i = 0; i < maxRetries; i++) { + const env = makeOidbEnvelope( + 0x929B, 0, + { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined; + if (node) return node; + } + throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); + } +} diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts new file mode 100644 index 00000000..2ebe8656 --- /dev/null +++ b/packages/core/src/bridge/apis/forward.ts @@ -0,0 +1,490 @@ +// ForwardApi — long-message (聊天记录 / forward) upload + retrieval. +// Inlined from `actions/forward.ts` (deleted alongside actions/* in +// commit 13). +// +// The module-scoped `forwardResCache` stays at file scope (not on the +// class instance) because forward res_ids are globally unique, and an +// outbound upload often gets queried back through `fetch` on a +// different Bridge instance (e.g. a different OneBot connection +// hitting the same account). Keeping the cache shared across the +// process matches NapCat's behaviour. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { randomUUID } from 'crypto'; +import { gunzipSync, gzipSync } from 'zlib'; +import type { + LongMsgResult, + RecvLongMsgReq, + RecvLongMsgResp, + SendLongMsgReq, + SendLongMsgResp, +} from '@snowluma/proto-defs/longmsg'; +import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { buildSendElems } from '@snowluma/bridge/element-builder'; +import type { ForwardNodePayload, MessageElement } from '@snowluma/bridge/events'; +import { parseMsgPush } from '@snowluma/bridge/msg-push'; +import { resolveSelfUid, toInt } from './shared'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +// Module-scoped cache, keyed by res_id. Survives only for the lifetime +// of the process — that's enough because OneBot clients typically +// resolve a forward immediately after receiving the parent message. +const forwardResCache = new Map(); + +// Per-layer piggyback entry. Each level of a nested forward attaches +// its own msgBody under a uuid `actionCommand`, so when the receiver +// fetches the outermost res_id it gets every layer in one shot +// (modelled on NapCat's `uploadForwardedNodesPacket` — see +// `dev/NapCatQQ/.../SendMsg.ts:208-347`). Lagrange.Core master + V2 +// both ship a single-action model and silently break when the +// recipient is a NapCat instance trying to walk the tree. +interface ForwardInnerAction { + uuid: string; + msgBody: PushMsgBody[]; +} + +interface ForwardUploadResult { + resId: string; + // The current level's msgBody + uuid — what an outer caller would + // piggyback to expose this layer through the tree. + msgBody: PushMsgBody[]; + uuid: string; + // All accumulated piggyback entries from deeper levels. Outer + // callers concatenate these to their own actions list so the + // outermost upload carries the full tree. + innerActions: ForwardInnerAction[]; +} + +// Local hex-decode helper — avoids importing the heavyweight `pipeline` +// module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`. +function hexToBytesLocal(hex: string): Uint8Array { + const s = hex.trim(); + if (!s) return new Uint8Array(0); + const len = s.length >> 1; + const out = new Uint8Array(len); + for (let i = 0; i < len; i++) { + out[i] = parseInt(s.substr(i * 2, 2), 16); + } + return out; +} + +async function buildForwardPushBody( + bridge: Bridge, + node: ForwardNodePayload, + groupId?: number, + userUid?: string, +): Promise { + const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin); + if (fromUin <= 0) throw new Error('forward node user uin is invalid'); + + const nickname = node.nickname.trim() || String(fromUin); + // image/record/video upload inside a forward node must be scoped to the + // forward's recipient: group → groupId, private → recipient uid. + // Without this the OIDB upload (0x11c4/0x11c5) has no scene and the + // element builder throws "private image target uid is missing". + // + // `forwardFake: true` keeps `{type:'file'}` segments in the + // long-msg payload: group → emitted as transElem(24) in elems[], + // c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }). + // The QQ-NT live-send pipeline would reject these (transElem(24) → + // result=79; notOnlineFile via PbSendMsg doesn't render), but the + // long-msg upload service stores the bytes verbatim and the + // receiver decodes them through the normal msg-push path. + const sendCtx = groupId !== undefined + ? { bridge, groupId, forwardFake: true } + : userUid + ? { bridge, userUid, forwardFake: true } + : { bridge, forwardFake: true }; + const elems = await buildSendElems(node.elements, sendCtx); + const now = Math.floor(Date.now() / 1000); + const random = Math.floor(Math.random() * 0x7fffffff) >>> 0; + const seq = Math.floor(Math.random() * 9000000) + 1000000; + + // c2c-file in a forward node — element-builder intentionally skips + // it (RichText.notOnlineFile + msgContent live outside elems[]). For + // forward fake-send we mirror what an inbound c2c file message looks + // like on the wire: serialise the FileExtra blob and ride it on + // `body.msgContent`. The receiver's rich-body-decoder reads from + // `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so + // the bubble renders with the right file name + size when the + // forward is expanded. Only the FIRST c2c file in a node ships — + // QQ NT's bubble can only carry one msgContent payload, same as + // a live c2c send. Group nodes ignore this branch entirely (the + // transElem(24) elems[] entry above covers them). + let msgContent: Uint8Array | undefined; + if (groupId === undefined) { + const fileEl = node.elements.find(e => e.type === 'file' && e.fileId); + if (fileEl) { + // Honour inline segment fields first; fall back to the upload + // metadata cache (populated by upload_private_file). Without + // size/md5 the receiver would render "0 B" so prefer recovering + // them — see same logic in modules/message-actions.ts. + const cached = bridge.recallUploadedFile(fileEl.fileId ?? ''); + const fileMd5 = fileEl.md5Hex + ? hexToBytesLocal(fileEl.md5Hex) + : (cached?.fileMd5 ?? new Uint8Array(0)); + const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0; + const fileName = fileEl.fileName ?? cached?.fileName ?? 'file'; + const fileHash = fileEl.fileHash ?? cached?.fileHash ?? ''; + const sevenDays = 7 * 24 * 60 * 60; + msgContent = protobuf_encode({ + file: { + fileType: 0, + fileUuid: fileEl.fileId!, + fileMd5, + fileName, + fileSize: BigInt(fileSize), + subcmd: 1, + dangerEvel: 0, + expireTime: now + sevenDays, + fileHash, + }, + }); + } + } + + return { + responseHead: { + fromUin, + toUid: bridge.identity.selfUid ?? '', + forward: { + friendName: nickname, + }, + }, + contentHead: { + msgType: 9, + subType: 4, + msgId: random, + sequence: seq, + timestamp: now, + divSeq: 0, + }, + body: { + richText: { + elems, + }, + ...(msgContent ? { msgContent } : {}), + }, + }; +} + +// Inner forward preview metadata — kept minimal here (the OneBot +// `parseForwardNodes` caller can override these on the top-level +// node by passing custom forwardSource/forwardSummary on the +// non-nested send path; nested levels just get sensible defaults +// since they're synthesised by us and never reach OneBot input). +function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string { + const nicks: string[] = []; + const seen = new Set(); + for (const node of innerNodes) { + const name = (node.nickname ?? '').trim(); + if (name && !seen.has(name)) { + seen.add(name); + nicks.push(name); + } + if (nicks.length >= 4) break; + } + if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录'; + return `${nicks.join('和')}的聊天记录`; +} + +function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> { + return innerNodes.slice(0, 4).map(node => { + const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户'); + const previewText = previewFromElements(node.elements); + return { text: previewText ? `${name}: ${previewText}` : name }; + }); +} + +function previewFromElements(elements: MessageElement[]): string { + for (const elem of elements) { + if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30); + if (elem.type === 'image') return '[图片]'; + if (elem.type === 'record') return '[语音]'; + if (elem.type === 'video') return '[视频]'; + if (elem.type === 'file') return '[文件]'; + if (elem.type === 'forward') return '[聊天记录]'; + if (elem.type === 'face') return '[表情]'; + } + return ''; +} + +export class ForwardApi { + constructor(private readonly ctx: BridgeContext) {} + + async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { + const { resId } = await this.uploadRecursive(nodes, groupId, userId); + return resId; + } + + /** + * Recursive upload with NapCat-style piggyback. Each invocation: + * 1. Walks `nodes`. For any node whose `innerForward` is set, + * recursively uploads that inner chain first (which itself runs + * this same recursion). + * 2. Replaces the node's `elements` with an ARK preview pointing at + * the inner res_id (and inner uuid for receiver-side walking). + * 3. Accumulates the inner level's `{uuid, msgBody}` plus all of + * ITS accumulated `innerActions` into this level's piggyback list. + * 4. Encodes this level's long-msg payload as + * `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it, + * returns `{resId, msgBody, uuid, innerActions}` so an outer + * caller can keep piggybacking up the tree. + */ + private async uploadRecursive( + nodes: ForwardNodePayload[], + groupId?: number, + userId?: number, + ): Promise { + if (!Array.isArray(nodes) || nodes.length === 0) { + throw new Error('forward nodes are required'); + } + + const bridge = asBridge(this.ctx); + + // For a private forward to `userId`, any image/record/video inside a node + // needs the recipient's uid as upload scene. Resolve it once up-front, + // and only when at least one node actually contains media (saves an RPC + // for text-only forwards). Also need it when a node is itself a nested + // forward — the inner upload uses the same scene. + let userUid: string | undefined; + if (groupId === undefined && userId !== undefined && userId > 0) { + const needsUid = nodes.some(node => !!node.innerForward + || node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video')); + if (needsUid) { + const resolved = await this.ctx.resolveUserUid(userId); + if (resolved) userUid = resolved; + } + } + + // Walk nodes and resolve nested forwards first (so we know their + // res_id / uuid before encoding the outer ARK previews). Build + // `processedNodes` with elements rewritten for nested layers, + // and collect every inner level's piggyback in `myInnerActions`. + const myInnerActions: ForwardInnerAction[] = []; + const processedNodes: ForwardNodePayload[] = []; + const isGroup = groupId !== undefined; + for (const node of nodes) { + if (node.innerForward && node.innerForward.length > 0) { + const inner = await this.uploadRecursive(node.innerForward, groupId, userId); + // NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}` + // + the entire `inner.innerPacketMsg` array up to its caller. We + // mirror that — `inner.uuid` indexes the inner level itself, + // and `inner.innerActions` already contains deeper layers. + myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody }); + myInnerActions.push(...inner.innerActions); + // Replace the inner placeholder element with a forward preview + // pointing at the inner res_id. The wire-side element builder + // turns this into the same XML m_resid blob it already produced + // for top-level forwards — see `makeForwardElem` in + // element-builder.ts:153. + const previewElement: MessageElement = { + type: 'forward', + resId: inner.resId, + forwardSource: deriveInnerSource(node.innerForward, isGroup), + forwardSummary: `查看${node.innerForward.length}条转发消息`, + forwardPrompt: '[聊天记录]', + forwardNews: previewLinesFromNodes(node.innerForward), + forwardTSum: node.innerForward.length, + }; + processedNodes.push({ + userUin: node.userUin, + nickname: node.nickname, + elements: [previewElement], + time: node.time, + msgId: node.msgId, + msgSeq: node.msgSeq, + groupId: node.groupId, + senderCard: node.senderCard, + messageType: node.messageType, + }); + } else { + processedNodes.push(node); + } + } + + // Encode this level's msgBody. + const msgBody = await Promise.all(processedNodes.map( + node => buildForwardPushBody(bridge, node, groupId, userUid), + )); + + // Compose the action list: own MultiMsg + piggybacked inner actions. + const longMsgResult = protobuf_encode({ + action: [ + { actionCommand: 'MultiMsg', actionData: { msgBody } }, + ...myInnerActions.map(a => ({ + actionCommand: a.uuid, + actionData: { msgBody: a.msgBody }, + })), + ], + }); + + const selfUid = await resolveSelfUid(bridge); + const info: SendLongMsgReq['info'] = { + type: groupId ? 3 : 1, + uid: { uid: groupId ? String(groupId) : selfUid }, + payload: gzipSync(Buffer.from(longMsgResult)), + }; + if (groupId) info.groupUin = groupId; + + const request = protobuf_encode({ + info, + settings: { + field1: 4, + field2: 1, + field3: 7, + field4: 0, + }, + }); + + const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'upload forward message failed'); + } + + const resp = protobuf_decode(result.responseData); + const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : ''; + if (!resId) { + throw new Error('upload forward message response missing res_id'); + } + + forwardResCache.set(resId, processedNodes.map(node => ({ + userUin: node.userUin, + nickname: node.nickname, + elements: [...node.elements], + time: node.time, + msgId: node.msgId, + msgSeq: node.msgSeq, + groupId: node.groupId ?? groupId, + senderCard: node.senderCard, + messageType: node.messageType ?? (groupId ? 'group' : 'private'), + }))); + + return { + resId, + msgBody, + uuid: randomUUID(), + innerActions: myInnerActions, + }; + } + + async fetch(resId: string): Promise { + const bridge = asBridge(this.ctx); + const cached = forwardResCache.get(resId); + if (cached) { + return cached.map(node => ({ + userUin: node.userUin, + nickname: node.nickname, + elements: [...node.elements], + time: node.time, + msgId: node.msgId, + msgSeq: node.msgSeq, + groupId: node.groupId, + senderCard: node.senderCard, + messageType: node.messageType, + })); + } + + const selfUid = await resolveSelfUid(bridge); + const request = protobuf_encode({ + info: { + uid: { uid: selfUid }, + resId, + acquire: true, + }, + settings: { + field1: 2, + field2: 0, + field3: 0, + field4: 0, + }, + }); + + const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'download forward message failed'); + } + + const resp = protobuf_decode(result.responseData); + const payload = resp?.result?.payload; + if (!(payload instanceof Uint8Array) || payload.length === 0) { + throw new Error('download forward message payload is empty'); + } + + const inflate = gunzipSync(Buffer.from(payload)); + const longMsg = protobuf_decode(inflate); + const action = longMsg?.action?.find((item) => item?.actionCommand === 'MultiMsg'); + const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : []; + + const nodes: ForwardNodePayload[] = []; + for (const msgBody of msgBodyList) { + const wrapped = protobuf_encode({ message: msgBody }); + const pkt: PacketInfo = { + pid: 0, + uin: this.ctx.identity.uin, + serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', + seqId: 0, + retCode: 0, + fromClient: false, + body: wrapped, + }; + const events = parseMsgPush(pkt, this.ctx.identity); + const event = events.find(e => + e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message'); + if (!event) continue; + + if (event.kind === 'group_message') { + nodes.push({ + userUin: event.senderUin, + nickname: event.senderCard || event.senderNick, + elements: event.elements, + time: event.time, + msgId: event.msgId, + msgSeq: event.msgSeq, + groupId: event.groupId, + senderCard: event.senderCard, + messageType: 'group', + }); + } else if (event.kind === 'friend_message') { + nodes.push({ + userUin: event.senderUin, + nickname: event.senderNick, + elements: event.elements, + time: event.time, + msgId: event.msgId, + msgSeq: event.msgSeq, + messageType: 'private', + }); + } else { + nodes.push({ + userUin: event.senderUin, + nickname: event.senderNick, + elements: event.elements, + time: event.time, + msgSeq: event.msgSeq, + groupId: event.groupId, + messageType: 'private', + }); + } + } + + if (nodes.length > 0) { + forwardResCache.set(resId, nodes.map(node => ({ + userUin: node.userUin, + nickname: node.nickname, + elements: [...node.elements], + time: node.time, + msgId: node.msgId, + msgSeq: node.msgSeq, + groupId: node.groupId, + senderCard: node.senderCard, + messageType: node.messageType, + }))); + } + return nodes; + } +} diff --git a/packages/core/src/bridge/apis/friend.ts b/packages/core/src/bridge/apis/friend.ts new file mode 100644 index 00000000..639b72a7 --- /dev/null +++ b/packages/core/src/bridge/apis/friend.ts @@ -0,0 +1,70 @@ +// FriendApi — friend roster mutations (handle add request / +// delete / set remark). Inlined from `actions/friend.ts` (deleted +// alongside actions/* in commit 13). The READ side of friends +// (fetchFriendList) lives on ContactsApi because friends/groups +// share the same roster pipeline. + +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbDeleteFriend, + OidbFriendRequestAction, + OidbSetFriendRemark, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +export class FriendApi { + constructor(private readonly ctx: BridgeContext) {} + + /** + * Accept or reject an inbound friend request. `uidOrFlag` is either a + * pre-resolved UID string or a numeric uin (then resolved on the fly). + */ + async handleRequest(uidOrFlag: string, approve: boolean): Promise { + const bridge = asBridge(this.ctx); + let targetUid = uidOrFlag; + if (/^\d+$/.test(uidOrFlag)) { + targetUid = await this.ctx.resolveUserUid(parseInt(uidOrFlag, 10)); + } + const env = makeOidbEnvelope(0xB5D, 44, { accept: approve ? 3 : 5, targetUid }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', protobuf_encode>(env)); + } + + async delete(userId: number, block = false): Promise { + const bridge = asBridge(this.ctx); + const targetUid = await this.ctx.resolveUserUid(userId); + const env = makeOidbEnvelope(0x126B, 0, { + field1: { + targetUid, + field2: { + field1: 130, + field2: 109, + field3: { + field1: 8, + field2: 8, + field3: 50, + }, + }, + block, + field4: false, + }, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x126b_0', protobuf_encode>(env)); + + // Refresh friend cache after deletion so subsequent reads don't + // surface a ghost entry. Best-effort: a transient OIDB hiccup here + // shouldn't make the delete itself look failed. + try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ } + } + + async setRemark(userId: number, remark: string): Promise { + const bridge = asBridge(this.ctx); + const uid = await this.ctx.resolveUserUid(userId); + const env = makeOidbEnvelope(0xB6E, 2, { targetUid: uid, remark }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', protobuf_encode>(env)); + } +} diff --git a/packages/core/src/bridge/apis/group-admin.ts b/packages/core/src/bridge/apis/group-admin.ts new file mode 100644 index 00000000..cc2488ef --- /dev/null +++ b/packages/core/src/bridge/apis/group-admin.ts @@ -0,0 +1,175 @@ +// GroupAdminApi — mute/kick/admin/card/name/title/leave + join-policy +// + add-request handling. Inlined from the previous +// `actions/group-admin.ts` (deleted alongside the rest of the +// actions/* facade in commit 13). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + Oidb0x89a_0AddOption, + Oidb0x89a_0Search, + Oidb0x8a0Req, + Oidb0x8a7Req, + Oidb0x8a7Resp, + Oidb0xf16Req, + OidbGroupRequestAction, + OidbKickMember, + OidbLeaveGroup, + OidbMuteAll, + OidbMuteMember, + OidbRenameGroup, + OidbRenameMember, + OidbSetAdmin, + OidbSpecialTitle, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +export class GroupAdminApi { + constructor(private readonly ctx: BridgeContext) {} + + async muteMember(groupId: number, userId: number, duration: number): Promise { + const bridge = asBridge(this.ctx); + const uid = await this.ctx.resolveUserUid(userId, groupId); + const env = makeOidbEnvelope(0x1253, 1, { + groupUin: groupId, type: 1, body: { targetUid: uid, duration }, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x1253_1', protobuf_encode>(env)); + } + + async muteAll(groupId: number, enable: boolean): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x89A, 0, { + groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 }, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode>(env)); + } + + async setAddOption(groupId: number, addType: number): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x89A, 0, { + groupUin: BigInt(groupId), settings: { addType }, field12: 0, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode>(env)); + } + + async setSearch(groupId: number): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x89A, 0, { + groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode>(env)); + } + + async setAddRequest( + groupId: number, sequence: number, eventType: number, + approve: boolean, reason = '', filtered = false, + ): Promise { + const bridge = asBridge(this.ctx); + const subCmd = filtered ? 2 : 1; + const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1'; + const env = makeOidbEnvelope( + 0x10C8, subCmd, + { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, + true, + ); + await runOidb(bridge, cmd, protobuf_encode>(env)); + } + + async kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise { + const bridge = asBridge(this.ctx); + const uid = await this.ctx.resolveUserUid(userId, groupId); + const env = makeOidbEnvelope(0x8A0, 1, { + groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', protobuf_encode>(env)); + } + + async kickMembers(groupId: number, userIds: number[], reject: boolean): Promise { + const bridge = asBridge(this.ctx); + const targetUids = await Promise.all(userIds.map(userId => this.ctx.resolveUserUid(userId, groupId))); + const env = makeOidbEnvelope(0x8A0, 1, { + groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', protobuf_encode>(env)); + } + + async leave(groupId: number): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x1097, 1, { groupUin: groupId }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x1097_1', protobuf_encode>(env)); + } + + async setAdmin(groupId: number, userId: number, enable: boolean): Promise { + const bridge = asBridge(this.ctx); + const uid = await this.ctx.resolveUserUid(userId, groupId); + const env = makeOidbEnvelope(0x1096, 1, { groupUin: groupId, uid, isAdmin: enable }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x1096_1', protobuf_encode>(env)); + } + + async setCard(groupId: number, userId: number, card: string): Promise { + const bridge = asBridge(this.ctx); + const uid = await this.ctx.resolveUserUid(userId, groupId); + const env = makeOidbEnvelope(0x8FC, 3, { + groupUin: groupId, body: { targetUid: uid, targetName: card }, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_3', protobuf_encode>(env)); + } + + async setName(groupId: number, name: string): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x89A, 15, { groupUin: groupId, body: { targetName: name } }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_15', protobuf_encode>(env)); + } + + async setSpecialTitle(groupId: number, userId: number, title: string): Promise { + const bridge = asBridge(this.ctx); + const uid = await this.ctx.resolveUserUid(userId, groupId); + const env = makeOidbEnvelope(0x8FC, 2, { + groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 }, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_2', protobuf_encode>(env)); + } + + /** + * The bot's local-only label for a group. Lives here rather than + * `FriendApi` because the semantic is "operate on a group" rather + * than "operate on a contact list". + */ + async setRemark(groupId: number, remark: string): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0xF16, 1, { inner: { groupId: BigInt(groupId), remark }, field12: 0 }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf16_1', protobuf_encode>(env)); + } + + async getAtAllRemain(groupId: number): Promise<{ + can_at_all: boolean; + remain_at_all_count_for_group: number; + remain_at_all_count_for_uin: number; + }> { + const bridge = asBridge(this.ctx); + const req = { + basic1: 1, + basic2: 2, + basic3: 1, + uin: BigInt(this.ctx.identity.uin), + groupId: BigInt(groupId), + type: 0, + }; + const env = makeOidbEnvelope(0x8A7, 0, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a7_0', protobuf_encode>(env)); + const result = protobuf_decode>(respBytes).body; + if (!result) throw new Error('get group at all remain result empty'); + + // Cast numbers to plain Number: the OIDB layer may surface uint32 + // as BigInt and the WebUI JSON serializer chokes on those. + return { + can_at_all: !!result.canAtAll, + remain_at_all_count_for_group: Number(result.groupRemain || 0), + remain_at_all_count_for_uin: Number(result.uinRemain || 0), + }; + } +} diff --git a/packages/core/src/bridge/apis/group-album.ts b/packages/core/src/bridge/apis/group-album.ts new file mode 100644 index 00000000..7fa80ade --- /dev/null +++ b/packages/core/src/bridge/apis/group-album.ts @@ -0,0 +1,285 @@ +// GroupAlbumApi — group photo album operations (list/upload/comment/ +// like/delete + media listing). Inlined from `actions/group-album.ts` +// and `web-actions/group-album.ts` (both deleted alongside actions/* +// in commit 13). The pure-HTTP helpers in `web/group-album.ts` stay +// where they are — they're transport-layer code, not Bridge actions. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { + DeleteMediasRequest, + DeleteMediasResponse, + DoQunCommentRequest, + DoQunCommentResponse, + DoQunLikeRequest, + DoQunLikeResponse, + GetMediaListRequest, + GetMediaListResponse, +} from '@snowluma/proto-defs/oidb-actions/group-album'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/bridge/web/group-album'; +// `getCookies` is part of WebApi — go through the hub so we don't +// duplicate the cookie acquisition flow. + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +export interface GroupAlbumMediaResult { + mediaList: any[]; + nextAttachInfo: string; +} + +export interface GroupAlbumCommentResult { + id: string; + user: { uin: string }; + content: Array<{ type: number; content: string }>; + time: string; + clientKey: string; +} + +function convertBigIntToString(obj: any): any { + if (obj === null || obj === undefined) return obj; + if (typeof obj === 'bigint') return obj.toString(); + if (Array.isArray(obj)) return obj.map(convertBigIntToString); + if (typeof obj === 'object') { + const result: any = {}; + for (const key in obj) { + result[key] = convertBigIntToString(obj[key]); + } + return result; + } + return obj; +} + +export class GroupAlbumApi { + constructor(private readonly ctx: BridgeContext) {} + + /** List a group's albums (HTTP-cookie-based, qzone.qq.com). */ + async list(groupId: number): Promise { + const groupCode = groupId.toString(); + const uin = this.ctx.identity.uin; + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + const albumData = await getGroupAlbumList(cookieObject, groupCode, uin); + return albumData?.album || []; + } + + /** Upload an image into an existing album (HTTP slice-upload). */ + async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise { + const groupCode = groupId.toString(); + const uin = this.ctx.identity.uin; + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin); + } + + async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise { + const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + + const body = protobuf_encode({ + field1: 0, + field2: new Uint8Array(0), + field3: new Uint8Array(0), + reqInfo: { + groupId: groupId.toString(), + albumId, + field3: 0, + attachInfo, + field5: '', + }, + traceId, + extMap: [{ key: 'fc-appid', value: '100' }], + }); + + const result = await this.ctx.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList', + body, + 15000, + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to get album media list'); + } + + const resp = protobuf_decode(result.responseData); + + if (resp.field1 !== 0) { + throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`); + } + + const data = resp.data ?? {}; + const mediaList = data.mediaList ?? []; + const nextAttachInfo = data.nextAttachInfo ?? ''; + + return convertBigIntToString({ mediaList, nextAttachInfo }); + } + + async comment(groupId: number, albumId: string, lloc: string, content: string): Promise { + const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + const clientKey = Date.now().toString(); + const uin = this.ctx.identity.uin; + + const body = protobuf_encode({ + field1: 8527, + field2: new Uint8Array(0), + field3: new Uint8Array(0), + body: { + groupId: groupId.toString(), + field3: 2, + reqBody: { + field1: { field3: 0, field4: '' }, + field2: { + field1: { uin }, + }, + field5: { + field1: { + field2: { + field1: 0, field2: '', + lloc, + field4: '', field6: '', field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0, + }, + }, + albumId, + field5: 0, + }, + }, + field5: { + field2: { uin }, + field3: { + field1: 0, + field2: content, + field3: '', field4: '', field5: 0, field6: '', + }, + clientKey, + }, + }, + traceId, + extMap: [{ key: 'fc-appid', value: '100' }], + }); + + const result = await this.ctx.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment', + body, + 15000, + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to comment on album media'); + } + + const resp = protobuf_decode(result.responseData); + + const resCode = resp.field1; + if (resCode !== 0 && resCode !== 8527 && !resp.comment) { + throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`); + } + + const commentData = resp.comment?.data ?? {}; + + return convertBigIntToString({ + id: commentData.id ?? '', + user: { uin: commentData.user?.uin ?? '' }, + content: commentData.content ?? [], + time: commentData.time ?? '0', + clientKey: commentData.clientKey ?? '', + }); + } + + async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise { + const uin = this.ctx.identity.uin; + const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + + const type = isLike ? 2 : 1; + const status = isLike ? 0 : 1; + + let id = ''; + if (lloc) { + id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`; + } else { + id = `421_1_0_${groupId}|${albumId}|${batchId}`; + } + + const body = protobuf_encode({ + field1: 5495, + field2: 'h5_test', + field3: 'h5_test', + body: { + type, + like: { id, status }, + publish: { + cellCommon: { + time: BigInt(Date.now()), + feedId: `422_0_${batchId}`, + }, + cellUserInfo: { + user: { uin }, + }, + cellMedia: { + albumId, + batchId: BigInt(batchId), + }, + cellQunInfo: { + qunId: groupId.toString(), + }, + }, + clientKey, + }, + extMap: [{ key: 'fc-appid', value: '100' }], + }); + + const result = await this.ctx.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike', + body, + 15000, + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to like album media'); + } + + const resp = protobuf_decode(result.responseData); + const resCode = resp.field1; + + if (resCode !== 5495) { + throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`); + } + + return convertBigIntToString(resp.body?.like ?? {}); + } + + async delete(groupId: number, albumId: string, lloc: string): Promise { + const uin = this.ctx.identity.uin; + const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + + const body = protobuf_encode({ + field1: 8694, + field2: 'h5_test', + field3: 'h5_test', + body: { + groupId: groupId.toString(), + albumId, + lloc, + }, + traceId: clientKey, + extMap: [{ key: 'fc-appid', value: '100' }], + }); + + const result = await this.ctx.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias', + body, + 15000, + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to delete album media'); + } + + const resp = protobuf_decode(result.responseData); + const resCode = resp.field1; + const errCode = resp.field2; + const errMsg = resp.field3; + + if (resCode !== 8694 || errCode) { + throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`); + } + + return { success: true }; + } +} diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts new file mode 100644 index 00000000..2af2e0f9 --- /dev/null +++ b/packages/core/src/bridge/apis/group-file.ts @@ -0,0 +1,1006 @@ +// GroupFileApi — group file CRUD + private (c2c) file upload + media +// download URL resolvers. Inlined from `actions/group-file.ts` +// (deleted alongside the rest of actions/* in commit 13). +// +// Naming: methods drop the redundant `Group`/`File` suffix where the +// area name already says it. The `Private`/`Group` axis stays +// explicit because some methods only exist for one side +// (`publish` only makes sense for group, `getPrivateUrl` only for +// c2c) — keeping them in one Api lets the few shared private helpers +// (`fetchNtv2DownloadUrl`, the upload-ext builder) live in one file. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { toHexUpper } from '@snowluma/common/hex'; +import { createLogger } from '@snowluma/common/logger'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; +import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway'; +import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/bridge/highway/utils'; +import type { FileUploadExt } from '@snowluma/proto-defs/highway'; +import { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileCountViewReq, + OidbGroupFileCountViewResp, + OidbGroupFileFolderReq, + OidbGroupFileFolderResp, + OidbGroupFileReq, + OidbGroupFileResp, + OidbGroupFileViewReq, + OidbGroupFileViewResp, + OidbGroupSendFileReq, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { + NTV2RichMediaReq, + NTV2RichMediaResp, + OidbPrivateFileDownloadReq, + OidbPrivateFileDownloadResp, + OidbPrivateFileUploadReq, + OidbPrivateFileUploadResp, +} from '@snowluma/proto-defs/oidb-actions/media'; +import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared'; + +const log = createLogger('GroupFile'); + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +// ─────────────── public result types ─────────────── + +export interface GroupFileInfo { + fileId: string; + fileName: string; + busId: number; + fileSize: number; + uploadTime: number; + deadTime: number; + modifyTime: number; + downloadTimes: number; + uploader: number; + uploaderName: string; +} + +export interface GroupFolderInfo { + folderId: string; + folderName: string; + createTime: number; + creator: number; + creatorName: string; + totalFileCount: number; +} + +export interface GroupFilesResult { + files: GroupFileInfo[]; + folders: GroupFolderInfo[]; +} + +export interface UploadFileResult { + fileId: string | null; + fileHash?: string | null; +} + +// Re-export so callers don't have to dig into apis/shared. +export type { MediaIndexNode } from './shared'; + +// ─────────────── file-specific helpers ─────────────── + +function normalizeDirectory(dir?: string): string { + if (!dir || !dir.trim()) return '/'; + return dir; +} + +function bytesToHexUpper(data: unknown): string { + if (!(data instanceof Uint8Array) || data.length === 0) return ''; + return toHexUpper(data); +} + +// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives +// little-endian-packed (byte0 = first dotted octet) and we unpack it the +// same way. Force-unsigned the shift to keep negative ints (high bit set) +// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000 +// into a negative number. +function int32ToIpv4Dotted(value: number): string { + const b1 = value & 0xFF; + const b2 = (value >>> 8) & 0xFF; + const b3 = (value >>> 16) & 0xFF; + const b4 = (value >>> 24) & 0xFF; + return `${b1}.${b2}.${b3}.${b4}`; +} + +function normalizeUploadFileName(name: string, fallback: string): string { + const trimmed = name.trim(); + if (trimmed) return trimmed; + const safeFallback = fallback.trim(); + return safeFallback || 'file.bin'; +} + +function md5First10MB(bytes: Uint8Array): Uint8Array { + const limit = Math.min(bytes.length, 10 * 1024 * 1024); + return computeMd5(bytes.subarray(0, limit)); +} + +function buildGroupFileUploadExt( + senderUin: number, + groupId: number, + fileName: string, + fileSize: number, + md5: Uint8Array, + fileId: string, + uploadKey: Uint8Array, + checkKey: Uint8Array, + uploadHost: string, + uploadPort: number, +): Uint8Array { + return protobuf_encode({ + unknown1: 100, + unknown2: 1, + entry: { + busiBuff: { + busId: 102, + senderUin: BigInt(senderUin), + receiverUin: BigInt(groupId), + groupCode: BigInt(groupId), + }, + fileEntry: { + fileSize: BigInt(Math.max(0, fileSize)), + md5, + md5S2: md5, + checkKey, + fileId, + uploadKey, + }, + clientInfo: { + clientType: 3, + appId: '100', + terminalType: 3, + clientVer: '1.1.1', + unknown: 4, + }, + fileNameInfo: { + fileName, + }, + host: { + hosts: [ + { + url: { + host: uploadHost, + unknown: 1, + }, + port: uploadPort, + }, + ], + }, + }, + unknown200: 0, + }); +} + +function buildPrivateFileUploadExt( + senderUin: number, + fileName: string, + fileSize: number, + md5: Uint8Array, + sha1: Uint8Array, + fileId: string, + uploadKey: Uint8Array, + uploadHost: string, + uploadPort: number, +): Uint8Array { + return protobuf_encode({ + unknown1: 100, + unknown2: 1, + entry: { + busiBuff: { + busId: 102, + senderUin: BigInt(senderUin), + receiverUin: 0n, + groupCode: 0n, + }, + fileEntry: { + fileSize: BigInt(Math.max(0, fileSize)), + md5, + md5S2: md5, + checkKey: sha1, + fileId, + uploadKey, + }, + clientInfo: { + clientType: 3, + appId: '100', + terminalType: 3, + clientVer: '1.1.1', + unknown: 4, + }, + fileNameInfo: { + fileName, + }, + host: { + hosts: [ + { + url: { + host: uploadHost, + unknown: 1, + }, + port: uploadPort, + }, + ], + }, + }, + unknown3: 0, + unknown200: 1, + }); +} + +function normalizeMediaNode(node: MediaIndexNode): Record { + const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : ''; + if (!fileUuid) throw new Error('media node fileUuid is required'); + + const info = node.info ?? {}; + const type = info.type ?? {}; + + return { + info: { + fileSize: toInt(info.fileSize), + fileHash: typeof info.fileHash === 'string' ? info.fileHash : '', + fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '', + fileName: typeof info.fileName === 'string' ? info.fileName : '', + type: { + type: toInt(type.type), + picFormat: toInt(type.picFormat), + videoFormat: toInt(type.videoFormat), + voiceFormat: toInt(type.voiceFormat), + }, + width: toInt(info.width), + height: toInt(info.height), + time: toInt(info.time), + original: toInt(info.original), + }, + fileUuid, + storeId: toInt(node.storeId), + uploadTime: toInt(node.uploadTime), + ttl: toInt(node.ttl), + subType: toInt(node.subType), + }; +} + +async function fetchNtv2DownloadUrl( + bridge: Bridge, + serviceCmd: string, + oidbCmd: number, + payload: Record, +): Promise { + const env = makeOidbEnvelope(oidbCmd, 200, payload as any, true); + const respBytes = await runOidb(bridge, serviceCmd, protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined); + const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : ''; + const path = typeof resp?.download?.info?.urlPath === 'string' ? resp.download.info.urlPath : ''; + const rKeyParam = typeof resp?.download?.rKeyParam === 'string' ? resp.download.rKeyParam : ''; + + if (!domain || !path) { + throw new Error('ntv2 download response invalid'); + } + return `https://${domain}${path}${rKeyParam}`; +} + +export class GroupFileApi { + constructor(private readonly ctx: BridgeContext) {} + + // ─────────────── publish (group file → chat) ─────────────── + + /** + * Publish a previously-uploaded group file as a chat message. + * + * Wire is OIDB `OidbSvcTrpcTcp.0x6d9_4` — NOT `MessageSvc.PbSendMsg`. + * Lagrange.Core V2 splits these two roles: the file UPLOAD path goes + * via 0x6D6_0 + highway PUT, then a SECOND OIDB hop (this one) tells + * the QQ server "now publish that staged blob as a chat message" so + * everyone in the group can see the file bubble. + * + * The old approach — wrap the file as `TransElem(elemType=24)` inside + * `richText.elems[]` and ship it via PbSendMsg — works for INCOMING + * messages (the receive decoder unpacks transElem(24) into a + * FileEntity) but the QQ-NT server REJECTS it on outgoing with + * `result=79` ("invalid element on send-side"). Mirror Lagrange's + * dedicated GroupSendFileService instead. + * + * The unused `field4` slot and the `field3=random` value match + * Lagrange's send-side defaults (`OidbSvcTrpcTcp0x6D9_4.cs` + the + * `Random.Shared.Next()` call in `GroupSendFileService.cs`). Field 5 + * is the `Field5=true` flag the receiver's deserializer expects. + */ + async publish(groupId: number, fileId: string): Promise { + if (!fileId) throw new Error('publish requires fileId'); + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x6D9, 4, { + body: { + groupUin: groupId, + type: 2, + info: { + busiType: 102, + fileId, + field3: Math.floor(Math.random() * 0x7fffffff) >>> 0, + field5: true, + }, + }, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d9_4', protobuf_encode>(env)); + } + + // ─────────────── count ─────────────── + + async getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D8, 3, + { count: { groupUin: groupId, appId: 7, busId: 0 } }, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + return { + fileCount: toInt(resp?.count?.fileCount ?? 0), + maxCount: toInt(resp?.count?.maxCount ?? 10000), + }; + } + + // ─────────────── upload ─────────────── + + async upload( + groupId: number, + source: string, + name = '', + folderId = '/', + uploadFile = true, + ): Promise { + const bridge = asBridge(this.ctx); + // Group/private files may legitimately be up to 4 GiB on QQ's wire, + // so override the default 1 GiB cap with the protocol ceiling. + const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); + if (!loaded.bytes.length) throw new Error('group file is empty'); + + const fileName = normalizeUploadFileName(name, loaded.fileName); + const hashes = computeHashes(loaded.bytes); + + const env = makeOidbEnvelope( + 0x6D6, 0, + { + file: { + groupUin: groupId, + appId: 4, + busId: 102, + entrance: 6, + targetDirectory: normalizeDirectory(folderId), + fileName, + localDirectory: `/${fileName}`, + fileSize: BigInt(loaded.bytes.length), + fileSha1: hashes.sha1, + fileSha3: new Uint8Array(0), + fileMd5: hashes.md5, + field15: true, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const upload = resp?.upload; + if (!upload) throw new Error('group file upload response missing'); + ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording); + + const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null; + if (!fileId) throw new Error('group file upload response missing file_id'); + + // Remember the upload so a later `send_group_msg` carrying just the + // file_id can route via `publish` without forcing the OneBot caller + // to thread fileName/size/md5 separately. For groups the wire + // publish (OIDB 0x6d9_4) only needs the file_id itself, so this is + // mainly for log-line correctness; the c2c counterpart in + // `uploadPrivate` is where the cache is actually load-bearing. + this.ctx.rememberUploadedFile({ + fileId, + scope: 'group', + groupId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileSha1: hashes.sha1, + rememberedAt: Date.now(), + }); + + if (!upload.boolFileExist && uploadFile) { + const senderUin = toInt(this.ctx.identity.uin); + if (senderUin <= 0) throw new Error('invalid self uin for group file upload'); + + const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp) + || (typeof upload.serverDns === 'string' && upload.serverDns) + || ''; + const uploadPort = toInt(upload.uploadPort); + if (!uploadHost || uploadPort <= 0) { + throw new Error('group file upload host is invalid'); + } + + const ext = buildGroupFileUploadExt( + senderUin, + groupId, + fileName, + loaded.bytes.length, + hashes.md5, + fileId, + upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0), + upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0), + uploadHost, + uploadPort, + ); + + const session = await fetchHighwaySession(bridge); + await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext); + } + + // Stage 3: file is on the server, now publish it as a chat message. + // + // Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes — + // the chat shows nothing. The publish step goes via a dedicated OIDB + // call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24) + // payload — the QQ-NT server rejects that with `result=79`. Mirrors + // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the + // caller opts out via `uploadFile=false` (treat that as "I only + // wanted the slot allocated, hold the chat post"). Routes through + // `this.publish` so tests can mock at the same Api boundary. + if (uploadFile) { + try { + await this.publish(groupId, fileId); + } catch (err) { + // The bytes are already on the server and the fileId is valid — + // fail loud but don't lose the upload result the action handler + // committed to returning. Callers can still resolve the file by + // id; they'll just have to re-publish it themselves. + log.warn('group file uploaded (fileId=%s) but chat post failed: %s', + fileId, err instanceof Error ? err.message : String(err)); + } + } + + return { fileId }; + } + + async uploadPrivate( + userId: number, + source: string, + name = '', + uploadFile = true, + ): Promise { + const bridge = asBridge(this.ctx); + // Group/private files may legitimately be up to 4 GiB on QQ's wire, + // so override the default 1 GiB cap with the protocol ceiling. + const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); + if (!loaded.bytes.length) throw new Error('private file is empty'); + + const targetUid = await this.ctx.resolveUserUid(userId); + let selfUid = this.ctx.identity.selfUid; + if (!selfUid) { + const selfUin = toInt(this.ctx.identity.uin); + if (selfUin > 0) { + selfUid = await this.ctx.resolveUserUid(selfUin); + } + } + if (!selfUid) throw new Error('self uid is unavailable'); + + const senderUin = toInt(this.ctx.identity.uin); + if (senderUin <= 0) throw new Error('invalid self uin for private file upload'); + + const fileName = normalizeUploadFileName(name, loaded.fileName); + const hashes = computeHashes(loaded.bytes); + + const env = makeOidbEnvelope(0xE37, 1700, { + command: 1700, + seq: 0, + upload: { + senderUid: selfUid, + receiverUid: targetUid, + fileSize: loaded.bytes.length, + fileName, + md510MCheckSum: md5First10MB(loaded.bytes), + sha1CheckSum: hashes.sha1, + localPath: '/', + md5CheckSum: hashes.md5, + sha3CheckSum: new Uint8Array(0), + }, + businessId: 3, + clientType: 1, + flagSupportMediaPlatform: 1, + }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const upload = resp?.upload; + if (!upload) throw new Error('private file upload response missing'); + ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined); + + const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null; + const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null; + if (!fileId) throw new Error('private file upload response missing file_id'); + + // Cache the metadata so a later `send_private_msg` carrying just + // `{type:'file', file_id}` can resurrect the full c2c-file packet + // (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without + // this the recipient sees a 0-byte file because the OneBot send path + // has no way to recover those fields from the file_id alone. + this.ctx.rememberUploadedFile({ + fileId, + scope: 'private', + userId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileSha1: hashes.sha1, + fileHash: fileHash ?? '', + rememberedAt: Date.now(), + }); + + if (!upload.boolFileExist && uploadFile) { + // Host selection. + // + // Current QQ-NT server rollout has stopped populating the legacy + // `uploadIp` (field 60) entirely. The host now arrives as the first + // entry of `rtpMediaPlatformUploadAddress` (field 210, repeated + // IPv4 message) — same place acidify reads it from since their + // 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort` + // (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN); + // acidify uses `inIP`/`inPort` exclusively and so do we, because + // that's the address the highway PUT actually needs to reach. + // + // The 32-bit IPs are little-endian-packed (byte0 = first octet) + // per acidify's `Int.toIpString()`. Cross-checked the byte order + // by inspecting their highway flow — there's no separate htonl + // step, so the integer is already in network-octet-first order. + // + // Older server versions still populate the legacy string fields + // (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain / + // uploadDns), so we fall through to those after rtpMediaPlatform. + // Pair an HTTPS-flavored host with `uploadHttpsPort` if that's + // what we picked. + const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress) + && upload.rtpMediaPlatformUploadAddress[0]) + ? upload.rtpMediaPlatformUploadAddress[0] : null; + const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0 + ? int32ToIpv4Dotted(rtpFirst.inIP) : ''; + const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number' + ? rtpFirst.inPort : 0; + const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0]) + ? upload.uploadIpList[0] : ''; + const uploadHost = (rtpInIP) + || (typeof upload.uploadIp === 'string' && upload.uploadIp) + || (typeof upload.uploadDomain === 'string' && upload.uploadDomain) + || (ipListFirst) + || (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain) + || (typeof upload.uploadDns === 'string' && upload.uploadDns) + || ''; + const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst + && typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain; + const uploadPort = rtpInIP && rtpInPort > 0 + ? rtpInPort + : httpsHostUsed && toInt(upload.uploadHttpsPort) > 0 + ? toInt(upload.uploadHttpsPort) + : toInt(upload.uploadPort); + if (!uploadHost || uploadPort <= 0) { + // Surface every host-bearing field we know about so a user + // hitting this can show us exactly which slot the server filled + // (or whether it returned nothing at all — which would point at + // a request mismatch rather than a missing decoder). + const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress) + ? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e: any) => ({ + outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort, + iPType: e.iPType, + }))) + : '[]'; + log.warn( + 'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s', + rtpDump, + upload.uploadIp ?? '', upload.uploadDomain ?? '', + JSON.stringify(upload.uploadIpList ?? []), + upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '', + upload.uploadLanip ?? '', upload.uploadPort ?? 0, + upload.uploadHttpsPort ?? 0, + ); + throw new Error('private file upload host is invalid'); + } + + const ext = buildPrivateFileUploadExt( + senderUin, + fileName, + loaded.bytes.length, + hashes.md5, + hashes.sha1, + fileId, + upload.mediaPlatformUploadKey instanceof Uint8Array + ? upload.mediaPlatformUploadKey + : (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)), + uploadHost, + uploadPort, + ); + + const session = await fetchHighwaySession(bridge); + await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext); + } + + // Stage 3: publish the file as a c2c chat message. C2C files use + // `RichText.notOnlineFile` (parallel to `elems`), so we go through + // the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate` + // which only knows about elems[]. NapCat does the same atomic + // upload+send dance — without it the file sits on the server and + // the recipient sees nothing. + if (uploadFile) { + try { + await this.ctx.apis.message.sendC2cFile(userId, targetUid, { + fileId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileHash: fileHash ?? '', + }); + } catch (err) { + log.warn('private file uploaded (fileId=%s) but chat post failed: %s', + fileId, err instanceof Error ? err.message : String(err)); + } + } + + return { fileId, fileHash }; + } + + // ─────────────── list ─────────────── + + async list(groupId: number, folderId = '/'): Promise { + const bridge = asBridge(this.ctx); + const targetDirectory = normalizeDirectory(folderId); + const files: GroupFileInfo[] = []; + const folders: GroupFolderInfo[] = []; + + const pageSize = 20; + let startIndex = 0; + for (let page = 0; page < 200; page++) { + const env = makeOidbEnvelope( + 0x6D8, 1, + { + list: { + groupUin: groupId, + appId: 7, + targetDirectory, + fileCount: pageSize, + sortBy: 1, + startIndex, + field17: 2, + field18: 0, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_1', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const list = resp?.list; + if (!list) break; + ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording); + + for (const item of list.items ?? []) { + const type = toInt(item?.type); + if (type === 1 && item?.fileInfo) { + const file = item.fileInfo; + const uploader = toInt(file.uploaderUin); + const cached = this.ctx.identity.findGroupMember(groupId, uploader); + files.push({ + fileId: typeof file.fileId === 'string' ? file.fileId : '', + fileName: typeof file.fileName === 'string' ? file.fileName : '', + busId: toInt(file.busId), + fileSize: toInt(file.fileSize), + uploadTime: toInt(file.uploadedTime), + deadTime: toInt(file.expireTime), + modifyTime: toInt(file.modifiedTime), + downloadTimes: toInt(file.downloadedTimes), + uploader, + uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName) + || cached?.card + || cached?.nickname + || '', + }); + } else if (type === 2 && item?.folderInfo) { + const folder = item.folderInfo; + const creator = toInt(folder.creatorUin); + const cached = this.ctx.identity.findGroupMember(groupId, creator); + folders.push({ + folderId: typeof folder.folderId === 'string' ? folder.folderId : '', + folderName: typeof folder.folderName === 'string' ? folder.folderName : '', + createTime: toInt(folder.createTime), + creator, + creatorName: (typeof folder.creatorName === 'string' && folder.creatorName) + || cached?.card + || cached?.nickname + || '', + totalFileCount: toInt(folder.totalFileCount), + }); + } + } + + if (list.isEnd) break; + startIndex += pageSize; + } + + return { files, folders }; + } + + // ─────────────── url fetch (group / private files) ─────────────── + + async getUrl(groupId: number, fileId: string, busId = 102): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D6, 2, + { + download: { + groupUin: groupId, + appId: 7, + busId, + fileId, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const download = resp?.download; + if (!download) throw new Error('group file url response missing'); + ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording); + + const dns = (typeof download.downloadDns === 'string' && download.downloadDns) + || (typeof download.downloadIp === 'string' && download.downloadIp) + || ''; + const hexUrl = bytesToHexUpper(download.downloadUrl); + if (!dns || !hexUrl) { + throw new Error('group file url response invalid'); + } + + // Keep the same behavior as Lagrange: append file_id after ?fname= + return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`; + } + + async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise { + const bridge = asBridge(this.ctx); + const selfUid = await resolveSelfUid(bridge); + void userId; + const env = makeOidbEnvelope(0xE37, 1200, { + subCommand: 1200, + field2: 1, + body: { + receiverUid: selfUid, + fileUuid: fileId, + type: 2, + fileHash, + t2: 0, + }, + field101: 3, + field102: 103, + field200: 1, + field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), + }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1200', protobuf_encode>(env), 5000); + const resp = protobuf_decode>(respBytes).body; + + const result = resp?.body?.result; + const server = typeof result?.server === 'string' ? result.server : ''; + const port = toInt(result?.port); + const url = typeof result?.url === 'string' ? result.url : ''; + if (!server || !port || !url) { + throw new Error('private file url response invalid'); + } + return `http://${server}:${port}${url}&isthumb=0`; + } + + // ─────────────── delete / move ─────────────── + + async delete(groupId: number, fileId: string): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D6, 3, + { + delete: { + groupUin: groupId, + busId: 102, + fileId, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const result = resp?.delete; + if (!result) throw new Error('group file delete response missing'); + ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording); + } + + async move( + groupId: number, + fileId: string, + parentDirectory: string, + targetDirectory: string, + ): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D6, 5, + { + move: { + groupUin: groupId, + appId: 7, + busId: 102, + fileId, + parentDirectory, + targetDirectory, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const result = resp?.move; + if (!result) throw new Error('group file move response missing'); + ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording); + } + + // ─────────────── folders ─────────────── + + async createFolder(groupId: number, name: string, parentId = '/'): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D7, 0, + { + create: { + groupUin: groupId, + rootDirectory: normalizeDirectory(parentId), + folderName: name, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const result = resp?.create; + if (!result) throw new Error('group folder create response missing'); + ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording); + } + + async deleteFolder(groupId: number, folderId: string): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D7, 1, + { + delete: { + groupUin: groupId, + folderId, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const result = resp?.delete; + if (!result) throw new Error('group folder delete response missing'); + ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording); + } + + async renameFolder(groupId: number, folderId: string, newFolderName: string): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope( + 0x6D7, 2, + { + rename: { + groupUin: groupId, + folderId, + newFolderName, + }, + }, + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const result = resp?.rename; + if (!result) throw new Error('group folder rename response missing'); + ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording); + } + + // ─────────────── rich-media URL by node ─────────────── + + async getPttUrl(groupId: number, node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + const normalizedNode = normalizeMediaNode(node); + return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, { + reqHead: { + common: { requestId: 4, command: 200 }, + scene: { + requestType: 1, + businessType: 3, + sceneType: 2, + group: { groupUin: groupId }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizedNode, + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); + } + + async getPrivatePttUrl(node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + const selfUid = await resolveSelfUid(bridge); + const normalizedNode = normalizeMediaNode(node); + return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, { + reqHead: { + common: { requestId: 1, command: 200 }, + scene: { + requestType: 1, + businessType: 3, + sceneType: 1, + c2c: { + accountType: 2, + targetUid: selfUid, + }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizedNode, + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); + } + + async getVideoUrl(groupId: number, node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + const normalizedNode = normalizeMediaNode(node); + return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, { + reqHead: { + common: { requestId: 1, command: 200 }, + scene: { + requestType: 2, + businessType: 2, + sceneType: 2, + group: { groupUin: groupId }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizedNode, + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); + } + + async getPrivateVideoUrl(node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + const selfUid = await resolveSelfUid(bridge); + const normalizedNode = normalizeMediaNode(node); + return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, { + reqHead: { + common: { requestId: 1, command: 200 }, + scene: { + requestType: 2, + businessType: 2, + sceneType: 1, + c2c: { + accountType: 2, + targetUid: selfUid, + }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizedNode, + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); + } +} diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/bridge/apis/index.ts new file mode 100644 index 00000000..4407a927 --- /dev/null +++ b/packages/core/src/bridge/apis/index.ts @@ -0,0 +1,101 @@ +// ApiHub — the per-instance bag of typed Api classes hanging off +// `bridge.apis`. Mirrors NapCat's `NapCatCore.apis = { MsgApi, …}` +// pattern but uses camelCase keys (`apis.message.sendGroup`) to match +// the rest of the SnowLuma TypeScript style. +// +// Each Api class is constructed once when the parent `Bridge` is +// constructed (eager — every account that connects gets its own +// `apis.*` set immediately). Api classes receive a `BridgeContext` +// reference, NOT the concrete `Bridge`, so they remain easy to mock +// without standing up a full Bridge instance. +// +// Adding a new Api: +// 1. Create `bridge/apis/.ts` exporting a `class XxxApi`. +// 2. Add a property here. +// 3. Construct it inside `buildApiHub(ctx)` below. +// 4. Move the relevant methods OFF Bridge and onto the new Api. +// +// All 12 Api hubs are now live (#6 commits 1-12). The interface lists +// every typed area an OneBot caller can reach via `bridge.apis.*`. + +import type { BridgeContext } from '../bridge-context'; +import { ContactsApi } from './contacts'; +import { ExtrasApi } from './extras'; +import { ForwardApi } from './forward'; +import { FriendApi } from './friend'; +import { GroupAdminApi } from './group-admin'; +import { GroupAlbumApi } from './group-album'; +import { GroupFileApi } from './group-file'; +import { InteractionApi } from './interaction'; +import { MessageApi } from './message'; +import { MiscApi } from './misc'; +import { ProfileApi } from './profile'; +import { WebApi } from './web'; + +export interface ApiHub { + /** Send/recall/markRead operations across c2c + group + c2c-file. */ + readonly message: MessageApi; + /** Friend / group / member roster + user-profile + group-request-list + download-rkey. */ + readonly contacts: ContactsApi; + /** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */ + readonly groupAdmin: GroupAdminApi; + /** Group file CRUD + private (c2c) file upload + media URL resolvers. */ + readonly groupFile: GroupFileApi; + /** Group photo album: list/upload/comment/like/delete + media listing. */ + readonly groupAlbum: GroupAlbumApi; + /** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */ + readonly interaction: InteractionApi; + /** Friend roster mutations: handleRequest / delete / setRemark. */ + readonly friend: FriendApi; + /** Personal profile: status / avatar / nickname / likes / custom-faces. */ + readonly profile: ProfileApi; + /** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */ + readonly forward: ForwardApi; + /** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */ + readonly misc: MiscApi; + /** Tier-2 napcat-parity: group todo / stranger status / AI voice. */ + readonly extras: ExtrasApi; + /** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */ + readonly web: WebApi; +} + +/** + * Construct the ApiHub for a Bridge. Called once from the Bridge + * constructor. Eager construction means every Bridge instance pays + * the cost up-front (a few object allocations) — there's no lazy + * path because that would require either a thunk-based wrapper or + * runtime-mutated `apis.xxx` slots, neither of which is worth the + * complexity for ~13 small classes. + */ +export function buildApiHub(ctx: BridgeContext): ApiHub { + return { + message: new MessageApi(ctx), + contacts: new ContactsApi(ctx), + groupAdmin: new GroupAdminApi(ctx), + groupFile: new GroupFileApi(ctx), + groupAlbum: new GroupAlbumApi(ctx), + interaction: new InteractionApi(ctx), + friend: new FriendApi(ctx), + profile: new ProfileApi(ctx), + forward: new ForwardApi(ctx), + misc: new MiscApi(ctx), + extras: new ExtrasApi(ctx), + web: new WebApi(ctx), + }; +} + +// Re-export the Api classes themselves so callers can write +// `import type { MessageApi } from '@snowluma/core/.../apis'` for +// signature use. Concrete instances always come from `bridge.apis.*`. +export { ContactsApi } from './contacts'; +export { ExtrasApi } from './extras'; +export { ForwardApi } from './forward'; +export { FriendApi } from './friend'; +export { GroupAdminApi } from './group-admin'; +export { GroupAlbumApi } from './group-album'; +export { GroupFileApi } from './group-file'; +export { InteractionApi } from './interaction'; +export { MessageApi } from './message'; +export { MiscApi } from './misc'; +export { ProfileApi } from './profile'; +export { WebApi } from './web'; diff --git a/packages/core/src/bridge/apis/interaction.ts b/packages/core/src/bridge/apis/interaction.ts new file mode 100644 index 00000000..a77a6086 --- /dev/null +++ b/packages/core/src/bridge/apis/interaction.ts @@ -0,0 +1,95 @@ +// InteractionApi — interactive engagement primitives (poke / like / +// reaction / essence / emoji-like-list). Inlined from +// `actions/interaction.ts` + the lone-survivor `setGroupEssence` from +// `actions/group-message.ts` (both deleted alongside actions/* in +// commit 13). The recall+markRead halves of `group-message.ts` were +// already absorbed into `MessageApi` back in commit 1. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + Oidb0x9083Req, + Oidb0x9083Resp, + OidbEssence, + OidbGroupReaction, + OidbLike, + OidbPoke, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +export class InteractionApi { + constructor(private readonly ctx: BridgeContext) {} + + async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0xED3, 1, { + uin: targetUin ?? peerUin, + groupUin: isGroup ? peerUin : 0, + friendUin: isGroup ? 0 : peerUin, + ext: 0, + }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xed3_1', protobuf_encode>(env)); + } + + async sendLike(userId: number, count: number): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x7E5, 104, { targetUin: userId, count }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x7e5_104', protobuf_encode>(env)); + } + + async setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise { + const bridge = asBridge(this.ctx); + const subCmd = isSet ? 1 : 2; + const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2'; + // Same heuristic Lagrange.Core V2 uses (`GroupAddReactionEvent.IsEmoji`): + // QQ face ids are 1–3 digits ("76") → type=1, unicode codepoints are + // longer ("128516") → type=2. Server reads the type at field 5; sending + // it at the wrong field number triggers + // "invalid ReqBody.EmojiType: value must be greater than 0". + const type = code.length > 3 ? 2 : 1; + const env = makeOidbEnvelope(0x9082, subCmd, { + groupUin: groupId, sequence, code, type, field6: false, field7: false, + }); + await runOidb(bridge, cmd, protobuf_encode>(env)); + } + + async setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise { + const bridge = asBridge(this.ctx); + const subCmd = enable ? 1 : 2; + const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2'; + const env = makeOidbEnvelope(0xEAC, subCmd, { groupUin: groupId, sequence, random }); + await runOidb(bridge, cmd, protobuf_encode>(env)); + } + + async getEmojiLikes( + groupId: number, + sequence: number, + emojiId: string, + emojiType = 1, + count = 10, + cookie = '', + ): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> { + const bridge = asBridge(this.ctx); + const req: any = { + groupId: BigInt(groupId), + sequence, + emojiType, + emojiId, + cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0), + field7: 0, + count, + field12: 1, + }; + const env = makeOidbEnvelope(0x9083, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + const uin = resp?.inner?.userInfo?.uin; + const users = uin ? [{ uin: Number(uin) }] : []; + const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : ''; + return { users, cookie: respCookie, isLast: !respCookie }; + } +} diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts new file mode 100644 index 00000000..0e2aea0a --- /dev/null +++ b/packages/core/src/bridge/apis/message.ts @@ -0,0 +1,345 @@ +// MessageApi — send / recall / mark-read operations. +// +// Folds together the previous shapes: +// - `Bridge.sendGroupMessage` / `sendPrivateMessage` / `sendC2cFileMessage` +// (formerly inline on the Bridge class). +// - `actions/group-message.ts` (recallGroup / recallPrivate / +// markGroupRead / markPrivateRead). +// +// All implementations are inlined here — the previous indirection +// through `actions/group-message.ts` exported functions was just +// `(bridge, args) → method body`; once methods live on a typed Api +// class the wrapper layer doesn't earn its keep. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { + SendMessageRequest, + SendMessageResponse, +} from '@snowluma/proto-defs/action'; +import type { FileExtra } from '@snowluma/proto-defs/message'; +import type { + C2CRecallRequest, + GroupRecallRequest, + SsoReadedReportReq, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { MessageElement } from '@snowluma/bridge/events'; +import { buildSendElems } from '@snowluma/bridge/element-builder'; +import type { BridgeContext } from '../bridge-context'; +// `Bridge` is imported as a type only so we can narrow `ctx` back to +// the concrete Bridge instance when passing it to `buildSendElems` +// (which still takes `Bridge` because the highway upload helpers it +// transitively calls each take `Bridge` — refactoring those is a +// separate concern that doesn't need to land alongside the Api split). +// +// At runtime `ctx` IS the Bridge instance that constructed this +// MessageApi — `buildApiHub(ctx)` passes the Bridge itself. +import type { Bridge, SendMessageReceipt } from '../bridge'; + +const SEND_MSG_CMD = 'MessageSvc.PbSendMsg'; + +export class MessageApi { + constructor(private readonly ctx: BridgeContext) {} + + /** + * Send a message to a QQ group. + * + * Wraps `MessageSvc.PbSendMsg` with `routingHead.grp.groupCode`. + * Media elements (image / record / video) trigger highway uploads + * inside `buildSendElems` — see `element-builder.ts`. + * + * Returns a `SendMessageReceipt` carrying the assigned messageId, + * group sequence, and timestamps; callers cache this for later + * `recall` / reply lookups. + */ + async sendGroup(groupId: number, elements: MessageElement[]): Promise { + if (elements.length === 0) throw new Error('message is empty'); + + const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, groupId }); + const random = this.ctx.nextMessageRandom(); + + const request = protobuf_encode({ + routingHead: { + grp: { groupCode: BigInt(groupId) }, + }, + contentHead: { + type: 1, + }, + messageBody: { + richText: { + elems: protoElems, + }, + } as any, + clientSequence: 0, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + multiSendSeq: 0, + }); + + const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`); + } + + const response = protobuf_decode(result.responseData); + if (!response) throw new Error('failed to decode SendMessageResponse'); + if (response.result != null && response.result !== 0) { + throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`); + } + + const seq = response.groupSequence ?? 0; + const messageId = (random & 0x7FFFFFFF) || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: 0, random, timestamp }; + } + + /** + * Send a c2c (private) message. + * + * Resolves the recipient's UID only when the message carries media + * — text-only messages skip the lookup. Routes through `c2c.uin` + * (and optionally `c2c.uid` for the media case). + */ + async sendPrivate(userUin: number, elements: MessageElement[]): Promise { + if (elements.length === 0) throw new Error('message is empty'); + + let userUid = ''; + const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'); + if (hasMedia) { + userUid = await this.ctx.resolveUserUid(userUin); + } + + const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid }); + const random = this.ctx.nextMessageRandom(); + const clientSeq = this.ctx.nextClientSequence(); + + const request = protobuf_encode({ + routingHead: { + c2c: { + uin: userUin, + ...(userUid ? { uid: userUid } : {}), + }, + }, + contentHead: { + type: 1, + subType: 0, + c2cCmd: 11, + }, + messageBody: { + richText: { + elems: protoElems, + }, + } as any, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { + msgFlag: Math.floor(Date.now() / 1000), + }, + multiSendSeq: 0, + }); + + const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`); + } + + const response = protobuf_decode(result.responseData); + if (!response) throw new Error('failed to decode SendMessageResponse'); + if (response.result != null && response.result !== 0) { + throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`); + } + + const seq = response.privateSequence ?? 0; + const messageId = (random & 0x7FFFFFFF) || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; + } + + /** + * Send a c2c file as a chat message. + * + * The wire shape isn't the same as a regular c2c message — the c2c + * file path uses three slots that differ from a normal text/image + * send (verified against `dev/Lagrange.Core/.../MessagePacker.cs: + * BuildPacketBase` + `FileEntity.PackMessageContent`): + * + * 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of + * `routingHead.c2c { uin, uid }`. The server rejects c2c file + * messages routed through the regular c2c slot. + * 2. `messageBody.msgContent` carries the serialised + * `FileExtra { file: NotOnlineFile }` bytes. NOT + * `richText.notOnlineFile` — the receiver doesn't read that + * slot for file metadata. + * 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The + * previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT + * server doesn't recognise. + * + * NotOnlineFile carries three required-on-send fields the receiver + * itself ignores but the server's intake validator checks: + * - `subcmd: 1` — c2c file send command code + * - `dangerEvel: 0` — virus-scan severity, always 0 client-side + * - `expireTime` — 7 days from now (Lagrange convention) + */ + async sendC2cFile( + userUin: number, + userUid: string, + info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string }, + ): Promise { + const random = this.ctx.nextMessageRandom(); + const clientSeq = this.ctx.nextClientSequence(); + + const nowSec = Math.floor(Date.now() / 1000); + const sevenDaysSec = 7 * 24 * 60 * 60; + const fileExtraBytes = protobuf_encode({ + file: { + fileType: 0, + fileUuid: info.fileId, + fileMd5: info.fileMd5, + fileName: info.fileName, + fileSize: BigInt(info.fileSize), + subcmd: 1, + dangerEvel: 0, + expireTime: nowSec + sevenDaysSec, + fileHash: info.fileHash ?? '', + }, + }); + + const request = protobuf_encode({ + routingHead: { + trans0x211: { ccCmd: 4, uid: userUid }, + }, + contentHead: { + type: 1, + subType: 0, + }, + messageBody: { + msgContent: fileExtraBytes, + }, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { msgFlag: nowSec }, + multiSendSeq: 0, + }); + + // `userUin` is part of the public contract (the OneBot layer + // threads it through for symmetry with `sendPrivate`) but the + // wire shape only needs the uid. Silence the unused-parameter + // lint without changing the signature. + void userUin; + + const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`); + } + const response = protobuf_decode(result.responseData); + if (!response) throw new Error('failed to decode SendMessageResponse'); + if (response.result != null && response.result !== 0) { + throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`); + } + const seq = response.privateSequence ?? 0; + const messageId = (random & 0x7FFFFFFF) || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; + } + + /** + * Recall (revoke) a group message by sequence number. Server-side + * the message ages out after the standard 2-minute window unless + * the user is an admin/owner. + */ + async recallGroup(groupId: number, sequence: number): Promise { + const request = protobuf_encode({ + type: 1, + groupUin: groupId, + info: { sequence, random: 0, field3: 0 }, + settings: { field1: 0 }, + }); + const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request); + if (!result.success) throw new Error(result.errorMessage || 'recall group message failed'); + } + + /** + * Recall a c2c (private) message. Needs more positional info than + * the group variant because c2c messages are identified by the + * `(clientSequence, msgSequence, random, timestamp)` tuple rather + * than a single group-side sequence. + */ + async recallPrivate( + userUin: number, + clientSeq: number, + msgSeq: number, + random: number, + timestamp: number, + ): Promise { + const targetUid = await this.ctx.resolveUserUid(userUin); + const request = protobuf_encode({ + type: 1, + targetUid, + info: { + clientSequence: clientSeq, + random, + messageId: BigInt((0x01000000 * 0x100000000) + random), + timestamp, + field5: 0, + messageSequence: msgSeq, + }, + settings: { field1: false, field2: false }, + field6: false, + }); + const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request); + if (!result.success) throw new Error(result.errorMessage || 'recall private message failed'); + } + + /** + * Push a group read-report (`trpc.msg.msg_svc.MsgService.SsoReadedReport`) + * advancing the bot's last-read marker to `sequence`. Mirrors the QQ + * NT client's own "scrolled to bottom" behaviour so subsequent + * sync packets don't replay messages we've already processed. + */ + async markGroupRead(groupId: number, sequence: number): Promise { + const request = protobuf_encode({ + groupList: [ + { + groupUin: BigInt(groupId), + lastReadSeq: BigInt(sequence), + }, + ], + }); + const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request); + if (!result.success) { + throw new Error(result.errorMessage || 'mark group message read failed'); + } + } + + /** + * Push a c2c read-report. Same wire-cmd as the group variant but + * keyed by friend uid (resolved from uin via IdentityService). + * `lastReadTime` defaults to "now" — matches the QQ NT client + * which also uses wall-clock seconds rather than the read-message + * timestamp. + */ + async markPrivateRead(userId: number, sequence: number): Promise { + const uid = await this.ctx.resolveUserUid(userId); + const request = protobuf_encode({ + c2cList: [ + { + uid, + lastReadTime: BigInt(Math.floor(Date.now() / 1000)), + lastReadSeq: BigInt(sequence), + }, + ], + }); + const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request); + if (!result.success) { + throw new Error(result.errorMessage || 'mark private message read failed'); + } + } +} + diff --git a/packages/core/src/bridge/apis/misc.ts b/packages/core/src/bridge/apis/misc.ts new file mode 100644 index 00000000..fe05bac2 --- /dev/null +++ b/packages/core/src/bridge/apis/misc.ts @@ -0,0 +1,146 @@ +// MiscApi — odds & ends that don't fit the other Apis: translation, +// mini-app ARK build, inline-keyboard button click, group sign-in. +// Inlined from `actions/misc.ts` (deleted alongside actions/* in +// commit 13). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + MiniAppShareReq, + MiniAppShareResp, + Oidb0x112eReq, + Oidb0x112eResp, + Oidb0x990Req, + Oidb0x990Resp, + Oidb0xeb7Req, + Oidb0xeb7Resp, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +export class MiscApi { + constructor(private readonly ctx: BridgeContext) {} + + async translateEn2Zh(words: string[]): Promise { + const bridge = asBridge(this.ctx); + const req = { + translateReq: { + srcLang: 'en', + dstLang: 'zh', + words, + }, + tag10: 1, + tag12: 1, + }; + + const env = makeOidbEnvelope(0x990, 2, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x990_2', protobuf_encode>(env)); + const result = protobuf_decode>(respBytes).body; + + const resp = result?.translateResp; + if (!resp) { + throw new Error('translate response empty'); + } + + return resp.dstWords || []; + } + + async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise { + let appid = '1109937557'; // default: bilibili + let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg'; + + if (type === 'weibo') { + appid = '1109224783'; + iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg'; + } else if (type !== 'bili') { + throw new Error(`unsupported type: ${type}, only support bili and weibo`); + } + + const request = protobuf_encode({ + sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A', + body: { appid, title, desc, picUrl, jumpUrl, iconUrl }, + }); + + const result = await this.ctx.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request); + + if (!result.success || !result.responseData) { + throw new Error(result.errorMessage || 'get mini app ark failed'); + } + + const decoded = protobuf_decode(result.responseData); + const jsonStr = decoded?.body?.jsonStr; + + if (!jsonStr) { + throw new Error('mini app share json empty'); + } + + const parsed = JSON.parse(jsonStr); + + return { + data: { + ver: parsed.ver, + prompt: parsed.prompt, + config: parsed.config, + app: parsed.appName, + view: parsed.appView, + meta: parsed.metaData, + miniappShareOrigin: 3, + miniappOpenRefer: '10002', + }, + }; + } + + async clickInlineKeyboardButton( + groupId: number, + botAppid: number, + buttonId: string, + callbackData: string, + msgSeq: number, + ): Promise { + const bridge = asBridge(this.ctx); + const req = { + botAppid: BigInt(botAppid), + msgSeq: BigInt(msgSeq), + buttonId: String(buttonId), + callbackData: String(callbackData || ''), + unknown7: 0, + groupId: BigInt(groupId), + unknown9: 1, + }; + + const env = makeOidbEnvelope(0x112E, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112e_1', protobuf_encode>(env)); + const result = protobuf_decode>(respBytes).body; + + if (!result) { + throw new Error('click inline keyboard button result empty'); + } + + return { + result: Number(result.result || 0), + errMsg: result.errMsg || '', + status: 0, + promptText: result.promptText || '', + promptType: 0, + promptIcon: 0, + }; + } + + async sendGroupSign(groupId: number): Promise { + const bridge = asBridge(this.ctx); + const req = { + signInInfo: { + uin: String(this.ctx.identity.uin), + groupId: String(groupId), + version: '9.0.90', + }, + }; + + const env = makeOidbEnvelope(0xEB7, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xEB7_1', protobuf_encode>(env)); + protobuf_decode>(respBytes); + } +} diff --git a/packages/core/src/bridge/apis/profile.ts b/packages/core/src/bridge/apis/profile.ts new file mode 100644 index 00000000..d92ac399 --- /dev/null +++ b/packages/core/src/bridge/apis/profile.ts @@ -0,0 +1,271 @@ +// ProfileApi — personal profile + status + avatar + likes + custom +// faces + unidirectional friend list. Inlined from +// `actions/profile.ts` (deleted alongside actions/* in commit 13). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FaceroamOpReq, + FaceroamOpResp, + GroupAvatarExtra, + Oidb0x112aReq, + Oidb0x112aResp, + Oidb0x7edReq, + Oidb0x7edResp, + Oidb0xcd4Req, + Oidb0xcd4Resp, + Oidb0xe17Req, + Oidb0xe17Resp, + OidbSetProfile, + SetStatusReq, + SetStatusResp, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; +import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway'; +import { computeHashes, loadBinarySource } from '@snowluma/bridge/highway/utils'; +import { resolveSelfUid } from './shared'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +export class ProfileApi { + constructor(private readonly ctx: BridgeContext) {} + + // ─────────────── status / profile setters ─────────────── + + async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise { + await this.dispatchSetStatus({ status, extStatus, batteryStatus }); + } + + /** + * DIY (custom) online status. napcat fixes status=10 / extStatus=2000 + * — the values QQ associates with "I have a custom status string" — + * and threads the faceId / wording / faceType through the customExt + * sub-message of the same SetStatus wire call. + */ + async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise { + await this.dispatchSetStatus({ + status: 10, + extStatus: 2000, + batteryStatus: 0, + customExt: { faceId, text: wording, faceType }, + }); + } + + private async dispatchSetStatus(value: { + status: number; + extStatus: number; + batteryStatus: number; + customExt?: { faceId: number; text: string; faceType: number }; + }): Promise { + const request = protobuf_encode(value); + const result = await this.ctx.sendRawPacket( + 'trpc.qq_new_tech.status_svc.StatusService.SetStatus', + request, + ); + + if (!result.success) { + throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); + } + + if (result.responseData && result.responseData.length > 0) { + const resp = protobuf_decode(result.responseData); + if (!resp) { + throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); + } + if (resp.errCode !== undefined && resp.errCode !== 0) { + throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`); + } + } + } + + async setProfile(nickname?: string, personalNote?: string): Promise { + const bridge = asBridge(this.ctx); + const uin = BigInt(this.ctx.identity.uin); + const stringProfiles: any[] = []; + const intProfiles: any[] = []; + + if (nickname !== undefined) { + stringProfiles.push({ fieldId: 20002, value: nickname }); + } + + if (personalNote !== undefined) { + stringProfiles.push({ fieldId: 102, value: personalNote }); + } + + if (stringProfiles.length === 0 && intProfiles.length === 0) { + return; + } + + const req = { uin, stringProfiles }; + const env = makeOidbEnvelope(0x112A, 2, req); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); + } + + async setSelfLongNick(longNick: string): Promise { + const bridge = asBridge(this.ctx); + const req = { + uin: BigInt(this.ctx.identity.uin), + profile: { + tag: 102, + value: String(longNick), + }, + }; + + const env = makeOidbEnvelope(0x112A, 2, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); + // Decode just to maintain the original behaviour of "consume the response". + protobuf_decode>(respBytes); + } + + async setInputStatus(userId: number, eventType: number): Promise { + const bridge = asBridge(this.ctx); + const targetUid = await this.ctx.resolveUserUid(userId); + + if (!targetUid) { + throw new Error('target uid not found'); + } + + const req = { + reqBody: { + uid: targetUid, + chatType: 0, + eventType, + }, + }; + + const env = makeOidbEnvelope(0xCD4, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', protobuf_encode>(env)); + protobuf_decode>(respBytes); + } + + async setAvatar(source: string): Promise { + const bridge = asBridge(this.ctx); + const loaded = await loadBinarySource(source, 'avatar'); + if (!loaded.bytes.length) throw new Error('avatar file is empty'); + + const hashes = computeHashes(loaded.bytes); + const session = await fetchHighwaySession(bridge); + await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0)); + } + + /** + * Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar: + * - same highway HTTP upload as personal avatar + * - cmdId 3000 (instead of 90) + * - GroupAvatarExtra proto carried as the `extend` blob, with the + * four protocol-prescribed constants (type=101, field5=3, field6=1, + * field3.field1=1) and the target groupUin. + * + * Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar. + */ + async setGroupAvatar(groupId: number, source: string): Promise { + const bridge = asBridge(this.ctx); + const loaded = await loadBinarySource(source, 'group-avatar'); + if (!loaded.bytes.length) throw new Error('group avatar file is empty'); + + const hashes = computeHashes(loaded.bytes); + const session = await fetchHighwaySession(bridge); + const extra = protobuf_encode({ + type: 101, + groupUin: groupId, + field3: { field1: 1 }, + field5: 3, + field6: 1, + }); + await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra); + } + + // ─────────────── queries on me / my contacts ─────────────── + + async getLike(userId?: number, start = 0, limit = 10): Promise { + const bridge = asBridge(this.ctx); + const isSelf = !userId; + const targetUid = isSelf + ? await resolveSelfUid(bridge) + : await this.ctx.resolveUserUid(userId); + + if (!targetUid) { + throw new Error('target uid not found'); + } + + const req = { + targetUid, + basic: 1, + vote: 1, + favorite: 1, + start, + limit, + }; + + const env = makeOidbEnvelope(0x7ED, 12, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', protobuf_encode>(env)); + const result = protobuf_decode>(respBytes).body; + + const data = result?.userLikeInfos?.[0]; + if (!data) { + throw new Error('get profile like info empty'); + } + + return { + uid: data.uid, + time: Number(data.time), + favoriteInfo: { + total_count: data.favoriteInfo?.totalCount || 0, + last_time: Number(data.favoriteInfo?.lastTime || 0), + today_count: data.favoriteInfo?.newCount || 0, + userInfos: [], + }, + voteInfo: { + total_count: data.voteInfo?.totalCount || 0, + new_count: data.voteInfo?.newCount || 0, + new_nearby_count: 0, + last_visit_time: Number(data.voteInfo?.lastTime || 0), + userInfos: [], + }, + }; + } + + async getUnidirectionalFriendList(): Promise { + const bridge = asBridge(this.ctx); + const reqObj = { + uint64_uin: String(this.ctx.identity.uin), + uint64_top: 0, + uint32_req_num: 99, + bytes_cookies: '', + }; + + const req = { jsonBody: JSON.stringify(reqObj) }; + const env = makeOidbEnvelope(0xE17, 0, req); + const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', protobuf_encode>(env)); + const result = protobuf_decode>(respBytes).body; + + if (!result || !result.jsonBody) { + throw new Error('get unidirectional friend list empty'); + } + + const parsed = JSON.parse(result.jsonBody); + return parsed.rpt_block_list || []; + } + + async fetchCustomFace(count = 10): Promise { + const req = { + inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' }, + uin: BigInt(this.ctx.identity.uin), + field3: 1, + field6: 1, + }; + const request = protobuf_encode(req); + const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'fetch custom face failed'); + } + const resp = protobuf_decode(result.responseData); + if (!resp || (resp as any).retCode !== 0) { + throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`); + } + const faceIds = (resp as any).item?.faceIds || []; + return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`); + } +} diff --git a/packages/core/src/bridge/actions/shared.ts b/packages/core/src/bridge/apis/shared.ts similarity index 92% rename from packages/core/src/bridge/actions/shared.ts rename to packages/core/src/bridge/apis/shared.ts index d9b8edeb..e3c4e091 100644 --- a/packages/core/src/bridge/actions/shared.ts +++ b/packages/core/src/bridge/apis/shared.ts @@ -1,7 +1,3 @@ -// Shared private helpers for the action modules. None of this is part -// of the public Bridge API; keeping it here avoids re-importing the -// same five-line utility from every themed file. - import type { Bridge } from '../bridge'; /** diff --git a/packages/core/src/bridge/apis/web.ts b/packages/core/src/bridge/apis/web.ts new file mode 100644 index 00000000..9e40fb75 --- /dev/null +++ b/packages/core/src/bridge/apis/web.ts @@ -0,0 +1,354 @@ +// WebApi — cookie-backed HTTP wrappers (group essence / honor / notice / +// client-key / pskey / csrf-token / credentials). Inlined from the +// per-feature files in `web-actions/` (all deleted in commit 13). +// The pure HTTP transport stays in `web/*.ts` and stays unchanged — +// only the Bridge-binding helpers move here. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbClientKeyReq, + OidbClientKeyResp, + OidbGetPskeyReq, + OidbGetPskeyResp, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; +import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '@snowluma/bridge/web/group-essence'; +import { getHonorListWebAPI, WebHonorType } from '@snowluma/bridge/web/group-honor'; +import { + deleteGroupNotice as deleteGroupNoticeHttp, + getGroupNoticeWebAPI, + setGroupNoticeWebAPI, + uploadGroupNoticeImage, +} from '@snowluma/bridge/web/group-notice'; +import { RequestUtil } from '@snowluma/bridge/web/request-util'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +export interface ClientKeyInfo { + clientKey: string; + keyIndex: string; + expireTime: string; +} + +// ─────────────── private helpers (cookie acquisition) ─────────────── + +async function forceFetchClientKeyInner(bridge: Bridge): Promise { + const env = makeOidbEnvelope(0x102A, 1, {}); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_1', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const clientKey = resp?.clientKey || ''; + // keyIndex falls back to "19" — origin unknown but the value is what + // every NapCat-derived implementation uses when the server omits it. + const keyIndex = String(resp?.keyIndex || '19'); + + return { + clientKey, + keyIndex, + expireTime: String(resp?.expireTime || '1800'), + }; +} + +async function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map }> { + const env = makeOidbEnvelope(0x102A, 0, { domainList }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_0', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + + const domainPskeyMap = new Map(); + if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) { + for (const item of resp.pskeyItems) { + if (item.domain && item.pskey) { + domainPskeyMap.set(item.domain, item.pskey); + } + } + } + + return { domainPskeyMap }; +} + +async function getCookies(bridge: Bridge, domain: string): Promise> { + const ClientKeyData = await forceFetchClientKeyInner(bridge); + + // Build the ptlogin2 jump URL: this is the canonical way for the + // bot to swap its clientKey for cookie-jar entries on a given + // qq.com subdomain. + const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin + + '&clientkey=' + ClientKeyData.clientKey + + '&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex; + + const data = await RequestUtil.HttpsGetCookies(requestUrl); + + if (!data['p_skey'] || data['p_skey'].length === 0) { + // ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey + // for the same domain. Errors are swallowed so the caller can + // still proceed with whatever cookies it did get. + try { + const pskeyData = await getPSkey(bridge, [domain]); + const pskey = pskeyData.domainPskeyMap.get(domain); + if (pskey) { + data['p_skey'] = pskey; + } + } catch { + return data; + } + } + + return data; +} + +async function getSKey(bridge: Bridge): Promise { + const ClientKeyData = await forceFetchClientKeyInner(bridge); + + if (!ClientKeyData.clientKey) { + throw new Error('getClientKey Error: clientKey is empty'); + } + + const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0'); + const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' + + '&clientuin=' + bridge.identity.uin + + '&clientkey=' + ClientKeyData.clientKey + + '&u1=' + u1 + + '&keyindex=' + ClientKeyData.keyIndex; + + const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl); + const skey = cookies['skey']; + + if (!skey) { + throw new Error('SKey is Empty'); + } + + return skey; +} + +/** + * Standard QQ bkn hash (also known as token / csrf_token) derived from + * skey or p_skey. djb2 hash truncated to 31 bits. + */ +function getBknFromSKey(skey: string): number { + let hash = 5381; + for (let i = 0; i < skey.length; i++) { + hash += (hash << 5) + skey.charCodeAt(i); + } + return hash & 2147483647; +} + +export class WebApi { + constructor(private readonly ctx: BridgeContext) {} + + // ─────────────── cookie / token primitives ─────────────── + + async forceFetchClientKey(): Promise { + return forceFetchClientKeyInner(asBridge(this.ctx)); + } + + /** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi + * (qzone.qq.com) and by every other web helper here. */ + async getCookies(domain: string): Promise> { + return getCookies(asBridge(this.ctx), domain); + } + + /** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */ + async getCookiesStr(domain: string): Promise { + const cookieObject = await getCookies(asBridge(this.ctx), domain); + return Object.entries(cookieObject) + .map(([key, value]) => `${key}=${value}`) + .join('; '); + } + + /** CSRF token == bkn(skey) — used by qzone / qun web APIs. */ + async getCsrfToken(): Promise { + const skey = await getSKey(asBridge(this.ctx)); + if (!skey) { + throw new Error('SKey is Empty'); + } + return getBknFromSKey(skey); + } + + /** Returns the OneBot `get_credentials` payload (cookie string + bkn). */ + async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> { + const cookieObject = await getCookies(asBridge(this.ctx), domain); + const cookiesStr = Object.entries(cookieObject) + .map(([key, value]) => `${key}=${value}`) + .join('; '); + + const skey = cookieObject['p_skey'] || cookieObject['skey'] || ''; + const token = skey ? getBknFromSKey(skey) : 0; + + return { + cookies: cookiesStr, + token, + csrf_token: token, + }; + } + + // ─────────────── group essence ─────────────── + + /** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */ + async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit); + return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } }; + } + + /** Walks every page and returns the concatenated result. */ + async getEssenceAll(groupId: number): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + return await getGroupEssenceMsgAll(cookieObject, groupCode); + } + + // ─────────────── group honor ─────────────── + + async getHonorInfo(groupId: number, type: WebHonorType | string): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + + const honorInfo: any = { + group_id: groupId, + current_talkative: null, + talkative_list: [], + performer_list: [], + legend_list: [], + emotion_list: [], + strong_newbie_list: [], + }; + + if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) { + const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1); + if (talkativeList.length > 0) { + honorInfo.current_talkative = talkativeList[0]; + honorInfo.talkative_list = talkativeList; + } + } + + if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) { + honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2); + } + + if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) { + honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3); + } + + if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) { + honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6); + } + + return honorInfo; + } + + // ─────────────── group notice ─────────────── + + async sendNotice( + groupId: number, + content: string, + options?: { + image?: string; // local path, http URL, or undefined (text-only) + pinned?: number; + type?: number; + confirm_required?: number; + }, + ): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + + let picId = ''; + let imgWidth = 540; + let imgHeight = 300; + + if (options?.image) { + let imageBuffer: Buffer; + + if (options.image.startsWith('http://') || options.image.startsWith('https://')) { + const response = await fetch(options.image); + if (!response.ok) throw new Error(`Failed to download image: ${response.status}`); + imageBuffer = Buffer.from(await response.arrayBuffer()); + } else { + const { readFileSync } = await import('fs'); + imageBuffer = readFileSync(options.image); + } + + const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer); + if (picInfo) { + picId = picInfo.id; + imgWidth = picInfo.width; + imgHeight = picInfo.height; + } + } + + const ret = await setGroupNoticeWebAPI( + cookieObject, + groupCode, + content, + options?.pinned ?? 0, + options?.type ?? 1, + 1, + 1, + options?.confirm_required ?? 1, + picId, + imgWidth, + imgHeight, + ); + + if (!ret || ret.ec !== 0) { + throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`); + } + + return ret; + } + + async getNotice(groupId: number): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + + const ret = await getGroupNoticeWebAPI(cookieObject, groupCode); + if (!ret) { + throw new Error('获取公告失败'); + } + + const retNotices: any[] = []; + + if (ret.feeds) { + for (const key in ret.feeds) { + const feed = ret.feeds[key]; + if (!feed) continue; + + const image = feed.msg?.pics?.map((pic) => ({ + id: pic.id, + height: pic.h, + width: pic.w, + })) || []; + + retNotices.push({ + notice_id: feed.fid, + sender_id: feed.u, + publish_time: feed.pubt, + message: { + text: feed.msg?.text || '', + image, + images: image, + }, + settings: feed.settings, + read_num: feed.read_num, + }); + } + } + + return retNotices; + } + + async deleteNotice(groupId: number, fid: string): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + return await deleteGroupNoticeHttp(cookieObject, groupCode, fid); + } +} diff --git a/packages/core/src/bridge/bridge-contacts.ts b/packages/core/src/bridge/bridge-contacts.ts deleted file mode 100644 index 54173dcf..00000000 --- a/packages/core/src/bridge/bridge-contacts.ts +++ /dev/null @@ -1,354 +0,0 @@ -// Contact / info-fetching operations extracted from Bridge. - -import type { Bridge } from './bridge'; -import type { DownloadRKeyInfo } from './bridge'; -import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; -import { protoDecode } from '../protobuf/decode'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from './bridge-oidb'; -import { AvatarInfoSchema } from './proto/oidb-action'; -import type { - OidbSvcTrpcTcp0xFD4_1Response, - OidbSvcTrpcTcp0xFE5_2Response, - OidbSvcTrpcTcp0xFE7_3Response, - OidbSvcTrpcTcp0x10C0Response, -} from './proto/proton/oidb'; -import type { - OidbFriendListRequest, - OidbGroupListRequest, - OidbGroupMemberListRequest, - OidbUserInfoRequest, - OidbUserInfoResponse, - OidbGroupRequestList, - NTV2RichMediaReq, - NTV2RichMediaResp, -} from './proto/proton/oidb-action'; - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -export function buildFriendProperties(raw: any): Map { - const props = new Map(); - for (const additional of raw.additional ?? []) { - if ((additional.type ?? 0) !== 1 || !additional.layer1) continue; - for (const property of additional.layer1.properties ?? []) { - props.set(property.code ?? 0, property.value ?? ''); - } - } - return props; -} - -export function permissionToRole(permission: number): string { - switch (permission) { - case 1: return 'owner'; - case 2: return 'admin'; - default: return 'member'; - } -} - -// --------------------------------------------------------------------------- -// Friend list -// --------------------------------------------------------------------------- - -export async function fetchFriendList(bridge: Bridge): Promise { - const friends: FriendInfo[] = []; - let nextUin: number | null = null; - - do { - const body: any = { - friendCount: 300, - field4: 0, - field6: 1, - field7: 0x7FFFFFFF, - body: [ - { type: 1, number: { numbers: [103, 102, 20002, 27394] } }, - { type: 4, number: { numbers: [100, 101, 102] } }, - ], - field10002: [13578, 13579, 13573, 13572, 13568], - field10003: 4051, - }; - if (nextUin !== null) { - body.nextUin = { uin: nextUin }; - } - - const env = makeOidbEnvelope(0xFD4, 1, body); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - if (resp?.friends) { - for (const raw of resp.friends) { - const props = buildFriendProperties(raw); - friends.push({ - uin: raw.uin ?? 0, - uid: raw.uid ?? '', - nickname: props.get(20002) ?? String(raw.uin ?? 0), - remark: props.get(103) ?? '', - }); - } - } - - nextUin = resp?.next?.uin ?? null; - if (nextUin === 0) nextUin = null; - } while (nextUin !== null); - - bridge.identity.rememberFriends(friends); - return friends; -} - -// --------------------------------------------------------------------------- -// Group list -// --------------------------------------------------------------------------- - -export async function fetchGroupList(bridge: Bridge): Promise { - // The config flags ask QQ which per-group fields to include in the - // response. Asking for everything looks innocent on small accounts - // but on ~200+ groups it makes the QQ NT process write a payload - // large enough to blow the named-pipe write buffer — we then read - // EPIPE and the whole session dies. See issue #42. - // - // The user-verified safe combination: keep `config1.*` mostly on - // (the response decoder pulls groupOwner / memberMax / memberCount / - // groupName / description / question / announcement from this - // group), but turn off the costly groups of bools that never map - // back to a decoded field: - // - config1.field5002, field5003 (expansive 5xxx-range descriptors) - // - all of config2 (auxiliary per-group blob the decoder ignores) - const allTrue = true; - const body = { - config: { - config1: { - groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue, - groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue, - field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue, - field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue, - question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue, - field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue, - field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue, - field32: allTrue, field5001: allTrue, field5002: false, field5003: false, - }, - config2: { - field1: false, field2: false, field3: false, field4: false, - field5: false, field6: false, field7: false, field8: false, - }, - config3: { field5: allTrue, field6: allTrue }, - }, - }; - - const env = makeOidbEnvelope(0xFE5, 2, body, true); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const groups: QQGroupInfo[] = []; - if (resp?.groups) { - for (const raw of resp.groups) { - groups.push({ - groupId: raw.groupUin ?? 0, - groupName: raw.info?.groupName ?? '', - remark: raw.customInfo?.remark ?? '', - memberCount: raw.info?.memberCount ?? 0, - memberMax: raw.info?.memberMax ?? 0, - members: new Map(), - }); - } - } - bridge.identity.rememberGroups(groups); - return groups; -} - -// --------------------------------------------------------------------------- -// Group member list -// --------------------------------------------------------------------------- - -export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Promise { - const members: GroupMemberInfo[] = []; - let token = ''; - - do { - const body: any = { - groupUin: groupId, - field2: 5, - field3: 2, - body: { - memberName: true, memberCard: true, level: true, field13: true, - field16: true, specialTitle: true, field18: true, field20: true, - field21: true, joinTimestamp: true, lastMsgTimestamp: true, - shutUpTimestamp: true, field103: true, field104: true, field105: true, - field106: true, permission: true, field200: true, field201: true, - }, - }; - if (token) body.token = token; - - const env = makeOidbEnvelope(0xFE7, 3, body); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - if (resp?.members) { - for (const raw of resp.members) { - members.push({ - uin: raw.uin?.uin ?? 0, - uid: raw.uin?.uid ?? '', - nickname: raw.memberName ?? '', - card: raw.memberCard?.memberCard ?? '', - role: permissionToRole(raw.permission ?? 0), - level: raw.level?.level ?? 0, - title: raw.specialTitle ?? '', - joinTime: raw.joinTimestamp ?? 0, - lastSentTime: raw.lastMsgTimestamp ?? 0, - shutUpTime: raw.shutUpTimestamp ?? 0, - }); - } - } - - token = resp?.token ?? ''; - } while (token); - - bridge.identity.rememberGroupMembers(groupId, members); - return members; -} - -// --------------------------------------------------------------------------- -// User profile -// --------------------------------------------------------------------------- - -export async function fetchUserProfile(bridge: Bridge, uin: number): Promise { - const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037]; - // Only `uin` and `keys` — see OidbUserInfoRequestSchema for why - // sending field 2 makes the server reject the request. - const body = { - uin, - keys: keys.map(k => ({ key: k })), - }; - - // Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the - // name is historical, the wire semantic is "this is the UIN-form - // variant of the call"). Without it newer QQ NT versions take the - // UID-form validation path, find neither uid nor openid in the body - // and bounce the request with `[oidb] one of uid/openid is invaild`. - // Matches Lagrange.Core's FetchStrangerByUin (Reserved = 1). - const env = makeOidbEnvelope(0xFE1, 2, body, true); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - if (!resp?.body) throw new Error('user info response body missing'); - - const info: UserProfileInfo = { - uin: resp.body.uin ?? uin, - uid: resp.body.uid ?? '', - nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', - }; - - if (resp.body.properties) { - const bytesMap = new Map(); - const numMap = new Map(); - for (const bp of resp.body.properties.bytesProperties ?? []) { - bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0)); - } - for (const np of resp.body.properties.numberProperties ?? []) { - numMap.set(np.number1 ?? 0, np.number2 ?? 0); - } - - const getString = (code: number) => { - const b = bytesMap.get(code); - return b ? Buffer.from(b).toString('utf8') : ''; - }; - - info.nickname = getString(20002); - info.remark = getString(103); - info.qid = getString(27394); - info.sign = getString(102); - - const avatarBytes = bytesMap.get(101); - if (avatarBytes) { - const av = protoDecode(avatarBytes, AvatarInfoSchema); - if (av?.url) info.avatar = av.url + '640'; - } - - const sexNum = numMap.get(20009) ?? 0; - info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown'; - info.age = numMap.get(20037) ?? 0; - } - - bridge.identity.rememberUserProfile(info); - return info; -} - -// --------------------------------------------------------------------------- -// Group requests -// --------------------------------------------------------------------------- - -export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise { - const subCmd = filtered ? 2 : 1; - const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1'; - const env = makeOidbEnvelope(0x10C0, subCmd, { count: 20, field2: 0 }); - const respBytes = await runOidb(bridge, cmd, encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const requests: GroupRequestInfo[] = []; - for (const raw of resp?.requests ?? []) { - requests.push({ - groupId: raw.group?.groupUin ?? 0, - groupName: raw.group?.groupName ?? '', - targetUid: raw.target?.uid ?? '', - targetUin: 0, - targetName: raw.target?.name ?? '', - invitorUid: raw.invitor?.uid ?? '', - invitorUin: 0, - invitorName: raw.invitor?.name ?? '', - operatorUid: raw.operatorUser?.uid ?? '', - operatorUin: 0, - operatorName: raw.operatorUser?.name ?? '', - sequence: Number(raw.sequence ?? 0), - state: raw.state ?? 0, - eventType: raw.eventType ?? 0, - comment: raw.comment ?? '', - filtered, - }); - } - bridge.identity.rememberGroupRequests(requests); - return requests; -} - -// --------------------------------------------------------------------------- -// Download RKeys -// --------------------------------------------------------------------------- - -export async function fetchDownloadRKeys(bridge: Bridge): Promise { - const PRIVATE_IMAGE = 10; - const GROUP_IMAGE = 20; - const FALLBACK_IMAGE = 2; - - const body = { - reqHead: { - common: { requestId: 1, command: 202 }, - scene: { requestType: 2, businessType: 1, sceneType: 0 }, - client: { agentType: 2 }, - }, - downloadRkey: { - types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE], - }, - }; - - const env = makeOidbEnvelope(0x9067, 202, body, true); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) { - throw new Error(resp.respHead.message ?? 'fetch download rkey failed'); - } - - const result: DownloadRKeyInfo[] = []; - for (const entry of resp?.downloadRkey?.rkeys ?? []) { - const rkey = entry.rkey ?? ''; - const type = entry.type ?? 0; - if (rkey && type) { - result.push({ - rkey, - ttlSeconds: Number(entry.rkeyTtlSec ?? 0), - storeId: entry.storeId ?? 0, - createTime: entry.rkeyCreateTime ?? 0, - type, - }); - } - } - return result; -} diff --git a/packages/core/src/bridge/bridge-context.ts b/packages/core/src/bridge/bridge-context.ts new file mode 100644 index 00000000..a2ca9296 --- /dev/null +++ b/packages/core/src/bridge/bridge-context.ts @@ -0,0 +1,27 @@ +// Api-layer extension of @snowluma/bridge's slim BridgeContext. +// +// The slim interface in @snowluma/bridge has the protocol-layer +// surface (identity / events / sendRawPacket / resolveUserUid / next* +// sequence helpers / upload-metadata cache). This file extends it +// with `apis: ApiHub` — the typed bag of Api classes that lives ONLY +// in @snowluma/core, so the bridge package never sees it (avoiding +// a bridge → core cycle). +// +// The 13 Api classes (apis/.ts) import `BridgeContext` from +// here, which gives them `this.ctx.apis.message.sendGroup(...)` type- +// safety alongside the protocol-layer fields. Highway uploaders, +// element-builder, msg-push parsers (all in @snowluma/bridge) import +// the slim version directly from `@snowluma/bridge/bridge-context`. + +import type { BridgeContext as BaseBridgeContext } from '@snowluma/bridge/bridge-context'; +import type { ApiHub } from './apis'; + +export interface BridgeContext extends BaseBridgeContext { + readonly apis: ApiHub; +} + +// Re-export `UploadedFileMeta` from the slim package so existing +// `import type { UploadedFileMeta } from '<…>/bridge-context'` (or +// from bridge.ts via re-export) keeps working without callers having +// to learn the new package path. +export type { UploadedFileMeta } from '@snowluma/bridge/bridge-context'; diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index 43a55aa4..b476fcfd 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -1,178 +1,22 @@ -// BridgeInterface — the surface OneBot (and any other external consumer) -// is allowed to see. The concrete Bridge class additionally exposes raw -// protocol primitives (sendRawPacket, packet dispatch, PID management) -// used by the in-tree action / contacts / highway modules; those internal -// methods deliberately do NOT appear here so that callers depending on -// the interface stay decoupled from the wire format. +// BridgeInterface — the public Bridge surface for OneBot-side +// consumers. Slimmed down to BridgeContext + the few extra fields +// OneBot reaches into directly (most notably `activePid`). // -// Every method below has a matching signature on Bridge; `Bridge -// implements BridgeInterface` is the compile-time enforcement. +// Most OneBot code paths reach business methods through +// `bridge.apis..method()` — those types come from `ApiHub` +// inside `bridge-context.ts`. The remaining members below are the +// non-Api state that doesn't fit into a typed Api hub. +// +// Internal Api implementations should depend on `BridgeContext` +// instead (the narrower contract). `BridgeInterface` is for callers +// that need the activePid hook or for backwards compatibility with +// pre-#6 code that imported `BridgeInterface` as the bridge type. -import type { BridgeEventBus } from './event-bus'; -import type { IdentityService } from './identity-service'; -import type { - FriendInfo, QQGroupInfo, GroupMemberInfo, - UserProfileInfo, GroupRequestInfo, -} from './qq-info'; -import type { MessageElement, ForwardNodePayload } from './events'; -import type { GroupFilesResult } from './actions/group-file'; -import type { MediaIndexNode } from './actions/shared'; -import type { WebHonorType } from './web/group-honor'; -import type { - SendMessageReceipt, - DownloadRKeyInfo, - ClientKeyInfo, - UploadedFileMeta, -} from './bridge'; -import type { SendPacketResult } from '../protocol/packet-sender'; +import type { BridgeContext } from './bridge-context'; -export interface BridgeInterface { - // ─── Shared state ─── - readonly identity: IdentityService; - readonly events: BridgeEventBus; +export interface BridgeInterface extends BridgeContext { + /** Last-active process id — used by `OneBotManager` to thread + * per-process state into the right instance. `null` when no + * process has bound yet. */ readonly activePid: number | null; - - // ─── Resolution ─── - resolveUserUid(uin: number, groupId?: number): Promise; - - // ─── Raw packet (deliberate escape hatch for `send_packet` action) ─── - // OneBot clients use this to debug or invoke commands SnowLuma has no - // typed wrapper for. Every other method on this interface eventually - // routes through here. - sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise; - - // ─── Send (messages) ─── - sendGroupMessage(groupId: number, elements: MessageElement[]): Promise; - sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise; - /** - * Send a c2c file as a chat message. Bypasses the regular elems[] - * pipeline because c2c files live on `RichText.notOnlineFile`, not - * inside the elems array. Group files go through `sendGroupMessage` - * with a `{type:'file', fileId, fileName, fileSize, md5Hex, sha1Hex}` - * element instead. - */ - sendC2cFileMessage( - userUin: number, - userUid: string, - info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string }, - ): Promise; - - // ─── Fetch (contacts / profile / system) ─── - fetchFriendList(): Promise; - fetchGroupList(): Promise; - fetchGroupMemberList(groupId: number, options?: { force?: boolean }): Promise; - fetchUserProfile(uin: number): Promise; - fetchGroupRequests(filtered?: boolean): Promise; - fetchDownloadRKeys(): Promise; - - // ─── Group admin ─── - muteGroupMember(groupId: number, userId: number, duration: number): Promise; - muteGroupAll(groupId: number, enable: boolean): Promise; - setGroupAddOption(groupId: number, addType: number): Promise; - setGroupSearch(groupId: number): Promise; - setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason?: string, filtered?: boolean): Promise; - kickGroupMember(groupId: number, userId: number, reject: boolean, reason?: string): Promise; - kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise; - leaveGroup(groupId: number): Promise; - setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise; - setGroupCard(groupId: number, userId: number, card: string): Promise; - setGroupName(groupId: number, name: string): Promise; - setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise; - setGroupRemark(groupId: number, remark: string): Promise; - setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise; - setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise; - - // ─── Friend ─── - setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise; - deleteFriend(userId: number, block?: boolean): Promise; - setFriendRemark(userId: number, remark: string): Promise; - - // ─── Files ─── - uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>; - uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>; - /** - * Publish a previously-uploaded group file as a chat message via - * `OidbSvcTrpcTcp.0x6d9_4`. The atomic upload+publish flow inside - * `uploadGroupFile` already does this, but the OneBot send-message - * path needs it too for {type:'file', file_id} segments. - */ - sendGroupFileMessage(groupId: number, fileId: string): Promise; - /** Cache file metadata so a later send_msg with just `file_id` can rehydrate it. */ - rememberUploadedFile(meta: UploadedFileMeta): void; - recallUploadedFile(fileId: string): UploadedFileMeta | undefined; - fetchGroupFiles(groupId: number, folderId?: string): Promise; - fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise; - fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise; - fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise; - fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise; - fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise; - fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise; - deleteGroupFile(groupId: number, fileId: string): Promise; - moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise; - createGroupFileFolder(groupId: number, name: string, parentId?: string): Promise; - deleteGroupFileFolder(groupId: number, folderId: string): Promise; - renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise; - fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>; - - // ─── Group Album ─── - getGroupAlbumList(groupId: number): Promise; - uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise; - getGroupAlbumMediaList(groupId: number, albumId: string, attachInfo?: string): Promise; - commentGroupAlbumMedia(groupId: number, albumId: string, lloc: string, content: string): Promise; - deleteGroupAlbumMedia(groupId: number, albumId: string, lloc: string): Promise; - likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise; - - // ─── Forward ─── - uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise; - fetchForwardNodes(resId: string): Promise; - - // ─── Message ops ─── - recallGroupMessage(groupId: number, sequence: number): Promise; - recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise; - markGroupMsgAsRead(groupId: number, sequence: number): Promise; - markPrivateMsgAsRead(userId: number, sequence: number): Promise; - - // ─── Interaction ─── - sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise; - sendLike(userId: number, count: number): Promise; - getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }>; - - // ─── Web-backed ─── - getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise; - forceFetchClientKey(): Promise; - getGroupEssence(groupId: number, pageStart?: number, pageLimit?: number): Promise; - getGroupEssenceAll(groupId: number): Promise; - sendGroupNotice(groupId: number, content: string, options?: any): Promise; - getGroupNotice(groupId: number): Promise; - deleteGroupNotice(groupId: number, fid: string): Promise; - getCookiesStr(domain: string): Promise; - getCsrfToken(): Promise; - getCredentials(domain: string): Promise; - - // ─── Personal profile ─── - setOnlineStatus(status: number, extStatus?: number, batteryStatus?: number): Promise; - setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise; - setProfile(nickname?: string, personalNote?: string): Promise; - setSelfLongNick(longNick: string): Promise; - setInputStatus(userId: number, eventType: number): Promise; - setAvatar(source: string): Promise; - setGroupAvatar(groupId: number, source: string): Promise; - fetchCustomFace(count?: number): Promise; - getProfileLike(userId?: number, start?: number, limit?: number): Promise; - getUnidirectionalFriendList(): Promise; - getGroupAtAllRemain(groupId: number): Promise; - - // ─── Misc ─── - translateEn2Zh(words: string[]): Promise; - getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise; - clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number): Promise; - sendGroupSign(groupId: number): Promise; - - // ─── Tier-2 napcat parity extras ─── - setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise; - completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise; - cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise; - getStrangerStatus(uin: number): Promise<{ status: number; ext_status: number } | null>; - fetchAiVoiceList(groupId: number, chatType: number): Promise }>>; - fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: number): Promise; } diff --git a/packages/core/src/bridge/bridge-oidb.ts b/packages/core/src/bridge/bridge-oidb.ts deleted file mode 100644 index cdd5c76e..00000000 --- a/packages/core/src/bridge/bridge-oidb.ts +++ /dev/null @@ -1,101 +0,0 @@ -// One deep entry point for a single OIDB round-trip: dispatch a -// pre-encoded envelope via Bridge.sendRawPacket, validate the envelope -// retCode, and return the raw response bytes. -// -// History note. The legacy implementation used a runtime -// `makeOidbBaseSchema(InnerSchema)` factory and ran a runtime -// schema-walking encoder. Proton is compile-time, so the envelope is -// the generic interface `OidbBase` (proto/proton/oidb.ts). Proton's -// wrapper-binding requires *pass-through* wrappers (the wrapper's first -// arg must be forwarded unchanged to the inner codec — see -// proton/src/transform/replacer.ts), so this file exposes thin -// pass-through helpers (`encodeOidbEnv` / `decodeOidbEnv`) that -// proton monomorphizes at every call site. `runOidb` itself is -// non-generic — it just sends pre-encoded bytes and peeks at the -// envelope retCode via the non-generic `OidbBaseMeta` view. - -import type { Bridge } from './bridge'; -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; -import type { OidbBase, OidbBaseMeta } from './proto/proton/oidb'; - -/** - * Build the OidbBase-shaped TS value. Pure helper, no protobuf - * encoding happens here — pair with `encodeOidbEnv` to produce the - * wire bytes. - * - * The `isUid` flag sets the envelope `reserved` field to 1; despite the - * name (kept for back-compat with the legacy API), `reserved = 1` - * empirically signals the UIN-form variant of an OIDB call. Omit - * (default false) for genuinely UID-keyed calls. - */ -export function makeOidbEnvelope( - oidbCmd: number, - subCmd: number, - body: T, - isUid: boolean = false, -): OidbBase { - return { - command: oidbCmd, - subCommand: subCmd, - errorCode: 0, - body, - errorMsg: '', - reserved: isUid ? 1 : 0, - }; -} - -/** - * Pass-through encoder for the OIDB envelope. Single type param, body - * literally forwards its arg to `protobuf_encode>` — proton - * wrapper-binds this and replaces every `encodeOidbEnv(env)` call - * site with `protobuf_encode_OidbBase__MyReq(env)` at build time. - */ -export function encodeOidbEnv(env: OidbBase): Uint8Array { - return protobuf_encode>(env); -} - -/** - * Pass-through decoder for the OIDB envelope. Mirror of `encodeOidbEnv` - * — proton monomorphizes `OidbBase` per call site. - * - * Returns the full envelope; the caller usually wants `.body`. - */ -export function decodeOidbEnv(bytes: Uint8Array): OidbBase { - return protobuf_decode>(bytes); -} - -/** - * Issue one OIDB request and return the raw response bytes. - * - * Typical usage: - * const env = makeOidbEnvelope(0x1253, 1, value); - * const buf = await runOidb(bridge, cmd, encodeOidbEnv(env)); - * const resp = decodeOidbEnv(buf).body; - * - * Fire-and-check (no body decode): - * await runOidb(bridge, cmd, encodeOidbEnv(env)); - * - * Always peeks at the envelope errorCode via the non-generic - * `OidbBaseMeta` view so a server-side rejection cannot slip past - * silently. Returns the raw response bytes (empty `Uint8Array` if the - * packet carried no payload). - */ -export async function runOidb( - bridge: Bridge, - cmd: string, - envelopeBytes: Uint8Array, -): Promise { - const result = await bridge.sendRawPacket(cmd, envelopeBytes); - if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); - if (!result.gotResponse) throw new Error(result.errorMessage || 'no response'); - - const bytes = result.responseData ?? new Uint8Array(0); - if (bytes.length > 0) { - const meta = protobuf_decode(bytes); - const code = meta?.errorCode; - if (code && code !== 0) { - throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`); - } - } - return bytes; -} diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 74b945c4..98cec6ba 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -1,144 +1,44 @@ -// Bridge — per-UIN session: handler registration, packet dispatch, event routing. -// Supports packet sending via native addon. -// Heavy OIDB / contact / action logic is split into bridge-oidb, bridge-contacts, bridge-actions. - -import type { PacketInfo } from '../protocol/types'; -import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events'; -import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; -import { MSG_PUSH_CMD, parseMsgPush } from './msg-push'; -import type { PacketSender, SendPacketResult } from '../protocol/packet-sender'; -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; -import { buildSendElems } from './element-builder'; -import { IdentityService } from './identity-service'; +import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; import type { BridgeInterface } from './bridge-interface'; -import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline'; -import { createLogger } from '../utils/logger'; -import type { - SendMessageRequest, - SendMessageResponse, -} from './proto/proton/action'; -import type { FileExtra } from './proto/proton/message'; +import { IdentityService } from '@snowluma/bridge/identity-service'; +import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/bridge/msg-push'; +import { IncomingPacketPipeline, type CmdParser } from '@snowluma/bridge/packet-pipeline'; +// qq-info types are no longer used directly in this file — they live +// inside the Api classes that own those fetches (apis/contacts.ts). +import { type ApiHub, buildApiHub } from './apis'; // Delegated modules +// Group-todo / stranger-status / AI-voice moved to apis/extras.ts. +// Public types stay re-exported through this file for backwards +// compatibility — the OneBot side imports them via `@snowluma/core`. import { - fetchFriendList as fetchFriendList_, - fetchGroupList as fetchGroupList_, - fetchGroupMemberList as fetchGroupMemberList_, - fetchUserProfile as fetchUserProfile_, - fetchGroupRequests as fetchGroupRequests_, - fetchDownloadRKeys as fetchDownloadRKeys_, -} from './bridge-contacts'; -import type { WebHonorType } from './web/group-honor'; -import { - muteGroupMember as muteGroupMember_, - muteGroupAll as muteGroupAll_, - setGroupAddOption as setGroupAddOption_, - setGroupSearch as setGroupSearch_, - setGroupAddRequest as setGroupAddRequest_, - kickGroupMember as kickGroupMember_, - kickGroupMembers as kickGroupMembers_, - leaveGroup as leaveGroup_, - setGroupAdmin as setGroupAdmin_, - setGroupCard as setGroupCard_, - setGroupName as setGroupName_, - setGroupSpecialTitle as setGroupSpecialTitle_, - setGroupRemark as setGroupRemark_, - getGroupAtAllRemain as getGroupAtAllRemain_, -} from './actions/group-admin'; -import { - uploadGroupFile as uploadGroupFile_, - uploadPrivateFile as uploadPrivateFile_, - sendGroupFileMessage as sendGroupFileMessage_, - fetchGroupFiles as fetchGroupFiles_, - fetchGroupFileUrl as fetchGroupFileUrl_, - fetchPrivateFileUrl as fetchPrivateFileUrl_, - fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_, - fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_, - fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_, - fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_, - deleteGroupFile as deleteGroupFile_, - moveGroupFile as moveGroupFile_, - createGroupFileFolder as createGroupFileFolder_, - deleteGroupFileFolder as deleteGroupFileFolder_, - renameGroupFileFolder as renameGroupFileFolder_, - fetchGroupFileCount as fetchGroupFileCount_, -} from './actions/group-file'; -import { - recallGroupMessage as recallGroupMessage_, - recallPrivateMessage as recallPrivateMessage_, - markPrivateMessageRead as markGroupMsgAsRead_, - markGroupMessageRead as markPrivateMsgAsRead_, - setGroupEssence as setGroupEssence_, -} from './actions/group-message'; -import { - sendPoke as sendPoke_, - sendLike as sendLike_, - setGroupReaction as setGroupReaction_, - getEmojiLikes as getEmojiLikes_, -} from './actions/interaction'; -import { - uploadForwardNodes as uploadForwardNodes_, - fetchForwardNodes as fetchForwardNodes_, -} from './actions/forward'; -import { - setFriendAddRequest as setFriendAddRequest_, - deleteFriend as deleteFriend_, - setFriendRemark as setFriendRemark_, -} from './actions/friend'; -import { - setOnlineStatus as setOnlineStatus_, - setDiyOnlineStatus as setDiyOnlineStatus_, - setProfile as setProfile_, - setSelfLongNick as setSelfLongNick_, - setInputStatus as setInputStatus_, - setAvatar as setAvatar_, - setGroupAvatar as setGroupAvatar_, - fetchCustomFace as fetchCustomFace_, - getProfileLike as getProfileLike_, - getUnidirectionalFriendList as getUnidirectionalFriendList_, -} from './actions/profile'; -import { - translateEn2Zh as translateEn2Zh_, - getMiniAppArk as getMiniAppArk_, - clickInlineKeyboardButton as clickInlineKeyboardButton_, - sendGroupSign as sendGroupSign_, -} from './actions/misc'; -import { - setGroupTodo as setGroupTodo_, - completeGroupTodo as completeGroupTodo_, - cancelGroupTodo as cancelGroupTodo_, - getStrangerStatus as getStrangerStatus_, - fetchAiVoiceList as fetchAiVoiceList_, - fetchAiVoice as fetchAiVoice_, AiVoiceChatType, type AiVoiceCategory, - type AiVoiceChatType as AiVoiceChatTypeT, type StrangerStatus, -} from './actions/extras'; +} from './apis/extras'; +// actions/forward.ts removed — moved to apis/forward.ts::ForwardApi. +// actions/friend.ts removed — moved to apis/friend.ts::FriendApi. +// actions/group-admin.ts removed — moved to `apis/group-admin.ts::GroupAdminApi`. +// actions/group-album.ts removed — moved to `apis/group-album.ts::GroupAlbumApi`. +// Group file CRUD + private c2c upload + media URL resolvers moved to +// `apis.groupFile` (see `apis/group-file.ts::GroupFileApi`). The shared +// result type still lives here because the OneBot side imports it +// through bridge.ts. +import type { GroupFilesResult } from './apis/group-file'; +// actions/group-message.ts removed — `setGroupEssence` moved to +// apis/interaction.ts::InteractionApi. The recall/markRead helpers +// were absorbed into MessageApi back in commit 1. +// actions/interaction.ts removed — sendPoke/sendLike/setReaction/ +// getEmojiLikes moved to apis/interaction.ts::InteractionApi. +// actions/misc.ts removed — moved to apis/misc.ts::MiscApi. +// actions/profile.ts removed — moved to apis/profile.ts::ProfileApi. +// `bridge-contacts.ts` removed — its 6 functions are now methods on +// `apis.contacts` (see `apis/contacts.ts::ContactsApi`). +import { BridgeEventBus } from '@snowluma/bridge/event-bus'; +// web-actions/* removed — moved to apis/web.ts::WebApi. export { AiVoiceChatType }; export type { AiVoiceCategory, StrangerStatus }; -import { - getGroupHonorInfo as getGroupHonorInfo_, - forceFetchClientKey as forceFetchClientKey_, - getGroupEssence as getGroupEssence_, - getGroupEssenceAll as getGroupEssenceAll_, - sendGroupNotice as sendGroupNotice_, - getGroupNotice as getGroupNotice_, - deleteGroupNoticeByFid as deleteGroupNotice_, - getCookiesStr as getCookiesStr_, - getCsrfToken as getCsrfToken_, - getCredentials as getCredentials_, - getGroupAlbumListWeb as getGroupAlbumListWeb_, - uploadImageToGroupAlbumWeb as uploadImageToGroupAlbumWeb_, -} from './web-actions'; -import { getGroupAlbumMediaList as getGroupAlbumMediaList_, - commentGroupAlbumMedia as commentGroupAlbumMedia_, - likeGroupAlbumMedia as likeGroupAlbumMedia_, - deleteGroupAlbumMedia as deleteGroupAlbumMedia_, -} from './actions/group-album'; -import type { GroupFilesResult } from './actions/group-file'; -import type { MediaIndexNode } from './actions/shared'; -import { BridgeEventBus } from './event-bus'; export interface SendMessageReceipt { messageId: number; @@ -185,11 +85,7 @@ export interface ClientKeyInfo { keyIndex: string } -const log = createLogger('Bridge'); - export class Bridge implements BridgeInterface { - private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg'; - readonly identity: IdentityService; private pids_ = new Set(); /** @@ -198,17 +94,19 @@ export class Bridge implements BridgeInterface { * care about and the pipeline fans out in parallel. */ readonly events = new BridgeEventBus(); + /** + * Typed Api hub. Each entry is a class encapsulating one logical + * area of the QQ protocol (sending messages, group admin, file + * uploads, etc.). Built eagerly in the constructor — every Bridge + * instance gets its own `apis.*` set with `this` (typed as + * `BridgeContext`) injected. See `apis/index.ts`. + */ + readonly apis: ApiHub; private readonly pipeline: IncomingPacketPipeline; private packetClient_: PacketSender | null = null; - // Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls - // and serves a fresh result for `kMemberListTtlMs` to all callers. - // Without this, a busy OneBot client (e.g. MaiBot calling - // get_group_member_info(no_cache=true) per inbound message) would - // trigger one OIDB 0xfe7_3 per chat message per group; sustained rate - // (>1k/h) is detected by Tencent risk-control and gets the account - // banned for 7 days. - private memberListInflight_ = new Map>(); - private memberListLastFetch_ = new Map(); + // (fetchGroupMemberList throttle cache moved to ContactsApi — same + // 60s TTL + inflight coalesce semantics, just owned by the Api class + // that exposes the method.) // ── Uploaded-file metadata cache ──────────────────────────────────── // @@ -234,9 +132,15 @@ export class Bridge implements BridgeInterface { constructor(identity: IdentityService) { this.identity = identity; + // Build Api hub FIRST — `setFetcher` below installs callbacks + // that reach into `this.apis.contacts.*`, so the hub must exist + // by the time those callbacks could fire. The Bridge instance IS + // the BridgeContext (Bridge implements BridgeInterface which + // includes the BridgeContext surface). + this.apis = buildApiHub(this); this.identity.setFetcher({ - fetchProfile: (uin) => this.fetchUserProfile(uin), - fetchGroupMemberList: (gid) => this.fetchGroupMemberList(gid), + fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin), + fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid), }); this.pipeline = new IncomingPacketPipeline({ identity: this.identity, @@ -287,10 +191,10 @@ export class Bridge implements BridgeInterface { private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise { if (refreshGroupList) { - try { await this.fetchGroupList(); } catch { /* ignore */ } + try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ } } if (!this.identity.findGroup(groupId)) return false; - await this.fetchGroupMemberList(groupId, { force: forceMemberList }); + await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList }); return true; } @@ -326,12 +230,18 @@ export class Bridge implements BridgeInterface { } // --- Sequence / random generators --- + // + // `public` (formerly `private`) because the Api classes in + // `apis/*.ts` need them to build `SendMessageRequest` packets. Part + // of the `BridgeContext` surface, so a third party that only sees + // `BridgeContext` can still synthesise wire packets without reaching + // into the concrete Bridge class. - private nextClientSequence(): number { + nextClientSequence(): number { return ++this.clientSeq_; } - private nextMessageRandom(): number { + nextMessageRandom(): number { this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0; return this.msgRandom_ & 0x7FFFFFFF; } @@ -348,236 +258,10 @@ export class Bridge implements BridgeInterface { return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs); } - // --- Send message (high-level) --- - - async sendGroupMessage(groupId: number, elements: MessageElement[]): Promise { - if (elements.length === 0) throw new Error('message is empty'); - - const protoElems = await buildSendElems(elements, { bridge: this, groupId }); - const random = this.nextMessageRandom(); - - const request = protobuf_encode({ - routingHead: { - grp: { groupCode: BigInt(groupId) }, - }, - contentHead: { - type: 1, - }, - messageBody: { - richText: { - elems: protoElems, - }, - } as any, - clientSequence: 0, - random, - syncCookie: new Uint8Array(0), - via: 0, - dataStatist: 0, - multiSendSeq: 0, - }); - - const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`); - } - - const response = protobuf_decode(result.responseData); - if (!response) { - throw new Error('failed to decode SendMessageResponse'); - } - if (response.result !== undefined && response.result !== 0) { - throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`); - } - - const seq = response.groupSequence ?? 0; - const messageId = (random & 0x7FFFFFFF) || seq; - const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); - - return { - messageId, - sequence: seq, - clientSequence: 0, - random, - timestamp, - }; - } - - async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise { - if (elements.length === 0) throw new Error('message is empty'); - - // Resolve UID for media upload and the final c2c routing head. - let userUid = ''; - const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'); - if (hasMedia) { - userUid = await this.resolveUserUid(userUin); - } - - const protoElems = await buildSendElems(elements, { bridge: this, userUid }); - const random = this.nextMessageRandom(); - const clientSeq = this.nextClientSequence(); - - const request = protobuf_encode({ - routingHead: { - c2c: { - uin: userUin, - ...(userUid ? { uid: userUid } : {}), - }, - }, - contentHead: { - type: 1, - subType: 0, - c2cCmd: 11, - }, - messageBody: { - richText: { - elems: protoElems, - }, - } as any, - clientSequence: clientSeq, - random, - syncCookie: new Uint8Array(0), - via: 0, - dataStatist: 0, - ctrl: { - msgFlag: Math.floor(Date.now() / 1000), - }, - multiSendSeq: 0, - }); - - const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`); - } - - const response = protobuf_decode(result.responseData); - if (!response) { - throw new Error('failed to decode SendMessageResponse'); - } - if (response.result !== undefined && response.result !== 0) { - throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`); - } - - const seq = response.privateSequence ?? 0; - const messageId = (random & 0x7FFFFFFF) || seq; - const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); - - return { - messageId, - sequence: seq, - clientSequence: clientSeq, - random, - timestamp, - }; - } - - /** - * Send a c2c file as a chat message. - * - * The wire shape isn't the same as a regular c2c message — the c2c - * file path uses three slots that differ from a normal text/image - * send (verified against `dev/Lagrange.Core/.../MessagePacker.cs: - * BuildPacketBase` + `FileEntity.PackMessageContent`): - * - * 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of - * `routingHead.c2c { uin, uid }`. The server rejects c2c file - * messages routed through the regular c2c slot. - * 2. `messageBody.msgContent` carries the serialised - * `FileExtra { file: NotOnlineFile }` bytes. NOT - * `richText.notOnlineFile` — the receiver doesn't read that - * slot for file metadata. - * 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The - * previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT - * server doesn't recognise. - * - * NotOnlineFile carries three required-on-send fields the receiver - * itself ignores but the server's intake validator checks: - * - `subcmd: 1` — c2c file send command code - * - `dangerEvel: 0` — virus-scan severity, always 0 client-side - * - `expireTime` — 7 days from now (Lagrange convention) - */ - async sendC2cFileMessage( - userUin: number, - userUid: string, - info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string }, - ): Promise { - const random = this.nextMessageRandom(); - const clientSeq = this.nextClientSequence(); - - const nowSec = Math.floor(Date.now() / 1000); - const sevenDaysSec = 7 * 24 * 60 * 60; - // Serialise `FileExtra { file: NotOnlineFile }` for `msgContent`. - // The NotOnlineFile field tags (1/3/4/5/6/9/50/55/57) are shared - // between send and receive — the schema is symmetric. - const fileExtraBytes = protobuf_encode({ - file: { - fileType: 0, - fileUuid: info.fileId, - fileMd5: info.fileMd5, - fileName: info.fileName, - fileSize: BigInt(info.fileSize), - subcmd: 1, - dangerEvel: 0, - expireTime: nowSec + sevenDaysSec, - fileHash: info.fileHash ?? '', - }, - }); - - const request = protobuf_encode({ - routingHead: { - // c2c-file scene: route through `trans0x211` (field 15) with - // ccCmd=4. The regular `c2c { uin, uid }` routing slot causes - // the server to reject this with a routing-mismatch error. - trans0x211: { ccCmd: 4, uid: userUid }, - }, - contentHead: { - type: 1, - subType: 0, - // c2cCmd intentionally omitted (defaults to 0). Was `11`, - // which produced an unknown-command error in the QQ-NT - // server's c2c file handler. `userUin` is unused on this path - // (routing carries the uid only) but kept in the function - // signature for symmetry with the OneBot caller. - }, - messageBody: { - // No elems — the file metadata lives in msgContent below. - msgContent: fileExtraBytes, - }, - clientSequence: clientSeq, - random, - syncCookie: new Uint8Array(0), - via: 0, - dataStatist: 0, - ctrl: { - msgFlag: nowSec, - }, - multiSendSeq: 0, - }); - - // Silence the unused-parameter lint — `userUin` is part of our - // BridgeInterface contract (the OneBot layer threads it through) - // but the wire shape only needs the uid. - void userUin; - - const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`); - } - - const response = protobuf_decode(result.responseData); - if (!response) { - throw new Error('failed to decode SendMessageResponse'); - } - if (response.result !== undefined && response.result !== 0) { - throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`); - } - - const seq = response.privateSequence ?? 0; - const messageId = (random & 0x7FFFFFFF) || seq; - const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); - return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; - } + // `Bridge.SEND_MSG_CMD` and the inline `sendGroupMessage` / + // `sendPrivateMessage` / `sendC2cFileMessage` implementations were + // moved to `apis/message.ts::MessageApi` as part of the #6 + // Api-on-ctx refactor. Callers route through `bridge.apis.message.*`. // --- Delegated: OIDB helpers --- @@ -585,206 +269,38 @@ export class Bridge implements BridgeInterface { return this.identity.resolveUid(uin, groupId); } - // --- Delegated: Contact / info queries --- + // fetchFriendList / fetchGroupList / fetchGroupMemberList / + // fetchUserProfile / fetchGroupRequests / fetchDownloadRKeys + // moved to apis.contacts (see apis/contacts.ts::ContactsApi). - async fetchFriendList(): Promise { return fetchFriendList_(this); } - async fetchGroupList(): Promise { return fetchGroupList_(this); } - async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise { - const kMemberListTtlMs = 60_000; - const now = Date.now(); - const last = this.memberListLastFetch_.get(groupId); - if (!options.force && last && now - last.at < kMemberListTtlMs) { - return last.data; - } - const inflight = this.memberListInflight_.get(groupId); - if (inflight) return inflight; - const task = (async () => { - try { - const data = await fetchGroupMemberList_(this, groupId); - this.memberListLastFetch_.set(groupId, { at: Date.now(), data }); - return data; - } finally { - this.memberListInflight_.delete(groupId); - } - })(); - this.memberListInflight_.set(groupId, task); - return task; - } - async fetchUserProfile(uin: number): Promise { return fetchUserProfile_(this, uin); } - async fetchGroupRequests(filtered = false): Promise { return fetchGroupRequests_(this, filtered); } - async fetchDownloadRKeys(): Promise { return fetchDownloadRKeys_(this); } + // --- Delegated: action methods --- + // + // GroupAdmin methods (mute/kick/admin/card/name/title/leave/ + // add-option/search/add-request/remark/at-all-remain) moved to + // apis.groupAdmin (apis/group-admin.ts::GroupAdminApi). + // Friend methods (handleRequest/delete/setRemark) moved to + // apis.friend. + // GroupFile methods (upload/uploadPrivate/publish/list/getUrl/ + // getPrivateUrl/{Ptt,Video}Url/getPrivate{Ptt,Video}Url/delete/move/ + // createFolder/deleteFolder/renameFolder/getCount) moved to + // apis.groupFile (apis/group-file.ts::GroupFileApi). + // Forward methods (upload / fetch) moved to apis.forward. + // Interaction methods (sendPoke/sendLike/setReaction/setEssence/ + // getEmojiLikes) moved to apis.interaction. + // recall* / markRead* moved to apis/message.ts::MessageApi. + // GroupAlbum methods (list/upload/getMediaList/comment/like/delete) + // moved to apis.groupAlbum (apis/group-album.ts::GroupAlbumApi). + // Web methods (getHonorInfo / forceFetchClientKey / getEssence / + // getEssenceAll / sendNotice / getNotice / deleteNotice / + // getCookiesStr / getCsrfToken / getCredentials) moved to apis.web. + // Profile methods (setOnlineStatus / setDiyOnlineStatus / setProfile / + // setSelfLongNick / setInputStatus / setAvatar / setGroupAvatar / + // fetchCustomFace / getLike / getUnidirectionalFriendList) moved to + // apis.profile. + // Misc methods (translateEn2Zh / getMiniAppArk / + // clickInlineKeyboardButton / sendGroupSign) moved to apis.misc. - // --- Delegated: Admin / action methods --- - - async muteGroupMember(groupId: number, userId: number, duration: number): Promise { return muteGroupMember_(this, groupId, userId, duration); } - async muteGroupAll(groupId: number, enable: boolean): Promise { return muteGroupAll_(this, groupId, enable); } - async setGroupAddOption(groupId: number, addType: number): Promise { return setGroupAddOption_(this, groupId, addType); } - async setGroupSearch(groupId: number): Promise { return setGroupSearch_(this, groupId); } - async kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise { return kickGroupMember_(this, groupId, userId, reject, reason); } - async kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise { return kickGroupMembers_(this, groupId, userIds, reject); } - async leaveGroup(groupId: number): Promise { return leaveGroup_(this, groupId); } - async setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise { return setGroupAdmin_(this, groupId, userId, enable); } - async setGroupCard(groupId: number, userId: number, card: string): Promise { return setGroupCard_(this, groupId, userId, card); } - async setGroupName(groupId: number, name: string): Promise { return setGroupName_(this, groupId, name); } - async setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise { return setGroupSpecialTitle_(this, groupId, userId, title); } - async setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise { return setFriendAddRequest_(this, uidOrFlag, approve); } - async deleteFriend(userId: number, block = false): Promise { return deleteFriend_(this, userId, block); } - async uploadGroupFile(groupId: number, file: string, name = '', folderId = '/', uploadFile = true): Promise<{ fileId: string | null }> { - return uploadGroupFile_(this, groupId, file, name, folderId, uploadFile); - } - async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> { - return uploadPrivateFile_(this, userId, file, name, uploadFile); - } - async sendGroupFileMessage(groupId: number, fileId: string): Promise { - return sendGroupFileMessage_(this, groupId, fileId); - } - async fetchGroupFiles(groupId: number, folderId = '/'): Promise { return fetchGroupFiles_(this, groupId, folderId); } - async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise { return fetchGroupFileUrl_(this, groupId, fileId, busId); } - async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); } - async fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise { return fetchGroupPttUrlByNode_(this, groupId, node); } - async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise { return fetchPrivatePttUrlByNode_(this, node); } - async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise { return fetchGroupVideoUrlByNode_(this, groupId, node); } - async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise { return fetchPrivateVideoUrlByNode_(this, node); } - async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { return uploadForwardNodes_(this, nodes, groupId, userId); } - async fetchForwardNodes(resId: string): Promise { return fetchForwardNodes_(this, resId); } - async deleteGroupFile(groupId: number, fileId: string): Promise { return deleteGroupFile_(this, groupId, fileId); } - async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); } - async createGroupFileFolder(groupId: number, name: string, parentId = '/'): Promise { return createGroupFileFolder_(this, groupId, name, parentId); } - async deleteGroupFileFolder(groupId: number, folderId: string): Promise { return deleteGroupFileFolder_(this, groupId, folderId); } - async renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise { return renameGroupFileFolder_(this, groupId, folderId, newFolderName); } - async setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason = '', filtered = false): Promise { return setGroupAddRequest_(this, groupId, sequence, eventType, approve, reason, filtered); } - async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { return sendPoke_(this, isGroup, peerUin, targetUin); } - async sendLike(userId: number, count: number): Promise { return sendLike_(this, userId, count); } - async setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise { return setGroupEssence_(this, groupId, sequence, random, enable); } - async setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise { return setGroupReaction_(this, groupId, sequence, code, isSet); } - async recallGroupMessage(groupId: number, sequence: number): Promise { return recallGroupMessage_(this, groupId, sequence); } - async recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise { return recallPrivateMessage_(this, userUin, clientSeq, msgSeq, random, timestamp); } - async markGroupMsgAsRead(groupId: number, sequence: number): Promise { return markGroupMsgAsRead_(this, groupId, sequence); } - async markPrivateMsgAsRead(userId: number, sequence: number): Promise { return markPrivateMsgAsRead_(this, userId, sequence); } - async setFriendRemark(userId: number, remark: string): Promise { return setFriendRemark_(this, userId, remark); } - async setGroupRemark(groupId: number, remark: string): Promise { return setGroupRemark_(this, groupId, remark); } - async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise { - return getGroupHonorInfo_(this, groupId, type); - } - async forceFetchClientKey(): Promise { return forceFetchClientKey_(this)} - async getGroupEssence(groupId: number, pageStart: number = 0, pageLimit: number = 50): Promise { - return getGroupEssence_(this, groupId, pageStart, pageLimit); - } - - async getGroupEssenceAll(groupId: number): Promise { - return getGroupEssenceAll_(this, groupId); - } - - async getGroupAlbumList(groupId: number): Promise { - return getGroupAlbumListWeb_(this, groupId); - } - - async uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise { - return uploadImageToGroupAlbumWeb_(this, groupId, albumId, albumName, filePath); - } - - async getGroupAlbumMediaList(groupId: number, albumId: string, attachInfo?: string): Promise { - return getGroupAlbumMediaList_(this, groupId, albumId, attachInfo); - } - - async commentGroupAlbumMedia(groupId: number, albumId: string, lloc: string, content: string): Promise { - return commentGroupAlbumMedia_(this, groupId, albumId, lloc, content); - } - - async likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise { - return likeGroupAlbumMedia_(this, groupId, albumId, batchId, lloc, isLike); - } - - async deleteGroupAlbumMedia(groupId: number, albumId: string, lloc: string): Promise { - return deleteGroupAlbumMedia_(this, groupId, albumId, lloc); - } - - async sendGroupNotice(groupId: number, content: string, options?: any) { - return sendGroupNotice_(this, groupId, content, options); - } - - async getGroupNotice(groupId: number) { - return getGroupNotice_(this, groupId); - } - - async deleteGroupNotice(groupId: number, fid: string): Promise { - return deleteGroupNotice_(this, groupId, fid); - } - - async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); } - - async getGroupAtAllRemain(groupId: number) { - return getGroupAtAllRemain_(this, groupId); - } - // extend - async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise { - return setOnlineStatus_(this, status, extStatus, batteryStatus); - } - async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise { - return setDiyOnlineStatus_(this, faceId, wording, faceType); - } - async setProfile(nickname?: string, personalNote?: string): Promise { - return setProfile_(this, nickname, personalNote); - } - async getCookiesStr(domain: string): Promise { return getCookiesStr_(this, domain); } - async getCsrfToken(): Promise { return getCsrfToken_(this); } - async getCredentials(domain: string) { return getCredentials_(this, domain); } - async getProfileLike(userId?: number, start?: number, limit?: number) { - return getProfileLike_(this, userId, start, limit); - } - async getUnidirectionalFriendList() { - return getUnidirectionalFriendList_(this); - } - async setSelfLongNick(longNick: string) { - return setSelfLongNick_(this, longNick); - } - async setInputStatus(userId: number, eventType: number) { - return setInputStatus_(this, userId, eventType); - } - async translateEn2Zh(words: string[]) { - return translateEn2Zh_(this, words); - } - async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) { - return getMiniAppArk_(this, type, title, desc, picUrl, jumpUrl); - } - async clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) { - return clickInlineKeyboardButton_(this, groupId, botAppid, buttonId, callbackData, msgSeq); - } - async sendGroupSign(groupId: number) { - return sendGroupSign_(this, groupId); - } - async setAvatar(source: string): Promise { - return setAvatar_(this, source); - } - async setGroupAvatar(groupId: number, source: string): Promise { - return setGroupAvatar_(this, groupId, source); - } - async fetchCustomFace(count?: number): Promise { - return fetchCustomFace_(this, count); - } - async getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) { - return getEmojiLikes_(this, groupId, sequence, emojiId, emojiType, count, cookie); - } - - // --- Tier-2 napcat-parity extras (group todo, stranger status, AI voice) --- - - async setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise { - return setGroupTodo_(this, groupId, BigInt(msgSeq)); - } - async completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise { - return completeGroupTodo_(this, groupId, BigInt(msgSeq)); - } - async cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise { - return cancelGroupTodo_(this, groupId, BigInt(msgSeq)); - } - async getStrangerStatus(uin: number): Promise { - return getStrangerStatus_(this, uin); - } - async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatTypeT): Promise { - return fetchAiVoiceList_(this, groupId, chatType); - } - async fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: AiVoiceChatTypeT) { - return fetchAiVoice_(this, groupId, voiceId, text, chatType); - } + // --- Tier-2 napcat-parity extras (group todo / stranger status / + // AI voice) moved to apis.extras. --- } diff --git a/packages/core/src/bridge/manager.ts b/packages/core/src/bridge/manager.ts index 951b538e..c31a8255 100644 --- a/packages/core/src/bridge/manager.ts +++ b/packages/core/src/bridge/manager.ts @@ -1,13 +1,8 @@ -// BridgeManager — manages per-UIN Bridge sessions. -// onPacket() is the single entry point for parsed hook packets; -// HookManager wires it as the default packet sink for every HookSession. -// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp - -import type { PacketInfo } from '../protocol/types'; +import type { PacketSender } from '@snowluma/common/packet-sender'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import { createLogger } from '@snowluma/common/logger'; import { Bridge } from './bridge'; -import { IdentityService } from './identity-service'; -import type { PacketSender } from '../protocol/packet-sender'; -import { createLogger } from '../utils/logger'; +import { IdentityService } from '@snowluma/bridge/identity-service'; export type SessionStartedCallback = (uin: string, bridge: Bridge) => void; export type SessionClosedCallback = (uin: string) => void; diff --git a/packages/core/src/bridge/proto/action.ts b/packages/core/src/bridge/proto/action.ts deleted file mode 100644 index bf56540e..00000000 --- a/packages/core/src/bridge/proto/action.ts +++ /dev/null @@ -1,103 +0,0 @@ -// Proto schemas for outgoing message actions. -// Port of src/bridge/include/bridge/proto/action.h - -import type { ProtoSchema } from '../../protobuf/decode'; -import { ElemSchema } from './element'; - -// --- Routing --- - -export const RoutingC2CSchema = { - uin: { field: 1, type: 'uint32' as const }, - uid: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const RoutingGroupSchema = { - groupCode: { field: 1, type: 'uint64' as const }, -} satisfies ProtoSchema; - -// `Trans0x211` is the c2c-file scene's routing header (Lagrange.Core -// `Routing/Trans0X211.cs`). See proton/action.ts:RoutingTrans0x211 -// for the rationale — c2c file sends *must* route through this slot, -// not `c2c`, or the server rejects them. -export const RoutingTrans0x211Schema = { - toUin: { field: 1, type: 'uint64' as const }, - ccCmd: { field: 2, type: 'uint32' as const }, - uid: { field: 8, type: 'string' as const }, -} satisfies ProtoSchema; - -export const RoutingHeadSchema = { - c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema }, - grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema }, - trans0x211: { field: 15, type: 'message' as const, schema: RoutingTrans0x211Schema }, -} satisfies ProtoSchema; - -// --- Content Head (for send) --- - -export const SendContentHeadSchema = { - type: { field: 1, type: 'uint32' as const }, - subType: { field: 2, type: 'uint32' as const }, - c2cCmd: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- Message Control --- - -export const MessageControlSchema = { - msgFlag: { field: 1, type: 'int32' as const }, -} satisfies ProtoSchema; - -// --- RichText (for send — only elems) --- - -export const SendRichTextSchema = { - elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema }, -} satisfies ProtoSchema; - -// --- MessageBody (for send) --- - -export const SendMessageBodySchema = { - richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema }, - // C2C file payload — serialised `FileExtra { file: NotOnlineFile }` - // bytes. See proton/action.ts:SendMessageBody for the WHY. - msgContent: { field: 2, type: 'bytes' as const }, -} satisfies ProtoSchema; - -// --- SendMessageRequest --- - -export const SendMessageRequestSchema = { - routingHead: { field: 1, type: 'message' as const, schema: RoutingHeadSchema }, - contentHead: { field: 2, type: 'message' as const, schema: SendContentHeadSchema }, - messageBody: { field: 3, type: 'message' as const, schema: SendMessageBodySchema }, - clientSequence: { field: 4, type: 'uint32' as const }, - random: { field: 5, type: 'uint32' as const }, - syncCookie: { field: 6, type: 'bytes' as const }, - via: { field: 8, type: 'uint32' as const }, - dataStatist: { field: 9, type: 'uint32' as const }, - ctrl: { field: 12, type: 'message' as const, schema: MessageControlSchema }, - multiSendSeq: { field: 14, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- SendMessageResponse --- - -export const SendMessageResponseSchema = { - result: { field: 1, type: 'int32' as const }, - errMsg: { field: 2, type: 'string' as const }, - timestamp1: { field: 3, type: 'uint32' as const }, - field10: { field: 10, type: 'uint32' as const }, - groupSequence: { field: 11, type: 'uint32' as const }, - timestamp2: { field: 12, type: 'uint32' as const }, - privateSequence: { field: 14, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- MentionExtra (for building @mention text element) --- - -export const MentionExtraSendSchema = { - type: { field: 3, type: 'int32' as const }, - uin: { field: 4, type: 'uint32' as const }, - field5: { field: 5, type: 'int32' as const }, - uid: { field: 9, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- MarkdownData --- - -export const MarkdownDataSchema = { - content: { field: 1, type: 'string' as const }, -} satisfies ProtoSchema; diff --git a/packages/core/src/bridge/proto/element.ts b/packages/core/src/bridge/proto/element.ts deleted file mode 100644 index 94f78dce..00000000 --- a/packages/core/src/bridge/proto/element.ts +++ /dev/null @@ -1,428 +0,0 @@ -// Proto schemas for QQ message elements. -// Port of src/bridge/include/bridge/proto/element.h - -import type { ProtoSchema } from '../../protobuf/decode'; - -// --- Nested / helper schemas --- - -export const CustomFacePbReserveSchema = { - subType: { field: 1, type: 'int32' as const }, - summary: { field: 9, type: 'string' as const }, -} satisfies ProtoSchema; - -export const NotOnlineImagePbReserve2Schema = { - field1: { field: 1, type: 'int32' as const }, - field2: { field: 2, type: 'string' as const }, - field3: { field: 3, type: 'int32' as const }, - field4: { field: 4, type: 'int32' as const }, - field5: { field: 5, type: 'int32' as const }, - field7: { field: 7, type: 'string' as const }, -} satisfies ProtoSchema; - -export const NotOnlineImagePbReserveSchema = { - subType: { field: 1, type: 'int32' as const }, - field3: { field: 3, type: 'int32' as const }, - field4: { field: 4, type: 'int32' as const }, - summary: { field: 8, type: 'string' as const }, - field10: { field: 10, type: 'int32' as const }, - field20: { field: 20, type: 'message' as const, schema: NotOnlineImagePbReserve2Schema }, - url: { field: 30, type: 'string' as const }, - md5Str: { field: 31, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- Core element schemas --- - -export const TextElemSchema = { - str: { field: 1, type: 'string' as const }, - link: { field: 2, type: 'string' as const }, - attr6Buf: { field: 3, type: 'bytes' as const }, - attr7Buf: { field: 4, type: 'bytes' as const }, - buf: { field: 11, type: 'bytes' as const }, - pbReserve: { field: 12, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const FaceElemSchema = { - index: { field: 1, type: 'int32' as const }, - oldData: { field: 2, type: 'bytes' as const }, - buf: { field: 11, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const OnlineImageSchema = { - guid: { field: 1, type: 'bytes' as const }, - filePath: { field: 2, type: 'bytes' as const }, - oldVerSendFile: { field: 3, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const NotOnlineImageSchema = { - filePath: { field: 1, type: 'string' as const }, - fileLen: { field: 2, type: 'uint32' as const }, - downloadPath: { field: 3, type: 'string' as const }, - oldVerSendFile: { field: 4, type: 'bytes' as const }, - imgType: { field: 5, type: 'int32' as const }, - previewsImage: { field: 6, type: 'bytes' as const }, - picMd5: { field: 7, type: 'bytes' as const }, - picHeight: { field: 8, type: 'uint32' as const }, - picWidth: { field: 9, type: 'uint32' as const }, - resId: { field: 10, type: 'string' as const }, - flag: { field: 11, type: 'bytes' as const }, - thumbUrl: { field: 12, type: 'string' as const }, - original: { field: 13, type: 'int32' as const }, - bigUrl: { field: 14, type: 'string' as const }, - origUrl: { field: 15, type: 'string' as const }, - bizType: { field: 16, type: 'int32' as const }, - result: { field: 17, type: 'int32' as const }, - index: { field: 18, type: 'int32' as const }, - opFaceBuf: { field: 19, type: 'bytes' as const }, - oldPicMd5: { field: 20, type: 'bool' as const }, - thumbWidth: { field: 21, type: 'int32' as const }, - thumbHeight: { field: 22, type: 'int32' as const }, - fileId: { field: 23, type: 'int32' as const }, - showLen: { field: 24, type: 'uint32' as const }, - downloadLen: { field: 25, type: 'uint32' as const }, - x400Url: { field: 26, type: 'string' as const }, - x400Width: { field: 27, type: 'int32' as const }, - x400Height: { field: 28, type: 'int32' as const }, - pbRes: { field: 29, type: 'message' as const, schema: NotOnlineImagePbReserveSchema }, -} satisfies ProtoSchema; - -export const TransElemSchema = { - elemType: { field: 1, type: 'int32' as const }, - elemValue: { field: 2, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const MarketFaceSchema = { - faceName: { field: 1, type: 'string' as const }, - itemType: { field: 2, type: 'uint32' as const }, - faceInfo: { field: 3, type: 'uint32' as const }, - faceId: { field: 4, type: 'bytes' as const }, - tabId: { field: 5, type: 'uint32' as const }, - subType: { field: 6, type: 'uint32' as const }, - key: { field: 7, type: 'bytes' as const }, - param: { field: 8, type: 'bytes' as const }, - mediaType: { field: 9, type: 'uint32' as const }, - imageWidth: { field: 10, type: 'uint32' as const }, - imageHeight: { field: 11, type: 'uint32' as const }, - mobileParam: { field: 12, type: 'bytes' as const }, - pbReserve: { field: 13, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const CustomFaceSchema = { - guid: { field: 1, type: 'bytes' as const }, - filePath: { field: 2, type: 'string' as const }, - shortcut: { field: 3, type: 'string' as const }, - buffer: { field: 4, type: 'bytes' as const }, - flag: { field: 5, type: 'bytes' as const }, - oldData: { field: 6, type: 'bytes' as const }, - fileId: { field: 7, type: 'uint32' as const }, - serverIp: { field: 8, type: 'int32' as const }, - serverPort: { field: 9, type: 'int32' as const }, - fileType: { field: 10, type: 'int32' as const }, - signature: { field: 11, type: 'bytes' as const }, - useful: { field: 12, type: 'int32' as const }, - md5: { field: 13, type: 'bytes' as const }, - thumbUrl: { field: 14, type: 'string' as const }, - bigUrl: { field: 15, type: 'string' as const }, - origUrl: { field: 16, type: 'string' as const }, - bizType: { field: 17, type: 'int32' as const }, - repeatIndex: { field: 18, type: 'int32' as const }, - repeatImage: { field: 19, type: 'int32' as const }, - imageType: { field: 20, type: 'int32' as const }, - index: { field: 21, type: 'int32' as const }, - width: { field: 22, type: 'int32' as const }, - height: { field: 23, type: 'int32' as const }, - source: { field: 24, type: 'int32' as const }, - size: { field: 25, type: 'uint32' as const }, - origin: { field: 26, type: 'int32' as const }, - thumbWidth: { field: 27, type: 'int32' as const }, - thumbHeight: { field: 28, type: 'int32' as const }, - showLen: { field: 29, type: 'int32' as const }, - downloadLen: { field: 30, type: 'int32' as const }, - x400Url: { field: 31, type: 'string' as const }, - x400Width: { field: 32, type: 'int32' as const }, - x400Height: { field: 33, type: 'int32' as const }, - pbRes: { field: 34, type: 'message' as const, schema: CustomFacePbReserveSchema }, -} satisfies ProtoSchema; - -export const RichMsgSchema = { - template1: { field: 1, type: 'bytes' as const }, - serviceId: { field: 2, type: 'int32' as const }, - msgResId: { field: 3, type: 'bytes' as const }, - rand: { field: 4, type: 'int32' as const }, - seq: { field: 5, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const GroupFileElemSchema = { - filename: { field: 1, type: 'string' as const }, - fileSize: { field: 2, type: 'uint64' as const }, - fileId: { field: 3, type: 'string' as const }, - batchId: { field: 4, type: 'string' as const }, - fileKey: { field: 5, type: 'string' as const }, - mark: { field: 6, type: 'bytes' as const }, - sequence: { field: 7, type: 'uint64' as const }, - batchItemId: { field: 8, type: 'bytes' as const }, - feedMsgTime: { field: 9, type: 'int32' as const }, - pbReserve: { field: 10, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const ExtraInfoSchema = { - nick: { field: 1, type: 'bytes' as const }, - groupCard: { field: 2, type: 'bytes' as const }, - level: { field: 3, type: 'int32' as const }, - flags: { field: 4, type: 'int32' as const }, - groupMask: { field: 5, type: 'int32' as const }, - msgTailId: { field: 6, type: 'int32' as const }, - senderTitle: { field: 7, type: 'bytes' as const }, - apnsTips: { field: 8, type: 'bytes' as const }, - uin: { field: 9, type: 'uint64' as const }, - msgStateFlag: { field: 10, type: 'int32' as const }, - apnsSoundType: { field: 11, type: 'int32' as const }, - newGroupFlag: { field: 12, type: 'int32' as const }, -} satisfies ProtoSchema; - -export const VideoFileSchema = { - fileUuid: { field: 1, type: 'string' as const }, - fileMd5: { field: 2, type: 'bytes' as const }, - fileName: { field: 3, type: 'string' as const }, - fileFormat: { field: 4, type: 'int32' as const }, - fileTime: { field: 5, type: 'int32' as const }, - fileSize: { field: 6, type: 'int32' as const }, - thumbWidth: { field: 7, type: 'int32' as const }, - thumbHeight: { field: 8, type: 'int32' as const }, - thumbFileMd5: { field: 9, type: 'bytes' as const }, - source: { field: 10, type: 'bytes' as const }, - thumbFileSize:{ field: 11, type: 'int32' as const }, - busiType: { field: 12, type: 'int32' as const }, - fromChatType: { field: 13, type: 'int32' as const }, - toChatType: { field: 14, type: 'int32' as const }, - supportProgressive: { field: 15, type: 'bool' as const }, - fileWidth: { field: 16, type: 'int32' as const }, - fileHeight: { field: 17, type: 'int32' as const }, - subBusiType: { field: 18, type: 'int32' as const }, - videoAttr: { field: 19, type: 'int32' as const }, - pbReserve: { field: 24, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const SrcMsgSchema = { - origSeqs: { field: 1, type: 'repeated_uint32' as const }, - senderUin: { field: 2, type: 'uint64' as const }, - time: { field: 3, type: 'int32' as const }, - flag: { field: 4, type: 'int32' as const }, - elemsRaw: { field: 5, type: 'repeated_bytes' as const }, - type: { field: 6, type: 'int32' as const }, - richMsg: { field: 7, type: 'bytes' as const }, - pbReserve: { field: 8, type: 'bytes' as const }, - sourceMsg: { field: 9, type: 'bytes' as const }, - toUin: { field: 10, type: 'uint64' as const }, - troopName: { field: 11, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const LightAppElemSchema = { - data: { field: 1, type: 'bytes' as const }, - msgResid: { field: 2, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const CommonElemSchema = { - serviceType: { field: 1, type: 'int32' as const }, - pbElem: { field: 2, type: 'bytes' as const }, - businessType: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const GeneralFlagsSchema = { - bubbleDiyTextId: { field: 1, type: 'int32' as const }, - groupFlagNew: { field: 2, type: 'int32' as const }, - uin: { field: 3, type: 'uint64' as const }, - longTextFlag: { field: 6, type: 'int32' as const }, - longTextResId: { field: 7, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- Elem (union of all element types) --- - -export const ElemSchema = { - text: { field: 1, type: 'message' as const, schema: TextElemSchema }, - face: { field: 2, type: 'message' as const, schema: FaceElemSchema }, - onlineImage: { field: 3, type: 'message' as const, schema: OnlineImageSchema }, - notOnlineImage: { field: 4, type: 'message' as const, schema: NotOnlineImageSchema }, - transElem: { field: 5, type: 'message' as const, schema: TransElemSchema }, - marketFace: { field: 6, type: 'message' as const, schema: MarketFaceSchema }, - customFace: { field: 8, type: 'message' as const, schema: CustomFaceSchema }, - richMsg: { field: 12, type: 'message' as const, schema: RichMsgSchema }, - groupFile: { field: 13, type: 'message' as const, schema: GroupFileElemSchema }, - extraInfo: { field: 16, type: 'message' as const, schema: ExtraInfoSchema }, - videoFile: { field: 19, type: 'message' as const, schema: VideoFileSchema }, - generalFlags: { field: 37, type: 'message' as const, schema: GeneralFlagsSchema }, - srcMsg: { field: 45, type: 'message' as const, schema: SrcMsgSchema }, - lightApp: { field: 51, type: 'message' as const, schema: LightAppElemSchema }, - commonElem: { field: 53, type: 'message' as const, schema: CommonElemSchema }, -} satisfies ProtoSchema; - -// --- Extra decode types (for CommonElem.pbElem sub-messages) --- - -export const MentionExtraSchema = { - type: { field: 3, type: 'int32' as const }, - uin: { field: 4, type: 'uint32' as const }, - field5: { field: 5, type: 'int32' as const }, - uid: { field: 9, type: 'string' as const }, -} satisfies ProtoSchema; - -export const QFaceExtraSchema = { - packId: { field: 1, type: 'string' as const }, - stickerId: { field: 2, type: 'string' as const }, - qsid: { field: 3, type: 'int32' as const }, - sourceType: { field: 4, type: 'int32' as const }, - stickerType: { field: 5, type: 'int32' as const }, - resultId: { field: 6, type: 'string' as const }, - text: { field: 7, type: 'string' as const }, - randomType: { field: 9, type: 'int32' as const }, -} satisfies ProtoSchema; - -export const QSmallFaceExtraSchema = { - faceId: { field: 1, type: 'uint32' as const }, - preview: { field: 2, type: 'string' as const }, - preview2: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- NTQQ MsgInfo types (CommonElem service_type 48) --- - -export const FileTypeSchema = { - type: { field: 1, type: 'uint32' as const }, - picFormat: { field: 2, type: 'uint32' as const }, - videoFormat: { field: 3, type: 'uint32' as const }, - voiceFormat: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const FileInfoSchema = { - fileSize: { field: 1, type: 'uint32' as const }, - fileHash: { field: 2, type: 'string' as const }, - fileSha1: { field: 3, type: 'string' as const }, - fileName: { field: 4, type: 'string' as const }, - type: { field: 5, type: 'message' as const, schema: FileTypeSchema }, - width: { field: 6, type: 'uint32' as const }, - height: { field: 7, type: 'uint32' as const }, - time: { field: 8, type: 'uint32' as const }, - original: { field: 9, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const IndexNodeSchema = { - info: { field: 1, type: 'message' as const, schema: FileInfoSchema }, - fileUuid: { field: 2, type: 'string' as const }, - storeId: { field: 3, type: 'uint32' as const }, - uploadTime: { field: 4, type: 'uint32' as const }, - ttl: { field: 5, type: 'uint32' as const }, - subType: { field: 6, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const PicUrlExtInfoSchema = { - originalParameter: { field: 1, type: 'string' as const }, - bigParameter: { field: 2, type: 'string' as const }, - thumbParameter: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const PictureInfoSchema = { - urlPath: { field: 1, type: 'string' as const }, - ext: { field: 2, type: 'message' as const, schema: PicUrlExtInfoSchema }, - domain: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const PicExtDataSchema = { - subType: { field: 1, type: 'uint32' as const }, - textSummary: { field: 9, type: 'string' as const }, -} satisfies ProtoSchema; - -export const PicExtBizInfoSchema = { - bizType: { field: 1, type: 'uint32' as const }, - textSummary: { field: 2, type: 'string' as const }, - bytesPbReserveC2c: { field: 11, type: 'bytes' as const }, - extData: { field: 12, type: 'message' as const, schema: PicExtDataSchema }, - fromScene: { field: 1001, type: 'uint32' as const }, - toScene: { field: 1002, type: 'uint32' as const }, - oldFileId: { field: 1003, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const VideoExtBizInfoSchema = { - fromScene: { field: 1, type: 'uint32' as const }, - toScene: { field: 2, type: 'uint32' as const }, - bytesPbReserve: { field: 3, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const PttExtBizInfoSchema = { - srcUin: { field: 1, type: 'uint64' as const }, - pttScene: { field: 2, type: 'uint32' as const }, - pttType: { field: 3, type: 'uint32' as const }, - changeVoice: { field: 4, type: 'uint32' as const }, - waveform: { field: 5, type: 'bytes' as const }, - autoConvertText: { field: 6, type: 'uint32' as const }, - bytesReserve: { field: 11, type: 'bytes' as const }, - bytesPbReserve: { field: 12, type: 'bytes' as const }, - bytesGeneralFlags: { field: 13, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const ExtBizInfoSchema = { - pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema }, - video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema }, - ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema }, - busiType: { field: 10, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const C2cSourceSchema = { - friendUid: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const TroopSourceSchema = { - groupUin: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const HashSumSchema = { - bytesPbReserveC2c: { field: 201, type: 'message' as const, schema: C2cSourceSchema }, - troopSource: { field: 202, type: 'message' as const, schema: TroopSourceSchema }, -} satisfies ProtoSchema; - -export const MsgInfoBodySchema = { - index: { field: 1, type: 'message' as const, schema: IndexNodeSchema }, - picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema }, - fileExist: { field: 5, type: 'bool' as const }, - hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema }, -} satisfies ProtoSchema; - -export const MsgInfoSchema = { - msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: MsgInfoBodySchema }, - extBizInfo: { field: 2, type: 'message' as const, schema: ExtBizInfoSchema }, -} satisfies ProtoSchema; - -// --- GroupFileExtra (TransElem type=24) --- - -// Field numbers cross-checked against NapCat (component.ts:146) + -// acidify (GroupFileExtra.kt:Inner.Info). Old schema had fileSha at 5 -// / extInfoString at 6 / fileMd5 at 7 which mismatched the real wire -// shape — the server rejected the chat post with `result=79` because -// fileSha bytes were landing where it expected a uint32 (field 5). -// See proton/element.ts for the WHY comment. -export const GroupFileInfoSchema = { - busId: { field: 1, type: 'uint32' as const }, - fileId: { field: 2, type: 'string' as const }, - fileSize: { field: 3, type: 'uint64' as const }, - fileName: { field: 4, type: 'string' as const }, - field5: { field: 5, type: 'uint32' as const }, - fileSha: { field: 6, type: 'bytes' as const }, - extInfoString: { field: 7, type: 'string' as const }, - fileMd5: { field: 8, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const GroupFileExtraInnerSchema = { - info: { field: 2, type: 'message' as const, schema: GroupFileInfoSchema }, -} satisfies ProtoSchema; - -export const GroupFileExtraSchema = { - field1: { field: 1, type: 'uint32' as const }, - fileName: { field: 2, type: 'string' as const }, - display: { field: 3, type: 'string' as const }, - inner: { field: 7, type: 'message' as const, schema: GroupFileExtraInnerSchema }, -} satisfies ProtoSchema; - -// --- Preserve (for message receipt info) --- - -export const PreserveSchema = { - messageId: { field: 3, type: 'uint64' as const }, - senderUid: { field: 6, type: 'string' as const }, - receiverUid: { field: 7, type: 'string' as const }, - clientSequence: { field: 8, type: 'uint32' as const }, -} satisfies ProtoSchema; diff --git a/packages/core/src/bridge/proto/highway.ts b/packages/core/src/bridge/proto/highway.ts deleted file mode 100644 index 11a583e7..00000000 --- a/packages/core/src/bridge/proto/highway.ts +++ /dev/null @@ -1,343 +0,0 @@ -// Proto schemas for highway upload protocol. -// Port of src/bridge/include/bridge/proto/highway.h + action.h (HttpConn) - -import type { ProtoSchema } from '../../protobuf/decode'; -import { - IndexNodeSchema, - PictureInfoSchema, - HashSumSchema, - PicExtBizInfoSchema, - VideoExtBizInfoSchema, - PttExtBizInfoSchema, -} from '../proto/element'; - -// --- DataHighwayHead --- - -export const DataHighwayHeadSchema = { - version: { field: 1, type: 'uint32' as const }, - uin: { field: 2, type: 'string' as const }, - command: { field: 3, type: 'string' as const }, - seq: { field: 4, type: 'uint32' as const }, - retryTimes:{ field: 5, type: 'uint32' as const }, - appId: { field: 6, type: 'uint32' as const }, - dataFlag: { field: 7, type: 'uint32' as const }, - commandId: { field: 8, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const SegHeadSchema = { - serviceId: { field: 1, type: 'uint32' as const }, - filesize: { field: 2, type: 'uint64' as const }, - dataOffset: { field: 3, type: 'uint64' as const }, - dataLength: { field: 4, type: 'uint32' as const }, - retCode: { field: 5, type: 'uint32' as const }, - serviceTicket: { field: 6, type: 'bytes' as const }, - flag: { field: 7, type: 'uint32' as const }, - md5: { field: 8, type: 'bytes' as const }, - fileMd5: { field: 9, type: 'bytes' as const }, - cacheAddr: { field: 10, type: 'uint32' as const }, - cachePort: { field: 13, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const LoginSigHeadSchema = { - loginSigType: { field: 1, type: 'uint32' as const }, - appId: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const ReqDataHighwayHeadSchema = { - msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema }, - msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema }, - bytesReqExtendInfo: { field: 3, type: 'bytes' as const }, - timestamp: { field: 4, type: 'uint64' as const }, - msgLoginSigHead: { field: 5, type: 'message' as const, schema: LoginSigHeadSchema }, -} satisfies ProtoSchema; - -export const RespDataHighwayHeadSchema = { - msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema }, - msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema }, - errorCode: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- Highway extend (NTV2RichMediaHighwayExt) --- - -export const HighwayDomainSchema = { - isEnable: { field: 1, type: 'bool' as const }, - ip: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const HighwayIPv4Schema = { - domain: { field: 1, type: 'message' as const, schema: HighwayDomainSchema }, - port: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const HighwayNetworkSchema = { - ipv4s: { field: 1, type: 'repeated_message' as const, schema: HighwayIPv4Schema }, -} satisfies ProtoSchema; - -export const HighwayHashSchema = { - fileSha1: { field: 1, type: 'repeated_bytes' as const }, -} satisfies ProtoSchema; - -export const HighwayMsgInfoBodySchema = { - index: { field: 1, type: 'message' as const, schema: IndexNodeSchema }, - picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema }, - fileExist: { field: 5, type: 'bool' as const }, - hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema }, -} satisfies ProtoSchema; - -export const NTV2RichMediaHighwayExtSchema = { - fileUuid: { field: 1, type: 'string' as const }, - uKey: { field: 2, type: 'string' as const }, - network: { field: 5, type: 'message' as const, schema: HighwayNetworkSchema }, - msgInfoBody: { field: 6, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema }, - blockSize: { field: 10, type: 'uint32' as const }, - hash: { field: 11, type: 'message' as const, schema: HighwayHashSchema }, -} satisfies ProtoSchema; - -// --- File upload extend (group/private file highway) --- - -export const FileUploadUrlSchema = { - unknown: { field: 1, type: 'int32' as const }, - host: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const FileUploadHostSchema = { - url: { field: 1, type: 'message' as const, schema: FileUploadUrlSchema }, - port: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const FileUploadHostConfigSchema = { - hosts: { field: 200, type: 'repeated_message' as const, schema: FileUploadHostSchema }, -} satisfies ProtoSchema; - -export const FileUploadNameInfoSchema = { - fileName: { field: 100, type: 'string' as const }, -} satisfies ProtoSchema; - -export const FileUploadClientInfoSchema = { - clientType: { field: 100, type: 'int32' as const }, - appId: { field: 200, type: 'string' as const }, - terminalType: { field: 300, type: 'int32' as const }, - clientVer: { field: 400, type: 'string' as const }, - unknown: { field: 600, type: 'int32' as const }, -} satisfies ProtoSchema; - -export const FileUploadFileEntrySchema = { - fileSize: { field: 100, type: 'uint64' as const }, - md5: { field: 200, type: 'bytes' as const }, - checkKey: { field: 300, type: 'bytes' as const }, - md5S2: { field: 400, type: 'bytes' as const }, - fileId: { field: 600, type: 'string' as const }, - uploadKey: { field: 700, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const FileUploadBusiInfoSchema = { - busId: { field: 1, type: 'int32' as const }, - senderUin: { field: 100, type: 'uint64' as const }, - receiverUin: { field: 200, type: 'uint64' as const }, - groupCode: { field: 400, type: 'uint64' as const }, -} satisfies ProtoSchema; - -export const FileUploadEntrySchema = { - busiBuff: { field: 100, type: 'message' as const, schema: FileUploadBusiInfoSchema }, - fileEntry: { field: 200, type: 'message' as const, schema: FileUploadFileEntrySchema }, - clientInfo: { field: 300, type: 'message' as const, schema: FileUploadClientInfoSchema }, - fileNameInfo: { field: 400, type: 'message' as const, schema: FileUploadNameInfoSchema }, - host: { field: 500, type: 'message' as const, schema: FileUploadHostConfigSchema }, -} satisfies ProtoSchema; - -export const FileUploadExtSchema = { - unknown1: { field: 1, type: 'int32' as const }, - unknown2: { field: 2, type: 'int32' as const }, - unknown3: { field: 3, type: 'int32' as const }, - entry: { field: 100, type: 'message' as const, schema: FileUploadEntrySchema }, - unknown200: { field: 200, type: 'int32' as const }, -} satisfies ProtoSchema; - -// --- Encodable MsgInfo (for embedding in message element) --- - -export const EncodableMediaExtBizInfoSchema = { - pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema }, - video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema }, - ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema }, - busiType: { field: 10, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const EncodableMediaMsgInfoSchema = { - msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema }, - extBizInfo: { field: 2, type: 'message' as const, schema: EncodableMediaExtBizInfoSchema }, -} satisfies ProtoSchema; - -// --- HttpConn.0x6ff_501 (highway session) --- - -export const HttpConnSchema = { - field1: { field: 1, type: 'int32' as const }, - field2: { field: 2, type: 'int32' as const }, - field3: { field: 3, type: 'int32' as const }, - field4: { field: 4, type: 'int32' as const }, - field6: { field: 6, type: 'int32' as const }, - serviceTypes: { field: 7, type: 'repeated_uint32' as const }, - field9: { field: 9, type: 'int32' as const }, - field10: { field: 10, type: 'int32' as const }, - field11: { field: 11, type: 'int32' as const }, - ver: { field: 15, type: 'string' as const }, -} satisfies ProtoSchema; - -export const HttpConn0x6FF501RequestSchema = { - httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnSchema }, -} satisfies ProtoSchema; - -export const ServerAddrSchema = { - type: { field: 1, type: 'uint32' as const }, - ip: { field: 2, type: 'uint32' as const }, // fixed32 as uint32 - port: { field: 3, type: 'uint32' as const }, - area: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const ServerInfoSchema = { - serviceType: { field: 1, type: 'uint32' as const }, - serverAddrs: { field: 2, type: 'repeated_message' as const, schema: ServerAddrSchema }, -} satisfies ProtoSchema; - -export const HttpConnResponseSchema = { - sigSession: { field: 1, type: 'bytes' as const }, - sessionKey: { field: 2, type: 'bytes' as const }, - serverInfos: { field: 3, type: 'repeated_message' as const, schema: ServerInfoSchema }, -} satisfies ProtoSchema; - -export const HttpConn0x6FF501ResponseSchema = { - httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnResponseSchema }, -} satisfies ProtoSchema; - -// --- NTV2 Upload Request (for OIDB 0x11C4/0x11C5) --- - -export const NTV2FileTypeSchema = { - type: { field: 1, type: 'uint32' as const }, - picFormat: { field: 2, type: 'uint32' as const }, - videoFormat: { field: 3, type: 'uint32' as const }, - voiceFormat: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2FileInfoSchema = { - fileSize: { field: 1, type: 'uint32' as const }, - fileHash: { field: 2, type: 'string' as const }, - fileSha1: { field: 3, type: 'string' as const }, - fileName: { field: 4, type: 'string' as const }, - type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema }, - width: { field: 6, type: 'uint32' as const }, - height: { field: 7, type: 'uint32' as const }, - time: { field: 8, type: 'uint32' as const }, - original: { field: 9, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2UploadInfoSchema = { - fileInfo: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema }, - subFileType: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// The NTV2 upload request + response carry the same ExtBizInfo shape that -// element-side incoming-message decoding uses. Pulling those schemas in -// directly (instead of redefining stub copies) keeps the round-trip -// `server response → finalizeMediaMsgInfo → commonElem.pbElem` from -// silently dropping fields the QQ NT server later validates against — -// the video `fromScene`/`toScene` drop was already responsible for c2c -// `result=79` rejections on `send_private_msg [{type:'video'}]`. -export const NTV2ExtBizInfoSchema = { - pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema }, - video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema }, - ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema }, - busiType: { field: 10, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2UploadReqSchema = { - uploadInfo: { field: 1, type: 'repeated_message' as const, schema: NTV2UploadInfoSchema }, - tryFastUploadCompleted: { field: 2, type: 'bool' as const }, - srvSendMsg: { field: 3, type: 'bool' as const }, - clientRandomId: { field: 4, type: 'uint64' as const }, - compatQmsgSceneType: { field: 5, type: 'uint32' as const }, - extBizInfo: { field: 6, type: 'message' as const, schema: NTV2ExtBizInfoSchema }, - clientSeq: { field: 7, type: 'uint32' as const }, - noNeedCompatMsg: { field: 8, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const NTV2C2CUserInfoSchema = { - accountType: { field: 1, type: 'uint32' as const }, - targetUid: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const NTV2GroupInfoSchema = { - groupUin: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2UploadSceneInfoSchema = { - requestType: { field: 101, type: 'uint32' as const }, - businessType: { field: 102, type: 'uint32' as const }, - sceneType: { field: 200, type: 'uint32' as const }, - c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema }, - group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema }, -} satisfies ProtoSchema; - -export const NTV2CommonHeadSchema = { - requestId: { field: 1, type: 'uint32' as const }, - command: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2ClientMetaSchema = { - agentType: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2UploadReqHeadSchema = { - common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema }, - scene: { field: 2, type: 'message' as const, schema: NTV2UploadSceneInfoSchema }, - client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema }, -} satisfies ProtoSchema; - -export const NTV2UploadRichMediaReqSchema = { - reqHead: { field: 1, type: 'message' as const, schema: NTV2UploadReqHeadSchema }, - upload: { field: 2, type: 'message' as const, schema: NTV2UploadReqSchema }, -} satisfies ProtoSchema; - -// --- NTV2 Upload Response --- - -export const NTV2IPv4Schema = { - outIp: { field: 1, type: 'uint32' as const }, - outPort: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2SubFileInfoRespSchema = { - subType: { field: 1, type: 'uint32' as const }, - uKey: { field: 2, type: 'string' as const }, - uKeyTtl: { field: 3, type: 'uint32' as const }, - ipv4s: { field: 4, type: 'repeated_message' as const, schema: NTV2IPv4Schema }, -} satisfies ProtoSchema; - -export const NTV2UploadRespMsgInfoSchema = { - msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema }, - extBizInfo: { field: 2, type: 'message' as const, schema: NTV2ExtBizInfoSchema }, -} satisfies ProtoSchema; - -export const NTV2UploadRespBodySchema = { - uKey: { field: 1, type: 'string' as const }, - uKeyTtl: { field: 2, type: 'uint32' as const }, - ipv4s: { field: 3, type: 'repeated_message' as const, schema: NTV2IPv4Schema }, - msgSeq: { field: 5, type: 'uint64' as const }, - msgInfo: { field: 6, type: 'message' as const, schema: NTV2UploadRespMsgInfoSchema }, - subFileInfos: { field: 10, type: 'repeated_message' as const, schema: NTV2SubFileInfoRespSchema }, -} satisfies ProtoSchema; - -export const NTV2UploadRespHeadSchema = { - common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema }, - retCode: { field: 2, type: 'uint32' as const }, - message: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const NTV2UploadRichMediaRespSchema = { - respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema }, - upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema }, -} satisfies ProtoSchema; - -// (The legacy `GroupAvatarUploadExtSchema` definition that briefly -// lived here in PR #31 was removed: it was a residual artifact of an -// alternative `setGroupAvatar` implementation that got dropped during -// review — the canonical Lagrange-derived `GroupAvatarExtraSchema` -// further up this file is the one `actions/profile.setGroupAvatar` -// actually uses.) diff --git a/packages/core/src/bridge/proto/longmsg.ts b/packages/core/src/bridge/proto/longmsg.ts deleted file mode 100644 index 2ac29beb..00000000 --- a/packages/core/src/bridge/proto/longmsg.ts +++ /dev/null @@ -1,68 +0,0 @@ -import type { ProtoSchema } from '../../protobuf/decode'; -import { PushMsgBodySchema } from './message'; - -export const LongMsgUidSchema = { - uid: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const LongMsgSettingsSchema = { - field1: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'uint32' as const }, - field4: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const SendLongMsgInfoSchema = { - type: { field: 1, type: 'uint32' as const }, - uid: { field: 2, type: 'message' as const, schema: LongMsgUidSchema }, - groupUin: { field: 3, type: 'uint32' as const }, - payload: { field: 4, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const SendLongMsgReqSchema = { - info: { field: 2, type: 'message' as const, schema: SendLongMsgInfoSchema }, - settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema }, -} satisfies ProtoSchema; - -export const SendLongMsgRespResultSchema = { - resId: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const SendLongMsgRespSchema = { - result: { field: 2, type: 'message' as const, schema: SendLongMsgRespResultSchema }, - settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema }, -} satisfies ProtoSchema; - -export const RecvLongMsgInfoSchema = { - uid: { field: 1, type: 'message' as const, schema: LongMsgUidSchema }, - resId: { field: 2, type: 'string' as const }, - acquire: { field: 3, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const RecvLongMsgReqSchema = { - info: { field: 1, type: 'message' as const, schema: RecvLongMsgInfoSchema }, - settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema }, -} satisfies ProtoSchema; - -export const RecvLongMsgRespResultSchema = { - resId: { field: 3, type: 'string' as const }, - payload: { field: 4, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const RecvLongMsgRespSchema = { - result: { field: 1, type: 'message' as const, schema: RecvLongMsgRespResultSchema }, - settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema }, -} satisfies ProtoSchema; - -export const LongMsgContentSchema = { - msgBody: { field: 1, type: 'repeated_message' as const, schema: PushMsgBodySchema }, -} satisfies ProtoSchema; - -export const LongMsgActionSchema = { - actionCommand: { field: 1, type: 'string' as const }, - actionData: { field: 2, type: 'message' as const, schema: LongMsgContentSchema }, -} satisfies ProtoSchema; - -export const LongMsgResultSchema = { - action: { field: 2, type: 'repeated_message' as const, schema: LongMsgActionSchema }, -} satisfies ProtoSchema; diff --git a/packages/core/src/bridge/proto/message.ts b/packages/core/src/bridge/proto/message.ts deleted file mode 100644 index 6b51a157..00000000 --- a/packages/core/src/bridge/proto/message.ts +++ /dev/null @@ -1,120 +0,0 @@ -// Proto schemas for message envelopes (PushMsg). -// Port of src/bridge/include/bridge/proto/message.h - -import type { ProtoSchema } from '../../protobuf/decode'; -import { ElemSchema } from './element'; - -// --- ResponseHead.Grp --- - -export const ResponseGrpSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - memberName: { field: 2, type: 'string' as const }, - groupName: { field: 4, type: 'string' as const }, -} satisfies ProtoSchema; - -export const ResponseForwardSchema = { - friendName: { field: 6, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- ResponseHead --- - -export const ResponseHeadSchema = { - fromUin: { field: 1, type: 'uint32' as const }, - fromUid: { field: 2, type: 'string' as const }, - type: { field: 3, type: 'uint32' as const }, - sigMap: { field: 4, type: 'uint32' as const }, - toUin: { field: 5, type: 'uint32' as const }, - toUid: { field: 6, type: 'string' as const }, - forward: { field: 7, type: 'message' as const, schema: ResponseForwardSchema }, - grp: { field: 8, type: 'message' as const, schema: ResponseGrpSchema }, -} satisfies ProtoSchema; - -// --- ContentHead --- - -export const ContentHeadSchema = { - msgType: { field: 1, type: 'uint32' as const }, - subType: { field: 2, type: 'uint32' as const }, - divSeq: { field: 3, type: 'uint32' as const }, - msgId: { field: 4, type: 'uint32' as const }, - sequence: { field: 5, type: 'uint32' as const }, - timestamp: { field: 6, type: 'uint32' as const }, - field7: { field: 7, type: 'uint64' as const }, - newId: { field: 12, type: 'uint64' as const }, -} satisfies ProtoSchema; - -// --- Ptt (voice) --- - -export const PttSchema = { - fileType: { field: 1, type: 'uint32' as const }, - fileId: { field: 2, type: 'uint64' as const }, - fileUuid: { field: 3, type: 'bytes' as const }, - fileMd5: { field: 4, type: 'bytes' as const }, - fileName: { field: 5, type: 'string' as const }, - fileSize: { field: 6, type: 'uint32' as const }, - groupFileKey: { field: 10, type: 'string' as const }, - fileKey: { field: 14, type: 'bytes' as const }, - time: { field: 19, type: 'uint32' as const }, - format: { field: 29, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- NotOnlineFile (C2C file) --- - -// Field numbers per `dev/Lagrange.Core/.../Component/NotOnlineFile.cs`. -// fields 9 (subcmd), 50 (dangerEvel), 55 (expireTime) are required -// on c2c file SEND (the receiver ignores them); the identification -// fields (1/3/4/5/6/57) are read both directions. -export const NotOnlineFileSchema = { - fileType: { field: 1, type: 'uint32' as const }, - fileUuid: { field: 3, type: 'string' as const }, - fileMd5: { field: 4, type: 'bytes' as const }, - fileName: { field: 5, type: 'string' as const }, - fileSize: { field: 6, type: 'uint64' as const }, - subcmd: { field: 9, type: 'uint32' as const }, - dangerEvel: { field: 50, type: 'uint32' as const }, - expireTime: { field: 55, type: 'uint32' as const }, - fileHash: { field: 57, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- RichText --- - -export const RichTextSchema = { - elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema }, - notOnlineFile: { field: 3, type: 'message' as const, schema: NotOnlineFileSchema }, - ptt: { field: 4, type: 'message' as const, schema: PttSchema }, -} satisfies ProtoSchema; - -// --- MessageBody --- - -export const MessageBodySchema = { - richText: { field: 1, type: 'message' as const, schema: RichTextSchema }, - msgContent: { field: 2, type: 'bytes' as const }, -} satisfies ProtoSchema; - -// --- FileExtra (for C2C file in msg_content) --- -// -// `FileExtra { file: NotOnlineFile }` is the wrapper QQ-NT actually -// uses at `MessageBody.msgContent` for c2c file sends. The previous -// `FileExtraInfoSchema` had fileSize=1, fileName=2, fileMd5=3, -// fileUuid=4, fileHash=5 — every field at the wrong tag, so received -// c2c-file payloads silently failed to parse. Consolidated to the -// shared `NotOnlineFileSchema` (Lagrange.Core's `FileExtra.cs` does -// the same — `[ProtoMember(1)] public NotOnlineFile? File`). - -export const FileExtraSchema = { - file: { field: 1, type: 'message' as const, schema: NotOnlineFileSchema }, -} satisfies ProtoSchema; - -// --- PushMsgBody --- - -export const PushMsgBodySchema = { - responseHead: { field: 1, type: 'message' as const, schema: ResponseHeadSchema }, - contentHead: { field: 2, type: 'message' as const, schema: ContentHeadSchema }, - body: { field: 3, type: 'message' as const, schema: MessageBodySchema }, -} satisfies ProtoSchema; - -// --- PushMsg (top-level) --- - -export const PushMsgSchema = { - message: { field: 1, type: 'message' as const, schema: PushMsgBodySchema }, - status: { field: 3, type: 'int32' as const }, -} satisfies ProtoSchema; diff --git a/packages/core/src/bridge/proto/notify.ts b/packages/core/src/bridge/proto/notify.ts deleted file mode 100644 index 2121ddad..00000000 --- a/packages/core/src/bridge/proto/notify.ts +++ /dev/null @@ -1,245 +0,0 @@ -// Proto schemas for notification types. -// Port of src/bridge/include/bridge/proto/notify.h - -import type { ProtoSchema } from '../../protobuf/decode'; - -export const OperatorField1Schema = { - uid: { field: 1, type: 'string' as const }, - field2: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'bytes' as const }, - field4: { field: 4, type: 'uint32' as const }, - field5: { field: 5, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const OperatorInfoSchema = { - operatorField: { field: 1, type: 'message' as const, schema: OperatorField1Schema }, -} satisfies ProtoSchema; - -export const GroupChangeSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - flag: { field: 2, type: 'uint32' as const }, - memberUid: { field: 3, type: 'string' as const }, - decreaseType: { field: 4, type: 'uint32' as const }, - operatorBytes: { field: 5, type: 'bytes' as const }, - increaseType: { field: 6, type: 'uint32' as const }, - field7: { field: 7, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const GroupAdminExtraSchema = { - adminUid: { field: 1, type: 'string' as const }, - isPromote: { field: 2, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const GroupAdminBodySchema = { - extraDisable: { field: 1, type: 'message' as const, schema: GroupAdminExtraSchema }, - extraEnable: { field: 2, type: 'message' as const, schema: GroupAdminExtraSchema }, -} satisfies ProtoSchema; - -export const GroupAdminSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - flag: { field: 2, type: 'uint32' as const }, - isPromote: { field: 3, type: 'bool' as const }, - body: { field: 4, type: 'message' as const, schema: GroupAdminBodySchema }, -} satisfies ProtoSchema; - -export const InvitationInnerSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'uint32' as const }, - field4: { field: 4, type: 'uint32' as const }, - targetUid: { field: 5, type: 'string' as const }, - invitorUid: { field: 6, type: 'string' as const }, - field7: { field: 7, type: 'uint32' as const }, - field9: { field: 9, type: 'uint32' as const }, - field10: { field: 10, type: 'bytes' as const }, - field11: { field: 11, type: 'uint32' as const }, - field12: { field: 12, type: 'string' as const }, -} satisfies ProtoSchema; - -export const InvitationInfoSchema = { - inner: { field: 1, type: 'message' as const, schema: InvitationInnerSchema }, -} satisfies ProtoSchema; - -export const GroupInvitationSchema = { - cmd: { field: 1, type: 'int32' as const }, - info: { field: 2, type: 'message' as const, schema: InvitationInfoSchema }, -} satisfies ProtoSchema; - -export const GroupInviteSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'uint32' as const }, - field4: { field: 4, type: 'uint32' as const }, - invitorUid: { field: 5, type: 'string' as const }, - hashes: { field: 6, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const GroupJoinSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - targetUid: { field: 3, type: 'string' as const }, - field4: { field: 4, type: 'uint32' as const }, - field6: { field: 6, type: 'uint32' as const }, - field7: { field: 7, type: 'string' as const }, - field8: { field: 8, type: 'uint32' as const }, - field9: { field: 9, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const FriendRequestInfoSchema = { - targetUid: { field: 1, type: 'string' as const }, - sourceUid: { field: 2, type: 'string' as const }, - newSource: { field: 5, type: 'string' as const }, - message: { field: 10, type: 'string' as const }, - source: { field: 11, type: 'string' as const }, -} satisfies ProtoSchema; - -export const FriendRequestSchema = { - info: { field: 1, type: 'message' as const, schema: FriendRequestInfoSchema }, -} satisfies ProtoSchema; - -export const FriendRecallTipInfoSchema = { - tip: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const FriendRecallInfoSchema = { - fromUid: { field: 1, type: 'string' as const }, - toUid: { field: 2, type: 'string' as const }, - clientSequence: { field: 3, type: 'uint32' as const }, - newId: { field: 4, type: 'uint64' as const }, - time: { field: 5, type: 'uint32' as const }, - random: { field: 6, type: 'uint32' as const }, - pkgNum: { field: 7, type: 'uint32' as const }, - pkgIndex: { field: 8, type: 'uint32' as const }, - divSeq: { field: 9, type: 'uint32' as const }, - tipInfo: { field: 13, type: 'message' as const, schema: FriendRecallTipInfoSchema }, -} satisfies ProtoSchema; - -export const FriendRecallSchema = { - info: { field: 1, type: 'message' as const, schema: FriendRecallInfoSchema }, - instId: { field: 2, type: 'uint32' as const }, - appId: { field: 3, type: 'uint32' as const }, - longMessageFlag: { field: 4, type: 'uint32' as const }, - reserved: { field: 5, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const GroupMuteStateSchema = { - targetUid: { field: 1, type: 'string' as const }, - duration: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const GroupMuteDataSchema = { - timestamp: { field: 1, type: 'uint32' as const }, - type: { field: 2, type: 'uint32' as const }, - state: { field: 3, type: 'message' as const, schema: GroupMuteStateSchema }, -} satisfies ProtoSchema; - -export const GroupMuteSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - subType: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'uint32' as const }, - operatorUid: { field: 4, type: 'string' as const }, - data: { field: 5, type: 'message' as const, schema: GroupMuteDataSchema }, -} satisfies ProtoSchema; - -export const RecallMessageSchema = { - sequence: { field: 1, type: 'uint32' as const }, - time: { field: 2, type: 'uint32' as const }, - random: { field: 3, type: 'uint32' as const }, - type: { field: 4, type: 'uint32' as const }, - flag: { field: 5, type: 'uint32' as const }, - authorUid: { field: 6, type: 'string' as const }, -} satisfies ProtoSchema; - -export const GroupRecallTipInfoSchema = { - tip: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const GroupRecallSchema = { - operatorUid: { field: 1, type: 'string' as const }, - recallMessages: { field: 3, type: 'repeated_message' as const, schema: RecallMessageSchema }, - userDef: { field: 5, type: 'bytes' as const }, - groupType: { field: 6, type: 'int32' as const }, - opType: { field: 7, type: 'int32' as const }, - tipInfo: { field: 9, type: 'message' as const, schema: GroupRecallTipInfoSchema }, -} satisfies ProtoSchema; - -export const TemplParamSchema = { - name: { field: 1, type: 'string' as const }, - value: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const GeneralGrayTipInfoSchema = { - busiType: { field: 1, type: 'uint64' as const }, - busiId: { field: 2, type: 'uint64' as const }, - ctrlFlag: { field: 3, type: 'uint32' as const }, - c2cType: { field: 4, type: 'uint32' as const }, - serviceType: { field: 5, type: 'uint32' as const }, - templId: { field: 6, type: 'uint64' as const }, - msgTemplParam: { field: 7, type: 'repeated_message' as const, schema: TemplParamSchema }, - content: { field: 8, type: 'string' as const }, -} satisfies ProtoSchema; - -export const EssenceMessageSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - msgSequence: { field: 2, type: 'uint32' as const }, - random: { field: 3, type: 'uint32' as const }, - setFlag: { field: 4, type: 'uint32' as const }, - memberUin: { field: 5, type: 'uint32' as const }, - operatorUin: { field: 6, type: 'uint32' as const }, - timestamp: { field: 7, type: 'uint32' as const }, - msgSequence2: { field: 8, type: 'uint32' as const }, - operatorNickname: { field: 9, type: 'string' as const }, - memberNickname: { field: 10, type: 'string' as const }, - setFlag2: { field: 11, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NotifyMessageBodySchema = { - type: { field: 1, type: 'uint32' as const }, - groupUin: { field: 4, type: 'uint32' as const }, - eventParam: { field: 5, type: 'bytes' as const }, - recall: { field: 11, type: 'message' as const, schema: GroupRecallSchema }, - field13: { field: 13, type: 'uint32' as const }, - operatorUid: { field: 21, type: 'string' as const }, - generalGrayTip: { field: 26, type: 'message' as const, schema: GeneralGrayTipInfoSchema }, - essenceMessage: { field: 33, type: 'message' as const, schema: EssenceMessageSchema }, - msgSequence: { field: 37, type: 'uint32' as const }, - field39: { field: 39, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// ─── Event0x2DC subType=16: GroupMsgEmojiLike ────────────────────────────── -// -// QQ pushes a Group message emoji reaction (someone tapped an emoji on a -// message in a group). The payload nesting matches NapCat's transformer -// (packet/transformer/proto/message/message.ts → GroupReactNotify); the -// outermost message is preceded by a 7-byte prefix that must be stripped -// before decoding (see the call site). - -export const GroupReactionDataInnerDataTargetSchema = { - seq: { field: 1, type: 'uint64' as const }, -} satisfies ProtoSchema; - -export const GroupReactionDataContentSchema = { - code: { field: 1, type: 'string' as const }, - count: { field: 3, type: 'uint32' as const }, - operatorUid: { field: 4, type: 'string' as const }, - type: { field: 5, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const GroupReactionDataInnerDataSchema = { - groupReactionTarget: { field: 2, type: 'message' as const, schema: GroupReactionDataInnerDataTargetSchema }, - groupReactionDataContent: { field: 3, type: 'message' as const, schema: GroupReactionDataContentSchema }, -} satisfies ProtoSchema; - -export const GroupReactionDataInnerSchema = { - data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerDataSchema }, -} satisfies ProtoSchema; - -export const GroupReactionDataSchema = { - data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerSchema }, -} satisfies ProtoSchema; - -export const GroupReactNotifySchema = { - groupUin: { field: 4, type: 'uint64' as const }, - field13: { field: 13, type: 'uint32' as const }, - groupReactionData: { field: 44, type: 'message' as const, schema: GroupReactionDataSchema }, -} satisfies ProtoSchema; diff --git a/packages/core/src/bridge/proto/oidb-action.ts b/packages/core/src/bridge/proto/oidb-action.ts deleted file mode 100644 index 90b63484..00000000 --- a/packages/core/src/bridge/proto/oidb-action.ts +++ /dev/null @@ -1,1539 +0,0 @@ -// Proto schemas for OIDB action requests. -// Port of src/bridge/include/bridge/proto/oidb.h (action-related structs) -// and src/bridge/src/bridge.cpp (recall message structs) - -import type { ProtoSchema } from '../../protobuf/decode'; - -// --- 0x1253_1: Mute group member --- - -export const OidbMuteMemberBodySchema = { - targetUid: { field: 1, type: 'string' as const }, - duration: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbMuteMemberSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - type: { field: 2, type: 'uint32' as const }, - body: { field: 3, type: 'message' as const, schema: OidbMuteMemberBodySchema }, -} satisfies ProtoSchema; - -// --- 0x89A_0: Mute group all --- - -export const OidbMuteAllStateSchema = { - state: { field: 17, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbMuteAllSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - muteState: { field: 2, type: 'message' as const, schema: OidbMuteAllStateSchema }, -} satisfies ProtoSchema; - -// --- 0x89A_0: Set group add option --- - -export const Oidb0x89a_0AddOptionSettingsSchema = { - addType: { field: 16, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const Oidb0x89a_0AddOptionSchema = { - groupUin: { field: 1, type: 'uint64' as const }, - settings: { field: 2, type: 'message' as const, schema: Oidb0x89a_0AddOptionSettingsSchema }, - field12: { field: 12, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- 0x89A_0: Set group search --- - -export const Oidb0x89a_0SearchSchema = { - groupUin: { field: 1, type: 'uint64' as const }, - settings: { field: 2, type: 'bytes' as const }, - field12: { field: 12, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- 0x8A0_1: Kick group member --- - -export const OidbKickMemberSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - targetUid: { field: 3, type: 'string' as const }, - rejectAddRequest:{ field: 4, type: 'bool' as const }, - reason: { field: 5, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- 0x1097_1: Leave group --- - -export const OidbLeaveGroupSchema = { - groupUin: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- 0xB5D_44: Friend add request --- - -export const OidbFriendRequestActionSchema = { - accept: { field: 1, type: 'uint32' as const }, - targetUid: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- 0x126B_0: Delete friend --- - -export const OidbDeleteFriendField2Field3Schema = { - field1: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbDeleteFriendField2Schema = { - field1: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'message' as const, schema: OidbDeleteFriendField2Field3Schema }, -} satisfies ProtoSchema; - -export const OidbDeleteFriendField1Schema = { - targetUid: { field: 1, type: 'string' as const }, - field2: { field: 2, type: 'message' as const, schema: OidbDeleteFriendField2Schema }, - block: { field: 3, type: 'bool' as const }, - field4: { field: 4, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const OidbDeleteFriendSchema = { - field1: { field: 1, type: 'message' as const, schema: OidbDeleteFriendField1Schema }, -} satisfies ProtoSchema; - -// --- 0x10C8: Group request action --- - -export const OidbGroupRequestBodySchema = { - sequence: { field: 1, type: 'uint64' as const }, - eventType: { field: 2, type: 'uint32' as const }, - groupUin: { field: 3, type: 'uint32' as const }, - message: { field: 4, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupRequestActionSchema = { - accept: { field: 1, type: 'uint32' as const }, - body: { field: 2, type: 'message' as const, schema: OidbGroupRequestBodySchema }, -} satisfies ProtoSchema; - -// --- 0xED3_1: Poke --- - -export const OidbPokeSchema = { - uin: { field: 1, type: 'uint32' as const }, - groupUin: { field: 2, type: 'uint32' as const }, - friendUin: { field: 5, type: 'uint32' as const }, - ext: { field: 6, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- 0xEAC: Group essence --- - -export const OidbEssenceSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - sequence: { field: 2, type: 'uint32' as const }, - random: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- 0x1096_1: Set group admin --- - -export const OidbSetAdminSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - uid: { field: 2, type: 'string' as const }, - isAdmin: { field: 3, type: 'bool' as const }, -} satisfies ProtoSchema; - -// --- 0x8FC_3: Set group card (rename member) --- - -export const OidbRenameMemberBodySchema = { - targetUid: { field: 1, type: 'string' as const }, - targetName: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbRenameMemberSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - body: { field: 2, type: 'message' as const, schema: OidbRenameMemberBodySchema }, -} satisfies ProtoSchema; - -// --- 0x89A_15: Rename group --- - -export const OidbRenameGroupBodySchema = { - targetName: { field: 1, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbRenameGroupSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - body: { field: 2, type: 'message' as const, schema: OidbRenameGroupBodySchema }, -} satisfies ProtoSchema; - -// --- 0x8FC_2: Set group special title --- - -export const OidbSpecialTitleBodySchema = { - targetUid: { field: 1, type: 'string' as const }, - specialTitle:{ field: 5, type: 'string' as const }, - expireTime: { field: 6, type: 'int32' as const }, -} satisfies ProtoSchema; - -export const OidbSpecialTitleSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - body: { field: 2, type: 'message' as const, schema: OidbSpecialTitleBodySchema }, -} satisfies ProtoSchema; - -// --- 0x7E5_104: Send like --- - -export const OidbLikeSchema = { - targetUin: { field: 1, type: 'uint32' as const }, - count: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- 0x10C0_1 / 0x10C0_2: Group request list --- - -export const OidbGroupRequestListSchema = { - count: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- 0xFE1_2: User profile info --- - -export const OidbUserInfoKeySchema = { - key: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// Field 2 USED to be `field2: uint32 = 0`, but newer QQ NT versions -// reinterpret field 2 as `uid: string` / `openid: string` and reject -// the request with "one of uid/openid is invaild" when a varint 0 -// shows up there. NapCat's schema (Oidb.0XFE1_2.ts) only emits `uin` -// and `key[]`, so we match that exactly. -export const OidbUserInfoRequestSchema = { - uin: { field: 1, type: 'uint32' as const }, - keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema }, -} satisfies ProtoSchema; - -export const OidbTwoNumberSchema = { - number1: { field: 1, type: 'uint32' as const }, - number2: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbBytePropertySchema = { - code: { field: 1, type: 'uint32' as const }, - value: { field: 2, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const OidbUserInfoPropertySchema = { - numberProperties: { field: 1, type: 'repeated_message' as const, schema: OidbTwoNumberSchema }, - bytesProperties: { field: 2, type: 'repeated_message' as const, schema: OidbBytePropertySchema }, -} satisfies ProtoSchema; - -export const OidbUserInfoResponseBodySchema = { - uid: { field: 1, type: 'string' as const }, - properties: { field: 2, type: 'message' as const, schema: OidbUserInfoPropertySchema }, - uin: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbUserInfoResponseSchema = { - body: { field: 1, type: 'message' as const, schema: OidbUserInfoResponseBodySchema }, -} satisfies ProtoSchema; - -export const AvatarInfoSchema = { - url: { field: 5, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- FD4_1: Friend list request body fields --- - -export const OidbFriendListNumberSchema = { - numbers: { field: 1, type: 'repeated_uint32' as const }, -} satisfies ProtoSchema; - -export const OidbFriendListBodyItemSchema = { - type: { field: 1, type: 'uint32' as const }, - number: { field: 2, type: 'message' as const, schema: OidbFriendListNumberSchema }, -} satisfies ProtoSchema; - -export const OidbFriendListNextUinSchema = { - uin: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbFriendListRequestSchema = { - friendCount: { field: 2, type: 'uint32' as const }, - field4: { field: 4, type: 'uint32' as const }, - nextUin: { field: 5, type: 'message' as const, schema: OidbFriendListNextUinSchema }, - field6: { field: 6, type: 'uint32' as const }, - field7: { field: 7, type: 'uint32' as const }, - body: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendListBodyItemSchema }, - field10002: { field: 10002, type: 'repeated_uint32' as const }, - field10003: { field: 10003, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- FE5_2: Group list request body (config fields) --- - -export const OidbGroupListConfig1Schema = { - groupOwner: { field: 1, type: 'bool' as const }, - field2: { field: 2, type: 'bool' as const }, - memberMax: { field: 3, type: 'bool' as const }, - memberCount: { field: 4, type: 'bool' as const }, - groupName: { field: 5, type: 'bool' as const }, - field8: { field: 8, type: 'bool' as const }, - field9: { field: 9, type: 'bool' as const }, - field10: { field: 10, type: 'bool' as const }, - field11: { field: 11, type: 'bool' as const }, - field12: { field: 12, type: 'bool' as const }, - field13: { field: 13, type: 'bool' as const }, - field14: { field: 14, type: 'bool' as const }, - field15: { field: 15, type: 'bool' as const }, - field16: { field: 16, type: 'bool' as const }, - field17: { field: 17, type: 'bool' as const }, - field18: { field: 18, type: 'bool' as const }, - question: { field: 19, type: 'bool' as const }, - field20: { field: 20, type: 'bool' as const }, - field22: { field: 22, type: 'bool' as const }, - field23: { field: 23, type: 'bool' as const }, - field24: { field: 24, type: 'bool' as const }, - field25: { field: 25, type: 'bool' as const }, - field26: { field: 26, type: 'bool' as const }, - field27: { field: 27, type: 'bool' as const }, - field28: { field: 28, type: 'bool' as const }, - field29: { field: 29, type: 'bool' as const }, - field30: { field: 30, type: 'bool' as const }, - field31: { field: 31, type: 'bool' as const }, - field32: { field: 32, type: 'bool' as const }, - field5001: { field: 5001, type: 'bool' as const }, - field5002: { field: 5002, type: 'bool' as const }, - field5003: { field: 5003, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const OidbGroupListConfig2Schema = { - field1: { field: 1, type: 'bool' as const }, - field2: { field: 2, type: 'bool' as const }, - field3: { field: 3, type: 'bool' as const }, - field4: { field: 4, type: 'bool' as const }, - field5: { field: 5, type: 'bool' as const }, - field6: { field: 6, type: 'bool' as const }, - field7: { field: 7, type: 'bool' as const }, - field8: { field: 8, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const OidbGroupListConfig3Schema = { - field5: { field: 5, type: 'bool' as const }, - field6: { field: 6, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const OidbGroupListConfigSchema = { - config1: { field: 1, type: 'message' as const, schema: OidbGroupListConfig1Schema }, - config2: { field: 2, type: 'message' as const, schema: OidbGroupListConfig2Schema }, - config3: { field: 3, type: 'message' as const, schema: OidbGroupListConfig3Schema }, -} satisfies ProtoSchema; - -export const OidbGroupListRequestSchema = { - config: { field: 1, type: 'message' as const, schema: OidbGroupListConfigSchema }, -} satisfies ProtoSchema; - -// --- FE7_3: Group member list request body --- - -export const OidbGroupMemberListBodySchema = { - memberName: { field: 10, type: 'bool' as const }, - memberCard: { field: 11, type: 'bool' as const }, - level: { field: 12, type: 'bool' as const }, - field13: { field: 13, type: 'bool' as const }, - field16: { field: 16, type: 'bool' as const }, - specialTitle: { field: 17, type: 'bool' as const }, - field18: { field: 18, type: 'bool' as const }, - field20: { field: 20, type: 'bool' as const }, - field21: { field: 21, type: 'bool' as const }, - joinTimestamp: { field: 100, type: 'bool' as const }, - lastMsgTimestamp: { field: 101, type: 'bool' as const }, - shutUpTimestamp: { field: 102, type: 'bool' as const }, - field103: { field: 103, type: 'bool' as const }, - field104: { field: 104, type: 'bool' as const }, - field105: { field: 105, type: 'bool' as const }, - field106: { field: 106, type: 'bool' as const }, - permission: { field: 107, type: 'bool' as const }, - field200: { field: 200, type: 'bool' as const }, - field201: { field: 201, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const OidbGroupMemberListRequestSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'uint32' as const }, - body: { field: 4, type: 'message' as const, schema: OidbGroupMemberListBodySchema }, - token: { field: 15, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- Group recall message (trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg) --- - -export const GroupRecallInfoSchema = { - sequence: { field: 1, type: 'uint32' as const }, - random: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const GroupRecallSettingsSchema = { - field1: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const GroupRecallRequestSchema = { - type: { field: 1, type: 'uint32' as const }, - groupUin: { field: 2, type: 'uint32' as const }, - info: { field: 3, type: 'message' as const, schema: GroupRecallInfoSchema }, - settings: { field: 4, type: 'message' as const, schema: GroupRecallSettingsSchema }, -} satisfies ProtoSchema; - -// --- C2C (private) recall message (trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg) --- - -export const C2CRecallInfoSchema = { - clientSequence: { field: 1, type: 'uint32' as const }, - random: { field: 2, type: 'uint32' as const }, - messageId: { field: 3, type: 'uint64' as const }, - timestamp: { field: 4, type: 'uint32' as const }, - field5: { field: 5, type: 'uint32' as const }, - messageSequence: { field: 6, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const C2CRecallSettingsSchema = { - field1: { field: 1, type: 'bool' as const }, - field2: { field: 2, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const C2CRecallRequestSchema = { - type: { field: 1, type: 'uint32' as const }, - targetUid:{ field: 3, type: 'string' as const }, - info: { field: 4, type: 'message' as const, schema: C2CRecallInfoSchema }, - settings: { field: 5, type: 'message' as const, schema: C2CRecallSettingsSchema }, - field6: { field: 6, type: 'bool' as const }, -} satisfies ProtoSchema; - -// --- 0x9082_1: Set group reaction --- - -export const OidbGroupReactionSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - sequence: { field: 2, type: 'uint32' as const }, - code: { field: 3, type: 'string' as const }, - // 1 = legacy QQ face (short numeric id like "76"), 2 = unicode emoji - // (decimal codepoint string like "128516" for 😄). Omitting this - // field used to make unicode reactions fail server-side because the - // server defaulted to type=1 and couldn't resolve a 6-digit code. - type: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -// --- 0x6D8_1: Group file list --- - -export const OidbGroupFileListReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - appId: { field: 2, type: 'uint32' as const }, - targetDirectory: { field: 3, type: 'string' as const }, - fileCount: { field: 5, type: 'uint32' as const }, - sortBy: { field: 9, type: 'uint32' as const }, - startIndex: { field: 13, type: 'uint32' as const }, - field17: { field: 17, type: 'uint32' as const }, - field18: { field: 18, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileViewReqSchema = { - list: { field: 2, type: 'message' as const, schema: OidbGroupFileListReqSchema }, -} satisfies ProtoSchema; - -export const OidbGroupFileListFolderRespSchema = { - folderId: { field: 1, type: 'string' as const }, - parentDirectoryId: { field: 2, type: 'string' as const }, - folderName: { field: 3, type: 'string' as const }, - createTime: { field: 4, type: 'uint32' as const }, - modifiedTime: { field: 5, type: 'uint32' as const }, - creatorUin: { field: 6, type: 'uint32' as const }, - creatorName: { field: 7, type: 'string' as const }, - totalFileCount: { field: 8, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileListFileRespSchema = { - fileId: { field: 1, type: 'string' as const }, - fileName: { field: 2, type: 'string' as const }, - fileSize: { field: 3, type: 'uint64' as const }, - busId: { field: 4, type: 'uint32' as const }, - uploadedTime: { field: 6, type: 'uint32' as const }, - expireTime: { field: 7, type: 'uint32' as const }, - modifiedTime: { field: 8, type: 'uint32' as const }, - downloadedTimes: { field: 9, type: 'uint32' as const }, - uploaderName: { field: 14, type: 'string' as const }, - uploaderUin: { field: 15, type: 'uint32' as const }, - parentDirectory: { field: 16, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileListItemRespSchema = { - type: { field: 1, type: 'uint32' as const }, - folderInfo: { field: 2, type: 'message' as const, schema: OidbGroupFileListFolderRespSchema }, - fileInfo: { field: 3, type: 'message' as const, schema: OidbGroupFileListFileRespSchema }, -} satisfies ProtoSchema; - -export const OidbGroupFileListRespSchema = { - retCode: { field: 1, type: 'uint32' as const }, - retMsg: { field: 2, type: 'string' as const }, - clientWording: { field: 3, type: 'string' as const }, - isEnd: { field: 4, type: 'bool' as const }, - items: { field: 5, type: 'repeated_message' as const, schema: OidbGroupFileListItemRespSchema }, -} satisfies ProtoSchema; - -export const OidbGroupFileViewRespSchema = { - list: { field: 2, type: 'message' as const, schema: OidbGroupFileListRespSchema }, -} satisfies ProtoSchema; - -// --- 0x6D6_2 / 0x6D6_3: Group file url & delete --- - -export const OidbGroupFileUploadReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - appId: { field: 2, type: 'uint32' as const }, - busId: { field: 3, type: 'uint32' as const }, - entrance: { field: 4, type: 'uint32' as const }, - targetDirectory: { field: 5, type: 'string' as const }, - fileName: { field: 6, type: 'string' as const }, - localDirectory: { field: 7, type: 'string' as const }, - fileSize: { field: 8, type: 'uint64' as const }, - fileSha1: { field: 9, type: 'bytes' as const }, - fileSha3: { field: 10, type: 'bytes' as const }, - fileMd5: { field: 11, type: 'bytes' as const }, - field15: { field: 15, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileDownloadReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - appId: { field: 2, type: 'uint32' as const }, - busId: { field: 3, type: 'uint32' as const }, - fileId: { field: 4, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileDeleteReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - busId: { field: 3, type: 'uint32' as const }, - fileId: { field: 5, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileMoveReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - appId: { field: 2, type: 'uint32' as const }, - busId: { field: 3, type: 'uint32' as const }, - fileId: { field: 4, type: 'string' as const }, - parentDirectory: { field: 5, type: 'string' as const }, - targetDirectory: { field: 6, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileReqSchema = { - file: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadReqSchema }, - download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadReqSchema }, - delete: { field: 4, type: 'message' as const, schema: OidbGroupFileDeleteReqSchema }, - move: { field: 6, type: 'message' as const, schema: OidbGroupFileMoveReqSchema }, -} satisfies ProtoSchema; - -export const OidbGroupFileUploadRespSchema = { - retCode: { field: 1, type: 'int32' as const }, - retMsg: { field: 2, type: 'string' as const }, - clientWording: { field: 3, type: 'string' as const }, - uploadIp: { field: 4, type: 'string' as const }, - serverDns: { field: 5, type: 'string' as const }, - busId: { field: 6, type: 'int32' as const }, - fileId: { field: 7, type: 'string' as const }, - checkKey: { field: 8, type: 'bytes' as const }, - fileKey: { field: 9, type: 'bytes' as const }, - boolFileExist: { field: 10, type: 'bool' as const }, - uploadPort: { field: 14, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileDownloadRespSchema = { - retCode: { field: 1, type: 'uint32' as const }, - retMsg: { field: 2, type: 'string' as const }, - clientWording: { field: 3, type: 'string' as const }, - downloadIp: { field: 4, type: 'string' as const }, - downloadDns: { field: 5, type: 'string' as const }, - downloadUrl: { field: 6, type: 'bytes' as const }, - saveFileName: { field: 11, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileRetRespSchema = { - retCode: { field: 1, type: 'uint32' as const }, - retMsg: { field: 2, type: 'string' as const }, - clientWording: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileRespSchema = { - upload: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadRespSchema }, - download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadRespSchema }, - delete: { field: 4, type: 'message' as const, schema: OidbGroupFileRetRespSchema }, - move: { field: 6, type: 'message' as const, schema: OidbGroupFileRetRespSchema }, -} satisfies ProtoSchema; - -// --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops --- - -export const OidbGroupFileCreateFolderReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - rootDirectory: { field: 3, type: 'string' as const }, - folderName: { field: 4, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileDeleteFolderReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - folderId: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileRenameFolderReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - folderId: { field: 3, type: 'string' as const }, - newFolderName: { field: 4, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileFolderReqSchema = { - create: { field: 1, type: 'message' as const, schema: OidbGroupFileCreateFolderReqSchema }, - delete: { field: 2, type: 'message' as const, schema: OidbGroupFileDeleteFolderReqSchema }, - rename: { field: 3, type: 'message' as const, schema: OidbGroupFileRenameFolderReqSchema }, -} satisfies ProtoSchema; - -export const OidbGroupFileFolderRetRespSchema = { - retcode: { field: 1, type: 'uint32' as const }, - retMsg: { field: 2, type: 'string' as const }, - clientWording: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileFolderRespSchema = { - create: { field: 1, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema }, - delete: { field: 2, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema }, - rename: { field: 3, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema }, -} satisfies ProtoSchema; - -// --- 0xE37_1200: Private file download url --- - -export const OidbPrivateFileDownloadReqBodySchema = { - receiverUid: { field: 10, type: 'string' as const }, - fileUuid: { field: 20, type: 'string' as const }, - type: { field: 30, type: 'uint32' as const }, - fileHash: { field: 60, type: 'string' as const }, - t2: { field: 601, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbPrivateFileDownloadReqSchema = { - subCommand: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadReqBodySchema }, - field101: { field: 101, type: 'uint32' as const }, - field102: { field: 102, type: 'uint32' as const }, - field200: { field: 200, type: 'uint32' as const }, - field99999: { field: 99999, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const OidbPrivateFileDownloadRespResultSchema = { - server: { field: 20, type: 'string' as const }, - port: { field: 40, type: 'uint32' as const }, - url: { field: 50, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbPrivateFileDownloadRespBodySchema = { - state: { field: 20, type: 'string' as const }, - result: { field: 30, type: 'message' as const, schema: OidbPrivateFileDownloadRespResultSchema }, -} satisfies ProtoSchema; - -export const OidbPrivateFileDownloadRespSchema = { - body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadRespBodySchema }, -} satisfies ProtoSchema; - -// --- 0xE37_1700: Private file upload --- - -export const OidbPrivateFileUploadReqBodySchema = { - senderUid: { field: 10, type: 'string' as const }, - receiverUid: { field: 20, type: 'string' as const }, - fileSize: { field: 30, type: 'uint32' as const }, - fileName: { field: 40, type: 'string' as const }, - md510MCheckSum:{ field: 50, type: 'bytes' as const }, - sha1CheckSum: { field: 60, type: 'bytes' as const }, - localPath: { field: 70, type: 'string' as const }, - md5CheckSum: { field: 110, type: 'bytes' as const }, - sha3CheckSum: { field: 120, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const OidbPrivateFileUploadReqSchema = { - command: { field: 1, type: 'uint32' as const }, - seq: { field: 2, type: 'int32' as const }, - upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadReqBodySchema }, - businessId: { field: 101, type: 'int32' as const }, - clientType: { field: 102, type: 'int32' as const }, - flagSupportMediaPlatform: { field: 200, type: 'int32' as const }, -} satisfies ProtoSchema; - -export const OidbPrivateFileUploadRespBodySchema = { - retCode: { field: 10, type: 'int32' as const }, - retMsg: { field: 20, type: 'string' as const }, - uploadIp: { field: 60, type: 'string' as const }, - uploadPort: { field: 80, type: 'uint32' as const }, - uuid: { field: 90, type: 'string' as const }, - uploadKey: { field: 100, type: 'bytes' as const }, - boolFileExist: { field: 110, type: 'bool' as const }, - fileAddon: { field: 200, type: 'string' as const }, - mediaPlatformUploadKey: { field: 220, type: 'bytes' as const }, -} satisfies ProtoSchema; - -export const OidbPrivateFileUploadRespSchema = { - upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadRespBodySchema }, -} satisfies ProtoSchema; - -// --- NTV2 Rich Media (0x9067_202): Download RKey --- - -export const NTV2CommonHeadSchema = { - requestId: { field: 1, type: 'uint32' as const }, - command: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2C2CUserInfoSchema = { - accountType: { field: 1, type: 'uint32' as const }, - targetUid: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const NTV2GroupInfoSchema = { - groupUin: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2SceneInfoSchema = { - requestType: { field: 101, type: 'uint32' as const }, - businessType: { field: 102, type: 'uint32' as const }, - sceneType: { field: 200, type: 'uint32' as const }, - c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema }, - group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema }, -} satisfies ProtoSchema; - -export const NTV2ClientMetaSchema = { - agentType: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2ReqHeadSchema = { - common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema }, - scene: { field: 2, type: 'message' as const, schema: NTV2SceneInfoSchema }, - client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema }, -} satisfies ProtoSchema; - -export const NTV2DownloadRKeyReqSchema = { - types: { field: 1, type: 'repeated_uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2FileTypeSchema = { - type: { field: 1, type: 'uint32' as const }, - picFormat: { field: 2, type: 'uint32' as const }, - videoFormat: { field: 3, type: 'uint32' as const }, - voiceFormat: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2FileInfoSchema = { - fileSize: { field: 1, type: 'uint32' as const }, - fileHash: { field: 2, type: 'string' as const }, - fileSha1: { field: 3, type: 'string' as const }, - fileName: { field: 4, type: 'string' as const }, - type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema }, - width: { field: 6, type: 'uint32' as const }, - height: { field: 7, type: 'uint32' as const }, - time: { field: 8, type: 'uint32' as const }, - original: { field: 9, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2IndexNodeSchema = { - info: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema }, - fileUuid: { field: 2, type: 'string' as const }, - storeId: { field: 3, type: 'uint32' as const }, - uploadTime: { field: 4, type: 'uint32' as const }, - ttl: { field: 5, type: 'uint32' as const }, - subType: { field: 6, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2VideoDownloadExtSchema = { - busiType: { field: 1, type: 'uint32' as const }, - sceneType: { field: 2, type: 'uint32' as const }, - subBusiType: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2DownloadExtSchema = { - video: { field: 2, type: 'message' as const, schema: NTV2VideoDownloadExtSchema }, -} satisfies ProtoSchema; - -export const NTV2DownloadReqSchema = { - node: { field: 1, type: 'message' as const, schema: NTV2IndexNodeSchema }, - download: { field: 2, type: 'message' as const, schema: NTV2DownloadExtSchema }, -} satisfies ProtoSchema; - -export const NTV2RichMediaReqSchema = { - reqHead: { field: 1, type: 'message' as const, schema: NTV2ReqHeadSchema }, - download: { field: 3, type: 'message' as const, schema: NTV2DownloadReqSchema }, - downloadRkey: { field: 4, type: 'message' as const, schema: NTV2DownloadRKeyReqSchema }, -} satisfies ProtoSchema; - -export const NTV2RespHeadSchema = { - common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema }, - retCode: { field: 2, type: 'uint32' as const }, - message: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const NTV2RKeyInfoSchema = { - rkey: { field: 1, type: 'string' as const }, - rkeyTtlSec: { field: 2, type: 'uint64' as const }, - storeId: { field: 3, type: 'uint32' as const }, - rkeyCreateTime:{ field: 4, type: 'uint32' as const }, - type: { field: 5, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2DownloadRKeyRespSchema = { - rkeys: { field: 1, type: 'repeated_message' as const, schema: NTV2RKeyInfoSchema }, -} satisfies ProtoSchema; - -export const NTV2MediaDownloadInfoSchema = { - domain: { field: 1, type: 'string' as const }, - urlPath: { field: 2, type: 'string' as const }, - httpsPort: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2MediaDownloadRespSchema = { - rKeyParam: { field: 1, type: 'string' as const }, - rKeyTtlSecond: { field: 2, type: 'uint32' as const }, - info: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadInfoSchema }, - rKeyCreateTime: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const NTV2RichMediaRespSchema = { - respHead: { field: 1, type: 'message' as const, schema: NTV2RespHeadSchema }, - download: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadRespSchema }, - downloadRkey:{ field: 4, type: 'message' as const, schema: NTV2DownloadRKeyRespSchema }, -} satisfies ProtoSchema; - -// --- 0xB6E_2: Set friend remark --- - -export const OidbSetFriendRemarkSchema = { - targetUid: { field: 1, type: 'string' as const }, - remark: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- 0x9082_2: Set group reaction (remove) — same schema as set --- -// (0x9082_1 for add, 0x9082_2 for remove — both use OidbGroupReactionSchema) - -// --- Group file count (0x6D8_3) --- - -export const OidbGroupFileCountReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - appId: { field: 2, type: 'uint32' as const }, - busId: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileCountRespSchema = { - fileCount: { field: 1, type: 'uint32' as const }, - maxCount: { field: 2, type: 'uint32' as const }, - isEnd: { field: 3, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const OidbGroupFileCountViewReqSchema = { - count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountReqSchema }, -} satisfies ProtoSchema; - -export const OidbGroupFileCountViewRespSchema = { - count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountRespSchema }, -} satisfies ProtoSchema; - - -// --- trpc.msg.msg_svc.MsgService.SsoReadedReport --- - -export const GroupReadedReportItemSchema = { - groupUin: { field: 1, type: 'uint64' as const }, - lastReadSeq: { field: 2, type: 'uint64' as const }, -} satisfies ProtoSchema; - -export const C2CReadedReportItemSchema = { - uid: { field: 2, type: 'string' as const }, - lastReadTime: { field: 3, type: 'uint64' as const }, - lastReadSeq: { field: 4, type: 'uint64' as const }, -} satisfies ProtoSchema; - -export const SsoReadedReportReqSchema = { - groupList: { field: 1, type: 'repeated_message' as const, schema: GroupReadedReportItemSchema }, - c2cList: { field: 2, type: 'repeated_message' as const, schema: C2CReadedReportItemSchema }, -} satisfies ProtoSchema; - - -// --- 0x102A_1: Get Client Key --- - -export const OidbClientKeyReqSchema = { -} satisfies ProtoSchema; - -export const OidbClientKeyRespSchema = { - keyIndex: { field: 2, type: 'uint32' as const }, - clientKey: { field: 3, type: 'string' as const }, - expireTime: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - - -// --- 0x102A_0: Get PSKey --- - -export const OidbGetPskeyReqSchema = { - domainList: { field: 1, type: 'repeated_string' as const }, -} satisfies ProtoSchema; - -export const OidbPskeyItemSchema = { - domain: { field: 1, type: 'string' as const }, - pskey: { field: 2, type: 'string' as const }, - expireTime: { field: 3, type: 'uint64' as const }, -} satisfies ProtoSchema; - -export const OidbGetPskeyRespSchema = { - pskeyItems: { field: 1, type: 'repeated_message' as const, schema: OidbPskeyItemSchema }, -} satisfies ProtoSchema; - - -// customExt sub-message of SetStatus. Populated only by -// set_diy_online_status (status=10 + extStatus=2000 + this payload); -// regular set_online_status leaves field 4 unset. -// -// Wire (from napcat packet/transformer/proto/action/action.ts SetStatusCustomExt): -// 1 faceId (uint32) — face icon id, e.g. "Q我吧" sticker -// 2 text (string) — wording shown next to the icon -// 3 field3 (uint32) — face_type / template id; observed values 1..3 -export const SetStatusCustomExtSchema = { - faceId: { field: 1, type: 'uint32' as const }, - text: { field: 2, type: 'string' as const }, - faceType: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const SetStatusReqSchema = { - status: { field: 1, type: 'int32' as const }, - extStatus: { field: 2, type: 'int32' as const }, - batteryStatus: { field: 3, type: 'int32' as const }, - customExt: { field: 4, type: 'message' as const, schema: SetStatusCustomExtSchema }, -} satisfies ProtoSchema; - -export const SetStatusRespSchema = { - errCode: { field: 1, type: 'int32' as const }, // 盲猜字段 1 是错误码(虽然成功时没下发,默认 0) - errMsg: { field: 2, type: 'string' as const }, // 返回的 "set status success" -} satisfies ProtoSchema; - - -export const OidbProfileStringItemSchema = { - fieldId: { field: 1, type: 'uint32' as const }, - value: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbProfileIntItemSchema = { - fieldId: { field: 1, type: 'uint32' as const }, - value: { field: 2, type: 'uint64' as const }, -} satisfies ProtoSchema; - -export const OidbSetProfileSchema = { - uin: { field: 1, type: 'uint64' as const }, - stringProfiles: { field: 2, type: 'repeated_message' as const, schema: OidbProfileStringItemSchema }, - intProfiles: { field: 3, type: 'repeated_message' as const, schema: OidbProfileIntItemSchema }, -} satisfies ProtoSchema; - - -export const Oidb0x7edInteractionSchema = { - totalCount: { field: 1, type: 'uint32' as const }, - newCount: { field: 2, type: 'uint32' as const }, - todayCount: { field: 3, type: 'uint32' as const }, - lastTime: { field: 4, type: 'uint64' as const }, - // userInfos: { field: 7, type: 'repeated_message' ... } // 我没有这个字段,期待未来补全 -} satisfies ProtoSchema; - -export const Oidb0x7edUserLikeInfoSchema = { - uid: { field: 1, type: 'string' as const }, - time: { field: 2, type: 'uint64' as const }, - favoriteInfo: { field: 3, type: 'message' as const, schema: Oidb0x7edInteractionSchema }, - voteInfo: { field: 4, type: 'message' as const, schema: Oidb0x7edInteractionSchema }, -} satisfies ProtoSchema; - -export const Oidb0x7edReqSchema = { - targetUid: { field: 1, type: 'string' as const }, - basic: { field: 2, type: 'uint32' as const }, - vote: { field: 3, type: 'uint32' as const }, - favorite: { field: 4, type: 'uint32' as const }, - start: { field: 12, type: 'uint32' as const }, - limit: { field: 103, type: 'uint32' as const }, // 0xB8 0x06 -} satisfies ProtoSchema; - -export const Oidb0x7edRespSchema = { - userLikeInfos: { field: 1, type: 'repeated_message' as const, schema: Oidb0x7edUserLikeInfoSchema }, -} satisfies ProtoSchema; - - -export const Oidb0x8a7ReqSchema = { - basic1: { field: 1, type: 'uint32' as const }, - basic2: { field: 2, type: 'uint32' as const }, - basic3: { field: 3, type: 'uint32' as const }, - uin: { field: 4, type: 'uint64' as const }, - groupId: { field: 5, type: 'uint64' as const }, - type: { field: 12, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const Oidb0x8a7RespSchema = { - uinRemain: { field: 2, type: 'uint32' as const }, - groupRemain: { field: 3, type: 'uint32' as const }, - msg: { field: 4, type: 'string' as const }, - canAtAll: { field: 6, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const Oidb0xe17ReqSchema = { - jsonBody: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const Oidb0xe17RespSchema = { - jsonBody: { field: 4, type: 'string' as const }, -} satisfies ProtoSchema; - -export const Oidb0x112aProfileInfoSchema = { - tag: { field: 1, type: 'uint32' as const }, - value: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const Oidb0x112aReqSchema = { - uin: { field: 1, type: 'uint64' as const }, - profile: { field: 2, type: 'message' as const, schema: Oidb0x112aProfileInfoSchema }, -} satisfies ProtoSchema; - -export const Oidb0x112aRespSchema = {} satisfies ProtoSchema; - -export const Oidb0xcd4ReqBodySchema = { - uid: { field: 1, type: 'string' as const }, - chatType: { field: 2, type: 'uint32' as const }, // 默认为 0 - eventType: { field: 3, type: 'uint32' as const }, // 输入状态 1 等 -} satisfies ProtoSchema; - -export const Oidb0xcd4ReqSchema = { - reqBody: { field: 1, type: 'message' as const, schema: Oidb0xcd4ReqBodySchema }, -} satisfies ProtoSchema; - -export const Oidb0xcd4RespSchema = {} satisfies ProtoSchema; - - -export const Oidb0x990TranslateReqSchema = { - srcLang: { field: 1, type: 'string' as const }, - dstLang: { field: 2, type: 'string' as const }, - words: { field: 3, type: 'repeated_string' as const }, -} satisfies ProtoSchema; - -export const Oidb0x990ReqSchema = { - translateReq: { field: 2, type: 'message' as const, schema: Oidb0x990TranslateReqSchema }, - tag10: { field: 10, type: 'uint32' as const }, - tag12: { field: 12, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const Oidb0x990TranslateRespSchema = { - errorCode: { field: 1, type: 'uint32' as const }, - errorMsg: { field: 2, type: 'string' as const }, - srcLang: { field: 3, type: 'string' as const }, - dstLang: { field: 4, type: 'string' as const }, - srcWords: { field: 5, type: 'repeated_string' as const }, - dstWords: { field: 6, type: 'repeated_string' as const }, -} satisfies ProtoSchema; - -export const Oidb0x990RespSchema = { - translateResp: { field: 2, type: 'message' as const, schema: Oidb0x990TranslateRespSchema } -} satisfies ProtoSchema; - -export const MiniAppShareReqBodySchema = { - appid: { field: 2, type: 'string' as const }, - title: { field: 3, type: 'string' as const }, - desc: { field: 4, type: 'string' as const }, - picUrl: { field: 9, type: 'string' as const }, - jumpUrl: { field: 11, type: 'string' as const }, - iconUrl: { field: 12, type: 'string' as const }, -} satisfies ProtoSchema; - -export const MiniAppShareReqSchema = { - sdkVersion: { field: 2, type: 'string' as const }, - body: { field: 4, type: 'message' as const, schema: MiniAppShareReqBodySchema }, -} satisfies ProtoSchema; - -export const MiniAppShareRespBodySchema = { - jsonStr: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const MiniAppShareRespSchema = { - status: { field: 2, type: 'uint32' as const }, - msg: { field: 3, type: 'string' as const }, - body: { field: 4, type: 'message' as const, schema: MiniAppShareRespBodySchema }, -} satisfies ProtoSchema; - -export const Oidb0x112eReqSchema = { - botAppid: { field: 3, type: 'uint64' as const }, - msgSeq: { field: 4, type: 'uint64' as const }, - buttonId: { field: 5, type: 'string' as const }, - callbackData: { field: 6, type: 'string' as const }, - unknown7: { field: 7, type: 'uint32' as const }, - groupId: { field: 8, type: 'uint64' as const }, - unknown9: { field: 9, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const Oidb0x112eRespSchema = { - result: { field: 3, type: 'uint32' as const }, - promptText: { field: 4, type: 'string' as const }, - errMsg: { field: 5, type: 'string' as const }, -} satisfies ProtoSchema; - -export const Oidb0xeb7SignInInfoSchema = { - uin: { field: 1, type: 'string' as const }, - groupId: { field: 2, type: 'string' as const }, - version: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const Oidb0xeb7ReqSchema = { - signInInfo: { field: 2, type: 'message' as const, schema: Oidb0xeb7SignInInfoSchema }, -} satisfies ProtoSchema; - -export const Oidb0xeb7RespSchema = {} satisfies ProtoSchema; - -// --- Faceroam.OpReq: Fetch custom face --- - -export const FaceroamOpReqInnerSchema = { - field1: { field: 1, type: 'uint32' as const }, - osVersion: { field: 2, type: 'string' as const }, - qqVersion: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const FaceroamOpReqSchema = { - inner: { field: 1, type: 'message' as const, schema: FaceroamOpReqInnerSchema }, - uin: { field: 2, type: 'uint64' as const }, - field3: { field: 3, type: 'uint32' as const }, - field6: { field: 6, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const FaceroamOpRespItemSchema = { - faceIds: { field: 1, type: 'repeated_string' as const }, - category: { field: 3, type: 'string' as const }, - totalCount: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const FaceroamOpRespSchema = { - retCode: { field: 1, type: 'uint32' as const }, - message: { field: 2, type: 'string' as const }, - field3: { field: 3, type: 'uint32' as const }, - item: { field: 4, type: 'message' as const, schema: FaceroamOpRespItemSchema }, -} satisfies ProtoSchema; - -// --- 0x9083_1: Get emoji likes --- - -export const Oidb0x9083ReqSchema = { - groupId: { field: 2, type: 'uint64' as const }, - sequence: { field: 3, type: 'uint32' as const }, - emojiType: { field: 4, type: 'uint32' as const }, - emojiId: { field: 5, type: 'string' as const }, - cookie: { field: 6, type: 'bytes' as const }, - field7: { field: 7, type: 'uint32' as const }, - count: { field: 8, type: 'uint32' as const }, - field12: { field: 12, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const Oidb0x9083RespUserInfoSchema = { - uin: { field: 1, type: 'uint64' as const }, - field3: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const Oidb0x9083RespInnerSchema = { - userInfo: { field: 1, type: 'message' as const, schema: Oidb0x9083RespUserInfoSchema }, - field4: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const Oidb0x9083RespSchema = { - inner: { field: 4, type: 'message' as const, schema: Oidb0x9083RespInnerSchema }, - cookie: { field: 5, type: 'bytes' as const }, -} satisfies ProtoSchema; - -// --- 0x8a0_1: Kick group members (batch) --- - -export const Oidb0x8a0ReqSchema = { - groupId: { field: 1, type: 'uint64' as const }, - targetUids: { field: 3, type: 'repeated_string' as const }, - rejectAddRequest: { field: 4, type: 'uint32' as const }, - kickReason: { field: 5, type: 'bytes' as const }, - field12: { field: 12, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const Oidb0x8a0RespSchema = {} satisfies ProtoSchema; - -// --- 0xf16_1: Set group remark --- - -export const Oidb0xf16InnerSchema = { - groupId: { field: 1, type: 'uint64' as const }, - remark: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const Oidb0xf16ReqSchema = { - inner: { field: 1, type: 'message' as const, schema: Oidb0xf16InnerSchema }, - field12: { field: 12, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const Oidb0xf16RespSchema = {} satisfies ProtoSchema; - -// --- 0xF90_{1,2,3}: Set / complete / cancel group todo --- -// All three subCmds share the same body (groupUin + msgSeq); only the -// envelope subCmd differs. Sources: napcat -// packet/transformer/action/{Set,Complete,Cancel}GroupTodo.ts. - -export const OidbGroupTodoSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - msgSeq: { field: 2, type: 'uint64' as const }, -} satisfies ProtoSchema; - -// --- 0xFE1_2: Get stranger profile (used for online/ext status lookup) --- - -export const OidbStrangerStatusKeySchema = { - key: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbStrangerStatusReqSchema = { - uin: { field: 1, type: 'uint32' as const }, - key: { field: 3, type: 'repeated_message' as const, schema: OidbStrangerStatusKeySchema }, -} satisfies ProtoSchema; - -export const OidbStrangerStatusRespStatusSchema = { - key: { field: 1, type: 'uint32' as const }, - value: { field: 2, type: 'uint64' as const }, -} satisfies ProtoSchema; - -export const OidbStrangerStatusRespDataSchema = { - status: { field: 2, type: 'message' as const, schema: OidbStrangerStatusRespStatusSchema }, -} satisfies ProtoSchema; - -export const OidbStrangerStatusRespSchema = { - data: { field: 1, type: 'message' as const, schema: OidbStrangerStatusRespDataSchema }, -} satisfies ProtoSchema; - -// --- 0x929D_0: Fetch AI voice character list --- - -export const OidbAiVoiceListReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - chatType: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbAiVoiceListEntrySchema = { - voiceId: { field: 1, type: 'string' as const }, - voiceDisplayName: { field: 2, type: 'string' as const }, - voiceExampleUrl: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbAiVoiceListCategorySchema = { - category: { field: 1, type: 'string' as const }, - voices: { field: 2, type: 'repeated_message' as const, schema: OidbAiVoiceListEntrySchema }, -} satisfies ProtoSchema; - -export const OidbAiVoiceListRespSchema = { - content: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceListCategorySchema }, -} satisfies ProtoSchema; - -// --- 0x929B_0: Trigger AI voice synthesis (returns server-side IndexNode) --- - -export const OidbAiVoiceSessionSchema = { - sessionId: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbAiVoiceReqSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - voiceId: { field: 2, type: 'string' as const }, - text: { field: 3, type: 'string' as const }, - chatType: { field: 4, type: 'uint32' as const }, - session: { field: 5, type: 'message' as const, schema: OidbAiVoiceSessionSchema }, -} satisfies ProtoSchema; - -// We only need the fields the OneBot adapter consumes back: the -// IndexNode payload (which feeds fetchGroupPttUrlByNode) and the -// statusCode that the server uses to signal "still rendering, retry". - -export const OidbAiVoiceFileTypeSchema = { - type: { field: 1, type: 'uint32' as const }, - picFormat: { field: 2, type: 'uint32' as const }, - videoFormat: { field: 3, type: 'uint32' as const }, - voiceFormat: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbAiVoiceFileInfoSchema = { - fileSize: { field: 1, type: 'uint32' as const }, - fileHash: { field: 2, type: 'string' as const }, - fileSha1: { field: 3, type: 'string' as const }, - fileName: { field: 4, type: 'string' as const }, - type: { field: 5, type: 'message' as const, schema: OidbAiVoiceFileTypeSchema }, - width: { field: 6, type: 'uint32' as const }, - height: { field: 7, type: 'uint32' as const }, - time: { field: 8, type: 'uint32' as const }, - original: { field: 9, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbAiVoiceIndexNodeSchema = { - info: { field: 1, type: 'message' as const, schema: OidbAiVoiceFileInfoSchema }, - fileUuid: { field: 2, type: 'string' as const }, - storeId: { field: 3, type: 'uint32' as const }, - uploadTime: { field: 4, type: 'uint32' as const }, - ttl: { field: 5, type: 'uint32' as const }, - subType: { field: 6, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbAiVoiceMsgInfoBodySchema = { - index: { field: 1, type: 'message' as const, schema: OidbAiVoiceIndexNodeSchema }, -} satisfies ProtoSchema; - -export const OidbAiVoiceMsgInfoSchema = { - msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceMsgInfoBodySchema }, -} satisfies ProtoSchema; - -export const OidbAiVoiceRespSchema = { - statusCode: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'uint32' as const }, - msgInfo: { field: 4, type: 'message' as const, schema: OidbAiVoiceMsgInfoSchema }, -} satisfies ProtoSchema; - -// --- Highway cmdId 3000: GroupAvatarExtra --- -// Ported from Lagrange.Core/Internal/Packets/Service/Highway/GroupAvatarExtra.cs. -// Field values are protocol-prescribed constants (Lagrange comments on each). - -export const GroupAvatarExtraField3Schema = { - field1: { field: 1, type: 'uint32' as const }, // observed value: 1 -} satisfies ProtoSchema; - -export const GroupAvatarExtraSchema = { - type: { field: 1, type: 'uint32' as const }, // observed value: 101 - groupUin: { field: 2, type: 'uint32' as const }, - field3: { field: 3, type: 'message' as const, schema: GroupAvatarExtraField3Schema }, - field5: { field: 5, type: 'uint32' as const }, // observed value: 3 - field6: { field: 6, type: 'uint32' as const }, // observed value: 1 -} satisfies ProtoSchema; - -///////// --- group album -// --- Request Schemas --- - -export const ExtMapEntrySchema = { - key: { field: 1, type: 'string' as const }, - value: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const ReqInfoSchema = { - groupId: { field: 1, type: 'string' as const }, - albumId: { field: 2, type: 'string' as const }, - field3: { field: 3, type: 'int32' as const }, - attachInfo: { field: 4, type: 'string' as const }, - field5: { field: 5, type: 'string' as const }, -} satisfies ProtoSchema; - -export const GetMediaListRequestSchema = { - field1: { field: 1, type: 'int32' as const }, - field2: { field: 2, type: 'bytes' as const }, - field3: { field: 3, type: 'bytes' as const }, - reqInfo: { field: 4, type: 'message' as const, schema: ReqInfoSchema }, - traceId: { field: 5, type: 'string' as const }, - extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema }, -} satisfies ProtoSchema; - -// --- Response Schemas --- - -export const UrlInfoSchema = { - url: { field: 1, type: 'string' as const }, - width: { field: 2, type: 'uint32' as const }, - height: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const PhotoUrlSchema = { - spec: { field: 1, type: 'uint32' as const }, - url: { field: 2, type: 'message' as const, schema: UrlInfoSchema } -} satisfies ProtoSchema; - -export const ImageInfoSchema = { - name: { field: 1, type: 'string' as const }, - sloc: { field: 2, type: 'string' as const }, - lloc: { field: 3, type: 'string' as const }, - photoUrls: { field: 4, type: 'repeated_message' as const, schema: PhotoUrlSchema }, - defaultUrl: { field: 5, type: 'message' as const, schema: UrlInfoSchema }, - isGif: { field: 6, type: 'bool' as const }, - hasRaw: { field: 7, type: 'bool' as const }, -} satisfies ProtoSchema; - -export const MediaInfoSchema = { - type: { field: 1, type: 'uint32' as const }, - image: { field: 2, type: 'message' as const, schema: ImageInfoSchema }, - uploader: { field: 6, type: 'string' as const }, - batchId: { field: 7, type: 'uint64' as const }, - uploadTime: { field: 8, type: 'uint64' as const }, -} satisfies ProtoSchema; - -export const GetMediaListRspDataSchema = { - albumInfo: { - field: 1, - type: 'message' as const, - schema: { - albumId: { field: 1, type: 'string' as const }, - owner: { field: 2, type: 'string' as const }, - name: { field: 3, type: 'string' as const }, - } satisfies ProtoSchema - }, - mediaList: { field: 3, type: 'repeated_message' as const, schema: MediaInfoSchema }, - prevAttachInfo: { field: 4, type: 'string' as const }, - nextAttachInfo: { field: 5, type: 'string' as const }, // 用于翻页拉取的 token -} satisfies ProtoSchema; - -export const GetMediaListResponseSchema = { - field1: { field: 1, type: 'int32' as const }, - field2: { field: 2, type: 'bytes' as const }, - field3: { field: 3, type: 'bytes' as const }, - data: { field: 4, type: 'message' as const, schema: GetMediaListRspDataSchema }, // 将原本的 bytes 修正为 message 解析 -} satisfies ProtoSchema; - - -// --- DoQunComment: Comment on group album media --- - -// --- DoQunComment: 严格对齐底层字节的字段定义 --- - -export const CommentContentItemSchema = { - type: { field: 1, type: 'uint32' as const }, - content: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const CommentUserSchema = { - uin: { field: 13, type: 'string' as const }, -} satisfies ProtoSchema; - -// 评论具体内容结构 (原 CommentReqContentSchema) -export const CommentReqContentSchema = { - field2: { field: 2, type: 'message' as const, schema: CommentUserSchema }, - field3: { field: 3, type: 'message' as const, schema: { - field1: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'string' as const }, - field3: { field: 3, type: 'string' as const }, - field4: { field: 4, type: 'string' as const }, - field5: { field: 5, type: 'uint32' as const }, - field6: { field: 6, type: 'string' as const }, - } satisfies ProtoSchema }, - clientKey: { field: 7, type: 'string' as const }, // 对应你的 clientKey -} satisfies ProtoSchema; - -export const CommentReqPhotoInfoSchema = { - field1: { field: 1, type: 'message' as const, schema: { - field2: { field: 2, type: 'message' as const, schema: { - field1: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'string' as const }, - lloc: { field: 3, type: 'string' as const }, - field4: { field: 4, type: 'string' as const }, - field6: { field: 6, type: 'string' as const }, - field7: { field: 7, type: 'uint32' as const }, - field8: { field: 8, type: 'uint32' as const }, - field9: { field: 9, type: 'uint32' as const }, - field14: { field: 14, type: 'uint32' as const }, - field15: { field: 15, type: 'uint32' as const }, - field17: { field: 17, type: 'uint32' as const }, - } satisfies ProtoSchema }, - } satisfies ProtoSchema }, - albumId: { field: 3, type: 'string' as const }, - field5: { field: 5, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const CommentReqBodySchema = { - field1: { field: 1, type: 'message' as const, schema: { - field3: { field: 3, type: 'uint32' as const }, - field4: { field: 4, type: 'string' as const }, - } satisfies ProtoSchema }, - field2: { field: 2, type: 'message' as const, schema: { - field1: { field: 1, type: 'message' as const, schema: CommentUserSchema } - } satisfies ProtoSchema }, - field5: { field: 5, type: 'message' as const, schema: CommentReqPhotoInfoSchema }, // 注意:抓包证实照片在 field 5 -} satisfies ProtoSchema; - -export const DoQunCommentRequestSchema = { - field1: { field: 1, type: 'int32' as const }, - field2: { field: 2, type: 'bytes' as const }, - field3: { field: 3, type: 'bytes' as const }, - body: { field: 4, type: 'message' as const, schema: { - groupId: { field: 2, type: 'string' as const }, - field3: { field: 3, type: 'uint32' as const }, - reqBody: { field: 4, type: 'message' as const, schema: CommentReqBodySchema }, - field5: { field: 5, type: 'message' as const, schema: CommentReqContentSchema }, // 注意:评论文本实际在外层的 field 5 - } satisfies ProtoSchema }, - traceId: { field: 5, type: 'string' as const }, - extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema }, -} satisfies ProtoSchema; - -export const CommentRespUserSchema = { - uin: { field: 13, type: 'string' as const }, -} satisfies ProtoSchema; - -export const CommentRespContentSchema = { - type: { field: 1, type: 'uint32' as const }, - content: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const CommentRespDataSchema = { - id: { field: 1, type: 'string' as const }, - user: { field: 2, type: 'message' as const, schema: CommentRespUserSchema }, - content: { field: 3, type: 'repeated_message' as const, schema: CommentRespContentSchema }, - time: { field: 4, type: 'uint64' as const }, - clientKey: { field: 7, type: 'string' as const }, -} satisfies ProtoSchema; - -export const DoQunCommentResponseSchema = { - field1: { field: 1, type: 'int32' as const }, - comment: { field: 4, type: 'message' as const, schema: { - data: { field: 2, type: 'message' as const, schema: CommentRespDataSchema }, - } satisfies ProtoSchema }, -} satisfies ProtoSchema; - -// --- DoQunLike: Like group album media --- - -export const DoQunLikeReqLikeInfoSchema = { - id: { field: 1, type: 'string' as const }, - status: { field: 3, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const DoQunLikeReqCellCommonSchema = { - time: { field: 3, type: 'uint64' as const }, - feedId: { field: 4, type: 'string' as const }, -} satisfies ProtoSchema; - -export const DoQunLikeReqCellUserSchema = { - uin: { field: 13, type: 'string' as const }, // 修复:抓包证实 uin 是 field 13 -} satisfies ProtoSchema; - -export const DoQunLikeReqCellUserInfoSchema = { - user: { field: 1, type: 'message' as const, schema: DoQunLikeReqCellUserSchema }, -} satisfies ProtoSchema; - -export const DoQunLikeReqCellQunInfoSchema = { - qunId: { field: 1, type: 'string' as const }, -} satisfies ProtoSchema; - -export const DoQunLikeReqCellMediaSchema = { - albumId: { field: 3, type: 'string' as const }, - batchId: { field: 5, type: 'uint64' as const }, -} satisfies ProtoSchema; - -export const DoQunLikeReqFeedPublishSchema = { - cellCommon: { field: 1, type: 'message' as const, schema: DoQunLikeReqCellCommonSchema }, - cellUserInfo: { field: 2, type: 'message' as const, schema: DoQunLikeReqCellUserInfoSchema }, - cellMedia: { field: 5, type: 'message' as const, schema: DoQunLikeReqCellMediaSchema }, - cellQunInfo: { field: 12, type: 'message' as const, schema: DoQunLikeReqCellQunInfoSchema }, -} satisfies ProtoSchema; - -export const DoQunLikeReqBodySchema = { - type: { field: 2, type: 'uint32' as const }, - like: { field: 3, type: 'message' as const, schema: DoQunLikeReqLikeInfoSchema }, - publish: { field: 4, type: 'message' as const, schema: DoQunLikeReqFeedPublishSchema }, - clientKey: { field: 5, type: 'string' as const }, -} satisfies ProtoSchema; - -export const DoQunLikeRequestSchema = { - field1: { field: 1, type: 'int32' as const }, - field2: { field: 2, type: 'string' as const }, - field3: { field: 3, type: 'string' as const }, - body: { field: 4, type: 'message' as const, schema: DoQunLikeReqBodySchema }, - extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema }, -} satisfies ProtoSchema; - -export const DoQunLikeRespBodySchema = { - like: { field: 2, type: 'message' as const, schema: DoQunLikeReqLikeInfoSchema }, -} satisfies ProtoSchema; - -export const DoQunLikeResponseSchema = { - field1: { field: 1, type: 'int32' as const }, - body: { field: 4, type: 'message' as const, schema: DoQunLikeRespBodySchema }, -} satisfies ProtoSchema; - -// --- DeleteMedias: Delete group album media --- - -export const DeleteMediasReqBodySchema = { - groupId: { field: 1, type: 'string' as const }, - albumId: { field: 2, type: 'string' as const }, - lloc: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const DeleteMediasRequestSchema = { - field1: { field: 1, type: 'int32' as const }, - field2: { field: 2, type: 'string' as const }, - field3: { field: 3, type: 'string' as const }, - body: { field: 4, type: 'message' as const, schema: DeleteMediasReqBodySchema }, - traceId: { field: 5, type: 'string' as const }, // <-- 把它挪到外层了! - extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema }, -} satisfies ProtoSchema; - -export const DeleteMediasResponseSchema = { - field1: { field: 1, type: 'int32' as const }, // 8694 - field2: { field: 2, type: 'int32' as const }, // 错误码 (例如: 10023) - field3: { field: 3, type: 'string' as const }, // 错误信息 (例如: "no right delete...") -} satisfies ProtoSchema; - diff --git a/packages/core/src/bridge/proto/oidb.ts b/packages/core/src/bridge/proto/oidb.ts deleted file mode 100644 index 65fa1000..00000000 --- a/packages/core/src/bridge/proto/oidb.ts +++ /dev/null @@ -1,161 +0,0 @@ -// Proto schemas for OidbSvc service types. -// Port of src/bridge/include/bridge/proto/oidb.h - -import type { ProtoSchema } from '../../protobuf/decode'; - -// --- OidbSvcTrpcTcpBase wrapper --- - -export const OidbPropertySchema = { - key: { field: 1, type: 'string' as const }, - value: { field: 2, type: 'bytes' as const }, -} satisfies ProtoSchema; - -// Factory for OidbSvcTrpcTcpBase -export function makeOidbBaseSchema(bodySchema: ProtoSchema): ProtoSchema { - return { - command: { field: 1, type: 'uint32' as const }, - subCommand: { field: 2, type: 'uint32' as const }, - errorCode: { field: 3, type: 'uint32' as const }, - body: { field: 4, type: 'message' as const, schema: bodySchema }, - errorMsg: { field: 5, type: 'string' as const }, - properties: { field: 11, type: 'repeated_message' as const, schema: OidbPropertySchema }, - reserved: { field: 12, type: 'int32' as const }, - }; -} - -// --- Friend list (0xFD4_1) --- - -export const OidbFriendPropertySchema = { - code: { field: 1, type: 'uint32' as const }, - value: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbFriendLayer1Schema = { - properties: { field: 2, type: 'repeated_message' as const, schema: OidbFriendPropertySchema }, -} satisfies ProtoSchema; - -export const OidbFriendAdditionalSchema = { - type: { field: 1, type: 'uint32' as const }, - layer1: { field: 2, type: 'message' as const, schema: OidbFriendLayer1Schema }, -} satisfies ProtoSchema; - -export const OidbFriendSchema = { - uid: { field: 1, type: 'string' as const }, - customGroup:{ field: 2, type: 'uint32' as const }, - uin: { field: 3, type: 'uint32' as const }, - additional: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendAdditionalSchema }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFD4_1ResponseUinSchema = { - uin: { field: 1, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFD4_1ResponseSchema = { - next: { field: 2, type: 'message' as const, schema: OidbSvcTrpcTcp0xFD4_1ResponseUinSchema }, - displayFriendCount: { field: 3, type: 'uint32' as const }, - timestamp: { field: 6, type: 'uint32' as const }, - selfUin: { field: 7, type: 'uint32' as const }, - friends: { field: 101, type: 'repeated_message' as const, schema: OidbFriendSchema }, - groups: { field: 102, type: 'repeated_message' as const, schema: OidbFriendPropertySchema }, -} satisfies ProtoSchema; - -// --- Group list (0xFE5_2) --- - -export const OidbSvcTrpcTcp0xFE5_2MemberSchema = { - uid: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFE5_2GroupInfoSchema = { - groupOwner: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2MemberSchema }, - createdTime: { field: 2, type: 'uint32' as const }, - memberMax: { field: 3, type: 'uint32' as const }, - memberCount: { field: 4, type: 'uint32' as const }, - groupName: { field: 5, type: 'string' as const }, - description: { field: 18, type: 'string' as const }, - question: { field: 19, type: 'string' as const }, - announcement: { field: 30, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFE5_2CustomInfoSchema = { - remark: { field: 3, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFE5_2GroupSchema = { - groupUin: { field: 3, type: 'uint32' as const }, - info: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupInfoSchema }, - customInfo: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2CustomInfoSchema }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFE5_2ResponseSchema = { - groups: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupSchema }, -} satisfies ProtoSchema; - -// --- Group member list (0xFE7_3) --- - -export const OidbSvcTrpcTcp0xFE7_3UinSchema = { - uid: { field: 2, type: 'string' as const }, - uin: { field: 4, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFE7_3CardSchema = { - memberCard: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFE7_3LevelSchema = { - infos: { field: 1, type: 'repeated_uint32' as const }, - level: { field: 2, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFE7_3MemberSchema = { - uin: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3UinSchema }, - memberName: { field: 10, type: 'string' as const }, - specialTitle: { field: 17, type: 'string' as const }, - memberCard: { field: 11, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3CardSchema }, - level: { field: 12, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3LevelSchema }, - joinTimestamp: { field: 100, type: 'uint32' as const }, - lastMsgTimestamp: { field: 101, type: 'uint32' as const }, - shutUpTimestamp: { field: 102, type: 'uint32' as const }, - permission: { field: 107, type: 'uint32' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0xFE7_3ResponseSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - members: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE7_3MemberSchema }, - field3: { field: 3, type: 'uint32' as const }, - memberChangeSeq: { field: 5, type: 'uint32' as const }, - memberCardChangeSeq:{ field: 6, type: 'uint32' as const }, - token: { field: 15, type: 'string' as const }, -} satisfies ProtoSchema; - -// --- Group request (0x10C0) --- - -export const OidbSvcTrpcTcp0x10C0ResponseUserSchema = { - uid: { field: 1, type: 'string' as const }, - name: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0x10C0ResponseGroupSchema = { - groupUin: { field: 1, type: 'uint32' as const }, - groupName: { field: 2, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0x10C0ResponseRequestSchema = { - sequence: { field: 1, type: 'uint64' as const }, - eventType: { field: 2, type: 'uint32' as const }, - state: { field: 3, type: 'uint32' as const }, - group: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseGroupSchema }, - target: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema }, - invitor: { field: 6, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema }, - operatorUser: { field: 7, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema }, - field9: { field: 9, type: 'string' as const }, - comment: { field: 10, type: 'string' as const }, -} satisfies ProtoSchema; - -export const OidbSvcTrpcTcp0x10C0ResponseSchema = { - requests: { field: 1, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseRequestSchema }, - field2: { field: 2, type: 'uint64' as const }, - newLatestSeq: { field: 3, type: 'uint64' as const }, - field4: { field: 4, type: 'uint32' as const }, - field5: { field: 5, type: 'uint64' as const }, - field6: { field: 6, type: 'uint32' as const }, -} satisfies ProtoSchema; diff --git a/packages/core/src/bridge/proto/proton/action.ts b/packages/core/src/bridge/proto/proton/action.ts deleted file mode 100644 index 0a44d8b8..00000000 --- a/packages/core/src/bridge/proto/proton/action.ts +++ /dev/null @@ -1,113 +0,0 @@ -// Proton (compile-time) form of bridge/proto/action.ts. -// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. - -import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton'; -import type { Elem } from './element'; - -// ── Routing ───────────────────────────────────────────────────────── - -export interface RoutingC2C { - uin?: pb<1, uint_32>; - uid?: pb<2, string>; -} - -export interface RoutingGroup { - groupCode?: pb<1, uint_64>; -} - -// `Trans0x211` is the c2c-file scene's routing header. The server -// rejects c2c file messages routed through `RoutingC2C` — instead it -// expects `trans0x211 { ccCmd: 4, uid: }`. Confirmed against -// `dev/Lagrange.Core/Lagrange.Core/Internal/Packets/Message/ -// Routing/Trans0X211.cs` + `RoutingHead.cs` (Trans0X211 sits at -// field 15) + `MessagePacker.BuildPacketBase` (`Trans0X211 = -// !chain.HasTypeOf() ? null : new Trans0X211 { CcCmd = 4, -// Uid = chain.Uid }`). -export interface RoutingTrans0x211 { - toUin?: pb<1, uint_64>; - ccCmd?: pb<2, uint_32>; - uid?: pb<8, string>; -} - -export interface RoutingHead { - c2c?: pb<1, RoutingC2C>; - grp?: pb<2, RoutingGroup>; - trans0x211?: pb<15, RoutingTrans0x211>; -} - -// ── Content Head (for send) ───────────────────────────────────────── - -export interface SendContentHead { - type?: pb<1, uint_32>; - subType?: pb<2, uint_32>; - c2cCmd?: pb<3, uint_32>; -} - -// ── Message Control ───────────────────────────────────────────────── - -export interface MessageControl { - msgFlag?: pb<1, int_32>; -} - -// ── RichText (for send — only elems) ──────────────────────────────── - -export interface SendRichText { - elems?: pb_repeated<2, Elem>; -} - -// ── MessageBody (for send) ────────────────────────────────────────── - -export interface SendMessageBody { - richText?: pb<1, SendRichText>; - // C2C file payload — serialised `FileExtra { file: NotOnlineFile }` - // bytes. The server reads c2c file metadata from this slot, NOT - // from `richText.notOnlineFile`. Confirmed against `dev/Lagrange.Core/ - // .../MessageBody.cs:12` (commented "Offline file is now put here"). - msgContent?: pb<2, bytes>; -} - -// ── SendMessageRequest ────────────────────────────────────────────── - -export interface SendMessageRequest { - routingHead?: pb<1, RoutingHead>; - contentHead?: pb<2, SendContentHead>; - messageBody?: pb<3, SendMessageBody>; - clientSequence?: pb<4, uint_32>; - random?: pb<5, uint_32>; - syncCookie?: pb<6, bytes>; - via?: pb<8, uint_32>; - dataStatist?: pb<9, uint_32>; - ctrl?: pb<12, MessageControl>; - multiSendSeq?: pb<14, uint_32>; -} - -// ── SendMessageResponse ───────────────────────────────────────────── - -export interface SendMessageResponse { - result?: pb<1, int_32>; - errMsg?: pb<2, string>; - timestamp1?: pb<3, uint_32>; - field10?: pb<10, uint_32>; - groupSequence?: pb<11, uint_32>; - timestamp2?: pb<12, uint_32>; - privateSequence?: pb<14, uint_32>; -} - -// ── MentionExtra (for building @mention text element) ─────────────── -// -// Same wire shape as element.ts's MentionExtra (which is used for decoding -// inbound mentions) — kept under a distinct name to mark the send-side -// usage, matching the legacy convention. - -export interface MentionExtraSend { - type?: pb<3, int_32>; - uin?: pb<4, uint_32>; - field5?: pb<5, int_32>; - uid?: pb<9, string>; -} - -// ── MarkdownData ──────────────────────────────────────────────────── - -export interface MarkdownData { - content?: pb<1, string>; -} diff --git a/packages/core/src/bridge/proto/proton/message.ts b/packages/core/src/bridge/proto/proton/message.ts deleted file mode 100644 index 8f31ab6b..00000000 --- a/packages/core/src/bridge/proto/proton/message.ts +++ /dev/null @@ -1,126 +0,0 @@ -// Proton (compile-time) form of bridge/proto/message.ts. -// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. - -import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton'; -import type { Elem } from './element'; - -// ── ResponseHead.Grp ──────────────────────────────────────────────── - -export interface ResponseGrp { - groupUin?: pb<1, uint_32>; - memberName?: pb<2, string>; - groupName?: pb<4, string>; -} - -export interface ResponseForward { - friendName?: pb<6, string>; -} - -// ── ResponseHead ──────────────────────────────────────────────────── - -export interface ResponseHead { - fromUin?: pb<1, uint_32>; - fromUid?: pb<2, string>; - type?: pb<3, uint_32>; - sigMap?: pb<4, uint_32>; - toUin?: pb<5, uint_32>; - toUid?: pb<6, string>; - forward?: pb<7, ResponseForward>; - grp?: pb<8, ResponseGrp>; -} - -// ── ContentHead ───────────────────────────────────────────────────── - -export interface ContentHead { - msgType?: pb<1, uint_32>; - subType?: pb<2, uint_32>; - divSeq?: pb<3, uint_32>; - msgId?: pb<4, uint_32>; - sequence?: pb<5, uint_32>; - timestamp?: pb<6, uint_32>; - field7?: pb<7, uint_64>; - newId?: pb<12, uint_64>; -} - -// ── Ptt (voice) ───────────────────────────────────────────────────── - -export interface Ptt { - fileType?: pb<1, uint_32>; - fileId?: pb<2, uint_64>; - fileUuid?: pb<3, bytes>; - fileMd5?: pb<4, bytes>; - fileName?: pb<5, string>; - fileSize?: pb<6, uint_32>; - groupFileKey?: pb<10, string>; - fileKey?: pb<14, bytes>; - time?: pb<19, uint_32>; - format?: pb<29, uint_32>; -} - -// ── NotOnlineFile (C2C file) ──────────────────────────────────────── -// -// Field numbers cross-checked against `dev/Lagrange.Core/.../Component/ -// NotOnlineFile.cs`. This same shape is what gets serialised inside -// `FileExtra` (below) and ridden as `MessageBody.msgContent` for c2c -// file sends — fields 9/50/55 are required on send (subcmd=1, -// dangerEvel=0, expireTime=now+7d), the receiver only reads the -// identification slots. - -export interface NotOnlineFile { - fileType?: pb<1, uint_32>; - fileUuid?: pb<3, string>; - fileMd5?: pb<4, bytes>; - fileName?: pb<5, string>; - fileSize?: pb<6, uint_64>; - subcmd?: pb<9, uint_32>; - dangerEvel?: pb<50, uint_32>; - expireTime?: pb<55, uint_32>; - fileHash?: pb<57, string>; -} - -// ── RichText ──────────────────────────────────────────────────────── - -export interface RichText { - elems?: pb_repeated<2, Elem>; - notOnlineFile?: pb<3, NotOnlineFile>; - ptt?: pb<4, Ptt>; -} - -// ── MessageBody ───────────────────────────────────────────────────── - -export interface MessageBody { - richText?: pb<1, RichText>; - msgContent?: pb<2, bytes>; -} - -// ── FileExtra (for C2C file in msg_content) ───────────────────────── -// -// `FileExtra { file: NotOnlineFile }` is the wrapper the server expects -// at `MessageBody.msgContent` (per `dev/Lagrange.Core/.../FileExtra.cs`). -// Old code had a parallel `FileExtraInfo` with fileSize=1, fileName=2, -// fileMd5=3, fileUuid=4, fileHash=5 — that schema didn't match the -// wire shape at all (every field was at the wrong tag), which is why -// c2c file messages we received via msgContent silently failed to -// parse, and c2c file messages we sent through `richText.notOnlineFile` -// (also wrong — see SendMessageBody) shipped a payload the recipient -// couldn't render. Consolidating to a single shared `NotOnlineFile` -// (identification fields 1/3/4/5/6/57) fixes both directions. - -export interface FileExtra { - file?: pb<1, NotOnlineFile>; -} - -// ── PushMsgBody ───────────────────────────────────────────────────── - -export interface PushMsgBody { - responseHead?: pb<1, ResponseHead>; - contentHead?: pb<2, ContentHead>; - body?: pb<3, MessageBody>; -} - -// ── PushMsg (top-level) ───────────────────────────────────────────── - -export interface PushMsg { - message?: pb<1, PushMsgBody>; - status?: pb<3, int_32>; -} diff --git a/packages/core/src/bridge/proto/proton/oidb-action.ts b/packages/core/src/bridge/proto/proton/oidb-action.ts deleted file mode 100644 index 40e2bc4a..00000000 --- a/packages/core/src/bridge/proto/proton/oidb-action.ts +++ /dev/null @@ -1,1637 +0,0 @@ -// Proton (compile-time) form of bridge/proto/oidb-action.ts. -// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. - -import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; - -// --- 0x1253_1: Mute group member --- - -export interface OidbMuteMemberBody { - targetUid?: pb<1, string>; - duration?: pb<2, uint_32>; -} - -export interface OidbMuteMember { - groupUin?: pb<1, uint_32>; - type?: pb<2, uint_32>; - body?: pb<3, OidbMuteMemberBody>; -} - -// --- 0x89A_0: Mute group all --- - -export interface OidbMuteAllState { - state?: pb<17, uint_32>; -} - -export interface OidbMuteAll { - groupUin?: pb<1, uint_32>; - muteState?: pb<2, OidbMuteAllState>; -} - -// --- 0x89A_0: Set group add option --- - -export interface Oidb0x89a_0AddOptionSettings { - addType?: pb<16, uint_32>; -} - -export interface Oidb0x89a_0AddOption { - groupUin?: pb<1, uint_64>; - settings?: pb<2, Oidb0x89a_0AddOptionSettings>; - field12?: pb<12, uint_32>; -} - -// --- 0x89A_0: Set group search --- - -export interface Oidb0x89a_0Search { - groupUin?: pb<1, uint_64>; - settings?: pb<2, bytes>; - field12?: pb<12, uint_32>; -} - -// --- 0x8A0_1: Kick group member --- - -export interface OidbKickMember { - groupUin?: pb<1, uint_32>; - targetUid?: pb<3, string>; - rejectAddRequest?: pb<4, bool>; - reason?: pb<5, string>; -} - -// --- 0x1097_1: Leave group --- - -export interface OidbLeaveGroup { - groupUin?: pb<1, uint_32>; -} - -// --- 0xB5D_44: Friend add request --- - -export interface OidbFriendRequestAction { - accept?: pb<1, uint_32>; - targetUid?: pb<2, string>; -} - -// --- 0x126B_0: Delete friend --- - -export interface OidbDeleteFriendField2Field3 { - field1?: pb<1, uint_32>; - field2?: pb<2, uint_32>; - field3?: pb<3, uint_32>; -} - -export interface OidbDeleteFriendField2 { - field1?: pb<1, uint_32>; - field2?: pb<2, uint_32>; - field3?: pb<3, OidbDeleteFriendField2Field3>; -} - -export interface OidbDeleteFriendField1 { - targetUid?: pb<1, string>; - field2?: pb<2, OidbDeleteFriendField2>; - block?: pb<3, bool>; - field4?: pb<4, bool>; -} - -export interface OidbDeleteFriend { - field1?: pb<1, OidbDeleteFriendField1>; -} - -// --- 0x10C8: Group request action --- - -export interface OidbGroupRequestBody { - sequence?: pb<1, uint_64>; - eventType?: pb<2, uint_32>; - groupUin?: pb<3, uint_32>; - message?: pb<4, string>; -} - -export interface OidbGroupRequestAction { - accept?: pb<1, uint_32>; - body?: pb<2, OidbGroupRequestBody>; -} - -// --- 0xED3_1: Poke --- - -export interface OidbPoke { - uin?: pb<1, uint_32>; - groupUin?: pb<2, uint_32>; - friendUin?: pb<5, uint_32>; - ext?: pb<6, uint_32>; -} - -// --- 0xEAC: Group essence --- - -export interface OidbEssence { - groupUin?: pb<1, uint_32>; - sequence?: pb<2, uint_32>; - random?: pb<3, uint_32>; -} - -// --- 0x1096_1: Set group admin --- - -export interface OidbSetAdmin { - groupUin?: pb<1, uint_32>; - uid?: pb<2, string>; - isAdmin?: pb<3, bool>; -} - -// --- 0x8FC_3: Set group card (rename member) --- - -export interface OidbRenameMemberBody { - targetUid?: pb<1, string>; - targetName?: pb<2, string>; -} - -export interface OidbRenameMember { - groupUin?: pb<1, uint_32>; - body?: pb<2, OidbRenameMemberBody>; -} - -// --- 0x89A_15: Rename group --- - -export interface OidbRenameGroupBody { - targetName?: pb<1, string>; -} - -export interface OidbRenameGroup { - groupUin?: pb<1, uint_32>; - body?: pb<2, OidbRenameGroupBody>; -} - -// --- 0x8FC_2: Set group special title --- - -export interface OidbSpecialTitleBody { - targetUid?: pb<1, string>; - specialTitle?: pb<5, string>; - expireTime?: pb<6, int_32>; -} - -export interface OidbSpecialTitle { - groupUin?: pb<1, uint_32>; - body?: pb<2, OidbSpecialTitleBody>; -} - -// --- 0x7E5_104: Send like --- - -export interface OidbLike { - targetUin?: pb<1, uint_32>; - count?: pb<2, uint_32>; -} - -// --- 0x10C0_1 / 0x10C0_2: Group request list --- - -export interface OidbGroupRequestList { - count?: pb<1, uint_32>; - field2?: pb<2, uint_32>; -} - -// --- 0xFE1_2: User profile info --- - -export interface OidbUserInfoKey { - key?: pb<1, uint_32>; -} - -// Field 2 USED to be `field2: uint32 = 0`, but newer QQ NT versions -// reinterpret field 2 as `uid: string` / `openid: string` and reject -// the request with "one of uid/openid is invaild" when a varint 0 -// shows up there. NapCat's schema (Oidb.0XFE1_2.ts) only emits `uin` -// and `key[]`, so we match that exactly. -export interface OidbUserInfoRequest { - uin?: pb<1, uint_32>; - keys?: pb_repeated<3, OidbUserInfoKey>; -} - -export interface OidbTwoNumber { - number1?: pb<1, uint_32>; - number2?: pb<2, uint_32>; -} - -export interface OidbByteProperty { - code?: pb<1, uint_32>; - value?: pb<2, bytes>; -} - -export interface OidbUserInfoProperty { - numberProperties?: pb_repeated<1, OidbTwoNumber>; - bytesProperties?: pb_repeated<2, OidbByteProperty>; -} - -export interface OidbUserInfoResponseBody { - uid?: pb<1, string>; - properties?: pb<2, OidbUserInfoProperty>; - uin?: pb<3, uint_32>; -} - -export interface OidbUserInfoResponse { - body?: pb<1, OidbUserInfoResponseBody>; -} - -export interface AvatarInfo { - url?: pb<5, string>; -} - -// --- FD4_1: Friend list request body fields --- - -export interface OidbFriendListNumber { - numbers?: pb_repeated<1, uint_32>; -} - -export interface OidbFriendListBodyItem { - type?: pb<1, uint_32>; - number?: pb<2, OidbFriendListNumber>; -} - -export interface OidbFriendListNextUin { - uin?: pb<1, uint_32>; -} - -export interface OidbFriendListRequest { - friendCount?: pb<2, uint_32>; - field4?: pb<4, uint_32>; - nextUin?: pb<5, OidbFriendListNextUin>; - field6?: pb<6, uint_32>; - field7?: pb<7, uint_32>; - body?: pb_repeated<10001, OidbFriendListBodyItem>; - field10002?: pb_repeated<10002, uint_32>; - field10003?: pb<10003, uint_32>; -} - -// --- FE5_2: Group list request body (config fields) --- - -export interface OidbGroupListConfig1 { - groupOwner?: pb<1, bool>; - field2?: pb<2, bool>; - memberMax?: pb<3, bool>; - memberCount?: pb<4, bool>; - groupName?: pb<5, bool>; - field8?: pb<8, bool>; - field9?: pb<9, bool>; - field10?: pb<10, bool>; - field11?: pb<11, bool>; - field12?: pb<12, bool>; - field13?: pb<13, bool>; - field14?: pb<14, bool>; - field15?: pb<15, bool>; - field16?: pb<16, bool>; - field17?: pb<17, bool>; - field18?: pb<18, bool>; - question?: pb<19, bool>; - field20?: pb<20, bool>; - field22?: pb<22, bool>; - field23?: pb<23, bool>; - field24?: pb<24, bool>; - field25?: pb<25, bool>; - field26?: pb<26, bool>; - field27?: pb<27, bool>; - field28?: pb<28, bool>; - field29?: pb<29, bool>; - field30?: pb<30, bool>; - field31?: pb<31, bool>; - field32?: pb<32, bool>; - field5001?: pb<5001, bool>; - field5002?: pb<5002, bool>; - field5003?: pb<5003, bool>; -} - -export interface OidbGroupListConfig2 { - field1?: pb<1, bool>; - field2?: pb<2, bool>; - field3?: pb<3, bool>; - field4?: pb<4, bool>; - field5?: pb<5, bool>; - field6?: pb<6, bool>; - field7?: pb<7, bool>; - field8?: pb<8, bool>; -} - -export interface OidbGroupListConfig3 { - field5?: pb<5, bool>; - field6?: pb<6, bool>; -} - -export interface OidbGroupListConfig { - config1?: pb<1, OidbGroupListConfig1>; - config2?: pb<2, OidbGroupListConfig2>; - config3?: pb<3, OidbGroupListConfig3>; -} - -export interface OidbGroupListRequest { - config?: pb<1, OidbGroupListConfig>; -} - -// --- FE7_3: Group member list request body --- - -export interface OidbGroupMemberListBody { - memberName?: pb<10, bool>; - memberCard?: pb<11, bool>; - level?: pb<12, bool>; - field13?: pb<13, bool>; - field16?: pb<16, bool>; - specialTitle?: pb<17, bool>; - field18?: pb<18, bool>; - field20?: pb<20, bool>; - field21?: pb<21, bool>; - joinTimestamp?: pb<100, bool>; - lastMsgTimestamp?: pb<101, bool>; - shutUpTimestamp?: pb<102, bool>; - field103?: pb<103, bool>; - field104?: pb<104, bool>; - field105?: pb<105, bool>; - field106?: pb<106, bool>; - permission?: pb<107, bool>; - field200?: pb<200, bool>; - field201?: pb<201, bool>; -} - -export interface OidbGroupMemberListRequest { - groupUin?: pb<1, uint_32>; - field2?: pb<2, uint_32>; - field3?: pb<3, uint_32>; - body?: pb<4, OidbGroupMemberListBody>; - token?: pb<15, string>; -} - -// --- Group recall message (trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg) --- - -export interface GroupRecallInfo { - sequence?: pb<1, uint_32>; - random?: pb<2, uint_32>; - field3?: pb<3, uint_32>; -} - -export interface GroupRecallSettings { - field1?: pb<1, uint_32>; -} - -export interface GroupRecallRequest { - type?: pb<1, uint_32>; - groupUin?: pb<2, uint_32>; - info?: pb<3, GroupRecallInfo>; - settings?: pb<4, GroupRecallSettings>; -} - -// --- C2C (private) recall message (trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg) --- - -export interface C2CRecallInfo { - clientSequence?: pb<1, uint_32>; - random?: pb<2, uint_32>; - messageId?: pb<3, uint_64>; - timestamp?: pb<4, uint_32>; - field5?: pb<5, uint_32>; - messageSequence?: pb<6, uint_32>; -} - -export interface C2CRecallSettings { - field1?: pb<1, bool>; - field2?: pb<2, bool>; -} - -export interface C2CRecallRequest { - type?: pb<1, uint_32>; - targetUid?: pb<3, string>; - info?: pb<4, C2CRecallInfo>; - settings?: pb<5, C2CRecallSettings>; - field6?: pb<6, bool>; -} - -// --- 0x9082_1: Set group reaction --- - -export interface OidbGroupReaction { - groupUin?: pb<1, uint_32>; - sequence?: pb<2, uint_32>; - code?: pb<3, string>; - // 1 = legacy QQ face (short numeric id like "76"), 2 = unicode emoji - // (decimal codepoint string like "128516" for 😄). Omitting this - // field used to make unicode reactions fail server-side because the - // server defaulted to type=1 and couldn't resolve a 6-digit code. - type?: pb<4, uint_32>; -} - -// --- 0x6D8_1: Group file list --- - -export interface OidbGroupFileListReq { - groupUin?: pb<1, uint_32>; - appId?: pb<2, uint_32>; - targetDirectory?: pb<3, string>; - fileCount?: pb<5, uint_32>; - sortBy?: pb<9, uint_32>; - startIndex?: pb<13, uint_32>; - field17?: pb<17, uint_32>; - field18?: pb<18, uint_32>; -} - -export interface OidbGroupFileViewReq { - list?: pb<2, OidbGroupFileListReq>; -} - -export interface OidbGroupFileListFolderResp { - folderId?: pb<1, string>; - parentDirectoryId?: pb<2, string>; - folderName?: pb<3, string>; - createTime?: pb<4, uint_32>; - modifiedTime?: pb<5, uint_32>; - creatorUin?: pb<6, uint_32>; - creatorName?: pb<7, string>; - totalFileCount?: pb<8, uint_32>; -} - -export interface OidbGroupFileListFileResp { - fileId?: pb<1, string>; - fileName?: pb<2, string>; - fileSize?: pb<3, uint_64>; - busId?: pb<4, uint_32>; - uploadedTime?: pb<6, uint_32>; - expireTime?: pb<7, uint_32>; - modifiedTime?: pb<8, uint_32>; - downloadedTimes?: pb<9, uint_32>; - uploaderName?: pb<14, string>; - uploaderUin?: pb<15, uint_32>; - parentDirectory?: pb<16, string>; -} - -export interface OidbGroupFileListItemResp { - type?: pb<1, uint_32>; - folderInfo?: pb<2, OidbGroupFileListFolderResp>; - fileInfo?: pb<3, OidbGroupFileListFileResp>; -} - -export interface OidbGroupFileListResp { - retCode?: pb<1, uint_32>; - retMsg?: pb<2, string>; - clientWording?: pb<3, string>; - isEnd?: pb<4, bool>; - items?: pb_repeated<5, OidbGroupFileListItemResp>; -} - -export interface OidbGroupFileViewResp { - list?: pb<2, OidbGroupFileListResp>; -} - -// --- 0x6D6_2 / 0x6D6_3: Group file url & delete --- - -export interface OidbGroupFileUploadReq { - groupUin?: pb<1, uint_32>; - appId?: pb<2, uint_32>; - busId?: pb<3, uint_32>; - entrance?: pb<4, uint_32>; - targetDirectory?: pb<5, string>; - fileName?: pb<6, string>; - localDirectory?: pb<7, string>; - fileSize?: pb<8, uint_64>; - fileSha1?: pb<9, bytes>; - fileSha3?: pb<10, bytes>; - fileMd5?: pb<11, bytes>; - field15?: pb<15, bool>; -} - -export interface OidbGroupFileDownloadReq { - groupUin?: pb<1, uint_32>; - appId?: pb<2, uint_32>; - busId?: pb<3, uint_32>; - fileId?: pb<4, string>; -} - -export interface OidbGroupFileDeleteReq { - groupUin?: pb<1, uint_32>; - busId?: pb<3, uint_32>; - fileId?: pb<5, string>; -} - -export interface OidbGroupFileMoveReq { - groupUin?: pb<1, uint_32>; - appId?: pb<2, uint_32>; - busId?: pb<3, uint_32>; - fileId?: pb<4, string>; - parentDirectory?: pb<5, string>; - targetDirectory?: pb<6, string>; -} - -export interface OidbGroupFileReq { - file?: pb<1, OidbGroupFileUploadReq>; - download?: pb<3, OidbGroupFileDownloadReq>; - delete?: pb<4, OidbGroupFileDeleteReq>; - move?: pb<6, OidbGroupFileMoveReq>; -} - -export interface OidbGroupFileUploadResp { - retCode?: pb<1, int_32>; - retMsg?: pb<2, string>; - clientWording?: pb<3, string>; - uploadIp?: pb<4, string>; - serverDns?: pb<5, string>; - busId?: pb<6, int_32>; - fileId?: pb<7, string>; - checkKey?: pb<8, bytes>; - fileKey?: pb<9, bytes>; - boolFileExist?: pb<10, bool>; - uploadPort?: pb<14, uint_32>; -} - -export interface OidbGroupFileDownloadResp { - retCode?: pb<1, uint_32>; - retMsg?: pb<2, string>; - clientWording?: pb<3, string>; - downloadIp?: pb<4, string>; - downloadDns?: pb<5, string>; - downloadUrl?: pb<6, bytes>; - saveFileName?: pb<11, string>; -} - -export interface OidbGroupFileRetResp { - retCode?: pb<1, uint_32>; - retMsg?: pb<2, string>; - clientWording?: pb<3, string>; -} - -export interface OidbGroupFileResp { - upload?: pb<1, OidbGroupFileUploadResp>; - download?: pb<3, OidbGroupFileDownloadResp>; - delete?: pb<4, OidbGroupFileRetResp>; - move?: pb<6, OidbGroupFileRetResp>; -} - -// --- 0x6D9_4: Group file PUBLISH-AS-CHAT-MESSAGE --- -// -// Posts an already-uploaded group file (via 0x6D6_0 + highway) as a -// chat message in the group. This is a separate OIDB endpoint from -// the file upload — NOT a `MessageSvc.PbSendMsg` with a `TransElem` -// payload (sending the file as a transElem(24) is a RECEIVE-side -// decoding shape, and the QQ-NT server rejects it on send with -// `result=79`). -// -// Wire shape (mirrors Lagrange.Core V2's nesting): -// OidbBase.body (envelope field 4) -// → OidbGroupSendFileReq.body (field 5) ← the nested wrapper -// → OidbGroupSendFileBody { groupUin, type, info } -// -// Ports `dev/Lagrange.Core/.../Internal/Service/Message/GroupSendFileService.cs` -// + `Internal/Packets/Service/Oidb/Request/OidbSvcTrpcTcp0x6D9_4.cs`. - -export interface OidbGroupSendFileInfo { - busiType?: pb<1, uint_32>; // hardcoded 102 - fileId?: pb<2, string>; // uuid from 0x6D6_0 upload response - field3?: pb<3, uint_32>; // random uint32 (msg id seed) - field4?: pb<4, string>; // null/empty on send - field5?: pb<5, bool>; // hardcoded true -} - -export interface OidbGroupSendFileBody { - groupUin?: pb<1, uint_32>; - type?: pb<2, uint_32>; // hardcoded 2 (= chat post) - info?: pb<3, OidbGroupSendFileInfo>; -} - -export interface OidbGroupSendFileReq { - body?: pb<5, OidbGroupSendFileBody>; -} - -// --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops --- - -export interface OidbGroupFileCreateFolderReq { - groupUin?: pb<1, uint_32>; - rootDirectory?: pb<3, string>; - folderName?: pb<4, string>; -} - -export interface OidbGroupFileDeleteFolderReq { - groupUin?: pb<1, uint_32>; - folderId?: pb<3, string>; -} - -export interface OidbGroupFileRenameFolderReq { - groupUin?: pb<1, uint_32>; - folderId?: pb<3, string>; - newFolderName?: pb<4, string>; -} - -export interface OidbGroupFileFolderReq { - create?: pb<1, OidbGroupFileCreateFolderReq>; - delete?: pb<2, OidbGroupFileDeleteFolderReq>; - rename?: pb<3, OidbGroupFileRenameFolderReq>; -} - -export interface OidbGroupFileFolderRetResp { - retcode?: pb<1, uint_32>; - retMsg?: pb<2, string>; - clientWording?: pb<3, string>; -} - -export interface OidbGroupFileFolderResp { - create?: pb<1, OidbGroupFileFolderRetResp>; - delete?: pb<2, OidbGroupFileFolderRetResp>; - rename?: pb<3, OidbGroupFileFolderRetResp>; -} - -// --- 0xE37_1200: Private file download url --- - -export interface OidbPrivateFileDownloadReqBody { - receiverUid?: pb<10, string>; - fileUuid?: pb<20, string>; - type?: pb<30, uint_32>; - fileHash?: pb<60, string>; - t2?: pb<601, uint_32>; -} - -export interface OidbPrivateFileDownloadReq { - subCommand?: pb<1, uint_32>; - field2?: pb<2, uint_32>; - body?: pb<14, OidbPrivateFileDownloadReqBody>; - field101?: pb<101, uint_32>; - field102?: pb<102, uint_32>; - field200?: pb<200, uint_32>; - field99999?: pb<99999, bytes>; -} - -export interface OidbPrivateFileDownloadRespResult { - server?: pb<20, string>; - port?: pb<40, uint_32>; - url?: pb<50, string>; -} - -export interface OidbPrivateFileDownloadRespBody { - state?: pb<20, string>; - result?: pb<30, OidbPrivateFileDownloadRespResult>; -} - -export interface OidbPrivateFileDownloadResp { - body?: pb<14, OidbPrivateFileDownloadRespBody>; -} - -// --- 0xE37_1700: Private file upload --- - -export interface OidbPrivateFileUploadReqBody { - senderUid?: pb<10, string>; - receiverUid?: pb<20, string>; - fileSize?: pb<30, uint_32>; - fileName?: pb<40, string>; - md510MCheckSum?: pb<50, bytes>; - sha1CheckSum?: pb<60, bytes>; - localPath?: pb<70, string>; - md5CheckSum?: pb<110, bytes>; - sha3CheckSum?: pb<120, bytes>; -} - -export interface OidbPrivateFileUploadReq { - command?: pb<1, uint_32>; - seq?: pb<2, int_32>; - upload?: pb<19, OidbPrivateFileUploadReqBody>; - businessId?: pb<101, int_32>; - clientType?: pb<102, int_32>; - flagSupportMediaPlatform?: pb<200, int_32>; -} - -// IPv4 wire message used inside ApplyUploadRespV3.rtpMediaPlatformUploadAddress -// (field 210). Sourced from acidify's `IPv4` class — outIP/inIP are -// little-endian-packed 32-bit IPv4 addresses (byte order: low byte = first -// octet), decoded via the standard `(ip & 0xFF).(ip>>8 & 0xFF)....` recipe. -// outPort/inPort are the matching port for each leg (out = WAN, in = LAN). -// iPType is the address family hint (1 = IPv4, etc — acidify treats it -// purely as metadata, no behavior). -export interface IPv4 { - outIP?: pb<1, int_32>; - outPort?: pb<2, int_32>; - inIP?: pb<3, int_32>; - inPort?: pb<4, int_32>; - iPType?: pb<5, int_32>; -} - -export interface OidbPrivateFileUploadRespBody { - retCode?: pb<10, int_32>; - retMsg?: pb<20, string>; - // 30/40/50 (totalSpace/usedSpace/uploadedSize int64) intentionally - // omitted — proton only needs fields we actually consume, and the - // quota numbers don't drive any code path. - uploadIp?: pb<60, string>; - // Cross-checked against LagrangeGo `OidbSvcTrpcTcp0xE37_800.proto` - // (fields 60-170 enumerated below) + NapCat `Oidb.0XE37_800.ts` + - // acidify (most recent NT-protocol fork, 2026-04). Real server in - // 2026 has been observed to leave the legacy host fields empty and - // put the host into the new field 210 (`rtpMediaPlatformUploadAddress`, - // repeated IPv4 messages) instead — the consumer walks them in that - // order. Decoding the legacy fields too means we keep working against - // older server rollouts. - uploadDomain?: pb<70, string>; - uploadPort?: pb<80, uint_32>; - uuid?: pb<90, string>; - uploadKey?: pb<100, bytes>; - boolFileExist?: pb<110, bool>; - uploadIpList?: pb_repeated<130, string>; - uploadHttpsPort?: pb<140, int_32>; - uploadHttpsDomain?: pb<150, string>; - uploadDns?: pb<160, string>; - uploadLanip?: pb<170, string>; - // Field 200 — acidify renamed this to `fileIdCrc` in their 2026-04 - // refactor; we keep `fileAddon` because the wire bytes are identical - // and our callers already read `fileAddon` as the file-hash blob (it's - // a hex string in practice). Worth renaming if a consumer ever needs - // the new semantic. - fileAddon?: pb<200, string>; - // Field 210 — the new "host carrier" the NT server actually populates - // in current rollouts. Each IPv4 entry has `inIP`/`inPort` (LAN) + - // `outIP`/`outPort` (WAN). acidify reads `inIP`+`inPort` exclusively; - // we follow suit because that's what the highway HTTP PUT needs to - // reach (same datacenter as the OIDB endpoint that returned this). - rtpMediaPlatformUploadAddress?: pb_repeated<210, IPv4>; - mediaPlatformUploadKey?: pb<220, bytes>; -} - -export interface OidbPrivateFileUploadResp { - upload?: pb<19, OidbPrivateFileUploadRespBody>; -} - -// --- NTV2 Rich Media (0x9067_202): Download RKey --- - -export interface NTV2CommonHead { - requestId?: pb<1, uint_32>; - command?: pb<2, uint_32>; -} - -export interface NTV2C2CUserInfo { - accountType?: pb<1, uint_32>; - targetUid?: pb<2, string>; -} - -export interface NTV2GroupInfo { - groupUin?: pb<1, uint_32>; -} - -export interface NTV2SceneInfo { - requestType?: pb<101, uint_32>; - businessType?: pb<102, uint_32>; - sceneType?: pb<200, uint_32>; - c2c?: pb<201, NTV2C2CUserInfo>; - group?: pb<202, NTV2GroupInfo>; -} - -export interface NTV2ClientMeta { - agentType?: pb<1, uint_32>; -} - -export interface NTV2ReqHead { - common?: pb<1, NTV2CommonHead>; - scene?: pb<2, NTV2SceneInfo>; - client?: pb<3, NTV2ClientMeta>; -} - -export interface NTV2DownloadRKeyReq { - types?: pb_repeated<1, uint_32>; -} - -export interface NTV2FileType { - type?: pb<1, uint_32>; - picFormat?: pb<2, uint_32>; - videoFormat?: pb<3, uint_32>; - voiceFormat?: pb<4, uint_32>; -} - -export interface NTV2FileInfo { - fileSize?: pb<1, uint_32>; - fileHash?: pb<2, string>; - fileSha1?: pb<3, string>; - fileName?: pb<4, string>; - type?: pb<5, NTV2FileType>; - width?: pb<6, uint_32>; - height?: pb<7, uint_32>; - time?: pb<8, uint_32>; - original?: pb<9, uint_32>; -} - -export interface NTV2IndexNode { - info?: pb<1, NTV2FileInfo>; - fileUuid?: pb<2, string>; - storeId?: pb<3, uint_32>; - uploadTime?: pb<4, uint_32>; - ttl?: pb<5, uint_32>; - subType?: pb<6, uint_32>; -} - -export interface NTV2VideoDownloadExt { - busiType?: pb<1, uint_32>; - sceneType?: pb<2, uint_32>; - subBusiType?: pb<3, uint_32>; -} - -export interface NTV2DownloadExt { - video?: pb<2, NTV2VideoDownloadExt>; -} - -export interface NTV2DownloadReq { - node?: pb<1, NTV2IndexNode>; - download?: pb<2, NTV2DownloadExt>; -} - -export interface NTV2RichMediaReq { - reqHead?: pb<1, NTV2ReqHead>; - download?: pb<3, NTV2DownloadReq>; - downloadRkey?: pb<4, NTV2DownloadRKeyReq>; -} - -export interface NTV2RespHead { - common?: pb<1, NTV2CommonHead>; - retCode?: pb<2, uint_32>; - message?: pb<3, string>; -} - -export interface NTV2RKeyInfo { - rkey?: pb<1, string>; - rkeyTtlSec?: pb<2, uint_64>; - storeId?: pb<3, uint_32>; - rkeyCreateTime?: pb<4, uint_32>; - type?: pb<5, uint_32>; -} - -export interface NTV2DownloadRKeyResp { - rkeys?: pb_repeated<1, NTV2RKeyInfo>; -} - -export interface NTV2MediaDownloadInfo { - domain?: pb<1, string>; - urlPath?: pb<2, string>; - httpsPort?: pb<3, uint_32>; -} - -export interface NTV2MediaDownloadResp { - rKeyParam?: pb<1, string>; - rKeyTtlSecond?: pb<2, uint_32>; - info?: pb<3, NTV2MediaDownloadInfo>; - rKeyCreateTime?: pb<4, uint_32>; -} - -export interface NTV2RichMediaResp { - respHead?: pb<1, NTV2RespHead>; - download?: pb<3, NTV2MediaDownloadResp>; - downloadRkey?: pb<4, NTV2DownloadRKeyResp>; -} - -// --- 0xB6E_2: Set friend remark --- - -export interface OidbSetFriendRemark { - targetUid?: pb<1, string>; - remark?: pb<2, string>; -} - -// --- 0x9082_2: Set group reaction (remove) — same schema as set --- -// (0x9082_1 for add, 0x9082_2 for remove — both use OidbGroupReactionSchema) - -// --- Group file count (0x6D8_3) --- - -export interface OidbGroupFileCountReq { - groupUin?: pb<1, uint_32>; - appId?: pb<2, uint_32>; - busId?: pb<3, uint_32>; -} - -export interface OidbGroupFileCountResp { - fileCount?: pb<1, uint_32>; - maxCount?: pb<2, uint_32>; - isEnd?: pb<3, bool>; -} - -export interface OidbGroupFileCountViewReq { - count?: pb<3, OidbGroupFileCountReq>; -} - -export interface OidbGroupFileCountViewResp { - count?: pb<3, OidbGroupFileCountResp>; -} - - -// --- trpc.msg.msg_svc.MsgService.SsoReadedReport --- - -export interface GroupReadedReportItem { - groupUin?: pb<1, uint_64>; - lastReadSeq?: pb<2, uint_64>; -} - -export interface C2CReadedReportItem { - uid?: pb<2, string>; - lastReadTime?: pb<3, uint_64>; - lastReadSeq?: pb<4, uint_64>; -} - -export interface SsoReadedReportReq { - groupList?: pb_repeated<1, GroupReadedReportItem>; - c2cList?: pb_repeated<2, C2CReadedReportItem>; -} - - -// --- 0x102A_1: Get Client Key --- - -export interface OidbClientKeyReq { -} - -export interface OidbClientKeyResp { - keyIndex?: pb<2, uint_32>; - clientKey?: pb<3, string>; - expireTime?: pb<4, uint_32>; -} - - -// --- 0x102A_0: Get PSKey --- - -export interface OidbGetPskeyReq { - domainList?: pb_repeated<1, string>; -} - -export interface OidbPskeyItem { - domain?: pb<1, string>; - pskey?: pb<2, string>; - expireTime?: pb<3, uint_64>; -} - -export interface OidbGetPskeyResp { - pskeyItems?: pb_repeated<1, OidbPskeyItem>; -} - - -// customExt sub-message of SetStatus. Populated only by -// set_diy_online_status (status=10 + extStatus=2000 + this payload); -// regular set_online_status leaves field 4 unset. -// -// Wire (from napcat packet/transformer/proto/action/action.ts SetStatusCustomExt): -// 1 faceId (uint32) — face icon id, e.g. "Q我吧" sticker -// 2 text (string) — wording shown next to the icon -// 3 field3 (uint32) — face_type / template id; observed values 1..3 -export interface SetStatusCustomExt { - faceId?: pb<1, uint_32>; - text?: pb<2, string>; - faceType?: pb<3, uint_32>; -} - -export interface SetStatusReq { - status?: pb<1, int_32>; - extStatus?: pb<2, int_32>; - batteryStatus?: pb<3, int_32>; - customExt?: pb<4, SetStatusCustomExt>; -} - -export interface SetStatusResp { - errCode?: pb<1, int_32>; // 盲猜字段 1 是错误码(虽然成功时没下发,默认 0) - errMsg?: pb<2, string>; // 返回的 "set status success" -} - - -export interface OidbProfileStringItem { - fieldId?: pb<1, uint_32>; - value?: pb<2, string>; -} - -export interface OidbProfileIntItem { - fieldId?: pb<1, uint_32>; - value?: pb<2, uint_64>; -} - -export interface OidbSetProfile { - uin?: pb<1, uint_64>; - stringProfiles?: pb_repeated<2, OidbProfileStringItem>; - intProfiles?: pb_repeated<3, OidbProfileIntItem>; -} - - -export interface Oidb0x7edInteraction { - totalCount?: pb<1, uint_32>; - newCount?: pb<2, uint_32>; - todayCount?: pb<3, uint_32>; - lastTime?: pb<4, uint_64>; - // userInfos: { field: 7, type: 'repeated_message' ... } // 我没有这个字段,期待未来补全 -} - -export interface Oidb0x7edUserLikeInfo { - uid?: pb<1, string>; - time?: pb<2, uint_64>; - favoriteInfo?: pb<3, Oidb0x7edInteraction>; - voteInfo?: pb<4, Oidb0x7edInteraction>; -} - -export interface Oidb0x7edReq { - targetUid?: pb<1, string>; - basic?: pb<2, uint_32>; - vote?: pb<3, uint_32>; - favorite?: pb<4, uint_32>; - start?: pb<12, uint_32>; - limit?: pb<103, uint_32>; // 0xB8 0x06 -} - -export interface Oidb0x7edResp { - userLikeInfos?: pb_repeated<1, Oidb0x7edUserLikeInfo>; -} - - -export interface Oidb0x8a7Req { - basic1?: pb<1, uint_32>; - basic2?: pb<2, uint_32>; - basic3?: pb<3, uint_32>; - uin?: pb<4, uint_64>; - groupId?: pb<5, uint_64>; - type?: pb<12, uint_32>; -} - -export interface Oidb0x8a7Resp { - uinRemain?: pb<2, uint_32>; - groupRemain?: pb<3, uint_32>; - msg?: pb<4, string>; - canAtAll?: pb<6, bool>; -} - -export interface Oidb0xe17Req { - jsonBody?: pb<3, string>; -} - -export interface Oidb0xe17Resp { - jsonBody?: pb<4, string>; -} - -export interface Oidb0x112aProfileInfo { - tag?: pb<1, uint_32>; - value?: pb<2, string>; -} - -export interface Oidb0x112aReq { - uin?: pb<1, uint_64>; - profile?: pb<2, Oidb0x112aProfileInfo>; -} - -export interface Oidb0x112aResp {} - -export interface Oidb0xcd4ReqBody { - uid?: pb<1, string>; - chatType?: pb<2, uint_32>; // 默认为 0 - eventType?: pb<3, uint_32>; // 输入状态 1 等 -} - -export interface Oidb0xcd4Req { - reqBody?: pb<1, Oidb0xcd4ReqBody>; -} - -export interface Oidb0xcd4Resp {} - - -export interface Oidb0x990TranslateReq { - srcLang?: pb<1, string>; - dstLang?: pb<2, string>; - words?: pb_repeated<3, string>; -} - -export interface Oidb0x990Req { - translateReq?: pb<2, Oidb0x990TranslateReq>; - tag10?: pb<10, uint_32>; - tag12?: pb<12, uint_32>; -} - -export interface Oidb0x990TranslateResp { - errorCode?: pb<1, uint_32>; - errorMsg?: pb<2, string>; - srcLang?: pb<3, string>; - dstLang?: pb<4, string>; - srcWords?: pb_repeated<5, string>; - dstWords?: pb_repeated<6, string>; -} - -export interface Oidb0x990Resp { - translateResp?: pb<2, Oidb0x990TranslateResp>; -} - -export interface MiniAppShareReqBody { - appid?: pb<2, string>; - title?: pb<3, string>; - desc?: pb<4, string>; - picUrl?: pb<9, string>; - jumpUrl?: pb<11, string>; - iconUrl?: pb<12, string>; -} - -export interface MiniAppShareReq { - sdkVersion?: pb<2, string>; - body?: pb<4, MiniAppShareReqBody>; -} - -export interface MiniAppShareRespBody { - jsonStr?: pb<2, string>; -} - -export interface MiniAppShareResp { - status?: pb<2, uint_32>; - msg?: pb<3, string>; - body?: pb<4, MiniAppShareRespBody>; -} - -export interface Oidb0x112eReq { - botAppid?: pb<3, uint_64>; - msgSeq?: pb<4, uint_64>; - buttonId?: pb<5, string>; - callbackData?: pb<6, string>; - unknown7?: pb<7, uint_32>; - groupId?: pb<8, uint_64>; - unknown9?: pb<9, uint_32>; -} - -export interface Oidb0x112eResp { - result?: pb<3, uint_32>; - promptText?: pb<4, string>; - errMsg?: pb<5, string>; -} - -export interface Oidb0xeb7SignInInfo { - uin?: pb<1, string>; - groupId?: pb<2, string>; - version?: pb<3, string>; -} - -export interface Oidb0xeb7Req { - signInInfo?: pb<2, Oidb0xeb7SignInInfo>; -} - -export interface Oidb0xeb7Resp {} - -// --- Faceroam.OpReq: Fetch custom face --- - -export interface FaceroamOpReqInner { - field1?: pb<1, uint_32>; - osVersion?: pb<2, string>; - qqVersion?: pb<3, string>; -} - -export interface FaceroamOpReq { - inner?: pb<1, FaceroamOpReqInner>; - uin?: pb<2, uint_64>; - field3?: pb<3, uint_32>; - field6?: pb<6, uint_32>; -} - -export interface FaceroamOpRespItem { - faceIds?: pb_repeated<1, string>; - category?: pb<3, string>; - totalCount?: pb<4, uint_32>; -} - -export interface FaceroamOpResp { - retCode?: pb<1, uint_32>; - message?: pb<2, string>; - field3?: pb<3, uint_32>; - item?: pb<4, FaceroamOpRespItem>; -} - -// --- 0x9083_1: Get emoji likes --- - -export interface Oidb0x9083Req { - groupId?: pb<2, uint_64>; - sequence?: pb<3, uint_32>; - emojiType?: pb<4, uint_32>; - emojiId?: pb<5, string>; - cookie?: pb<6, bytes>; - field7?: pb<7, uint_32>; - count?: pb<8, uint_32>; - field12?: pb<12, uint_32>; -} - -export interface Oidb0x9083RespUserInfo { - uin?: pb<1, uint_64>; - field3?: pb<3, uint_32>; -} - -export interface Oidb0x9083RespInner { - userInfo?: pb<1, Oidb0x9083RespUserInfo>; - field4?: pb<4, uint_32>; -} - -export interface Oidb0x9083Resp { - inner?: pb<4, Oidb0x9083RespInner>; - cookie?: pb<5, bytes>; -} - -// --- 0x8a0_1: Kick group members (batch) --- - -export interface Oidb0x8a0Req { - groupId?: pb<1, uint_64>; - targetUids?: pb_repeated<3, string>; - rejectAddRequest?: pb<4, uint_32>; - kickReason?: pb<5, bytes>; - field12?: pb<12, uint_32>; -} - -export interface Oidb0x8a0Resp {} - -// --- 0xf16_1: Set group remark --- - -export interface Oidb0xf16Inner { - groupId?: pb<1, uint_64>; - remark?: pb<3, string>; -} - -export interface Oidb0xf16Req { - inner?: pb<1, Oidb0xf16Inner>; - field12?: pb<12, uint_32>; -} - -export interface Oidb0xf16Resp {} - -// --- 0xF90_{1,2,3}: Set / complete / cancel group todo --- -// All three subCmds share the same body (groupUin + msgSeq); only the -// envelope subCmd differs. Sources: napcat -// packet/transformer/action/{Set,Complete,Cancel}GroupTodo.ts. - -export interface OidbGroupTodo { - groupUin?: pb<1, uint_32>; - msgSeq?: pb<2, uint_64>; -} - -// --- 0xFE1_2: Get stranger profile (used for online/ext status lookup) --- - -export interface OidbStrangerStatusKey { - key?: pb<1, uint_32>; -} - -export interface OidbStrangerStatusReq { - uin?: pb<1, uint_32>; - key?: pb_repeated<3, OidbStrangerStatusKey>; -} - -export interface OidbStrangerStatusRespStatus { - key?: pb<1, uint_32>; - value?: pb<2, uint_64>; -} - -export interface OidbStrangerStatusRespData { - status?: pb<2, OidbStrangerStatusRespStatus>; -} - -export interface OidbStrangerStatusResp { - data?: pb<1, OidbStrangerStatusRespData>; -} - -// --- 0x929D_0: Fetch AI voice character list --- - -export interface OidbAiVoiceListReq { - groupUin?: pb<1, uint_32>; - chatType?: pb<2, uint_32>; -} - -export interface OidbAiVoiceListEntry { - voiceId?: pb<1, string>; - voiceDisplayName?: pb<2, string>; - voiceExampleUrl?: pb<3, string>; -} - -export interface OidbAiVoiceListCategory { - category?: pb<1, string>; - voices?: pb_repeated<2, OidbAiVoiceListEntry>; -} - -export interface OidbAiVoiceListResp { - content?: pb_repeated<1, OidbAiVoiceListCategory>; -} - -// --- 0x929B_0: Trigger AI voice synthesis (returns server-side IndexNode) --- - -export interface OidbAiVoiceSession { - sessionId?: pb<1, uint_32>; -} - -export interface OidbAiVoiceReq { - groupUin?: pb<1, uint_32>; - voiceId?: pb<2, string>; - text?: pb<3, string>; - chatType?: pb<4, uint_32>; - session?: pb<5, OidbAiVoiceSession>; -} - -// We only need the fields the OneBot adapter consumes back: the -// IndexNode payload (which feeds fetchGroupPttUrlByNode) and the -// statusCode that the server uses to signal "still rendering, retry". - -export interface OidbAiVoiceFileType { - type?: pb<1, uint_32>; - picFormat?: pb<2, uint_32>; - videoFormat?: pb<3, uint_32>; - voiceFormat?: pb<4, uint_32>; -} - -export interface OidbAiVoiceFileInfo { - fileSize?: pb<1, uint_32>; - fileHash?: pb<2, string>; - fileSha1?: pb<3, string>; - fileName?: pb<4, string>; - type?: pb<5, OidbAiVoiceFileType>; - width?: pb<6, uint_32>; - height?: pb<7, uint_32>; - time?: pb<8, uint_32>; - original?: pb<9, uint_32>; -} - -export interface OidbAiVoiceIndexNode { - info?: pb<1, OidbAiVoiceFileInfo>; - fileUuid?: pb<2, string>; - storeId?: pb<3, uint_32>; - uploadTime?: pb<4, uint_32>; - ttl?: pb<5, uint_32>; - subType?: pb<6, uint_32>; -} - -export interface OidbAiVoiceMsgInfoBody { - index?: pb<1, OidbAiVoiceIndexNode>; -} - -export interface OidbAiVoiceMsgInfo { - msgInfoBody?: pb_repeated<1, OidbAiVoiceMsgInfoBody>; -} - -export interface OidbAiVoiceResp { - statusCode?: pb<1, uint_32>; - field2?: pb<2, uint_32>; - field3?: pb<3, uint_32>; - msgInfo?: pb<4, OidbAiVoiceMsgInfo>; -} - -// --- Highway cmdId 3000: GroupAvatarExtra --- -// Ported from Lagrange.Core/Internal/Packets/Service/Highway/GroupAvatarExtra.cs. -// Field values are protocol-prescribed constants (Lagrange comments on each). - -export interface GroupAvatarExtraField3 { - field1?: pb<1, uint_32>; // observed value: 1 -} - -export interface GroupAvatarExtra { - type?: pb<1, uint_32>; // observed value: 101 - groupUin?: pb<2, uint_32>; - field3?: pb<3, GroupAvatarExtraField3>; - field5?: pb<5, uint_32>; // observed value: 3 - field6?: pb<6, uint_32>; // observed value: 1 -} - -// ── Group Album: TRPC envelopes ──────────────────────────────────── -// Raw TRPC packets (not OIDB-wrapped) for the qzone group-album -// service. Service commands look like -// `QunAlbum.trpc.qzone.webapp_qun_*`. Field naming follows the legacy -// schema's positional convention (`field1`/`field2`/...) where the -// reverse-engineered packet has no semantic name yet — keep it stable -// for the parity audit. - -// Common: `extMap` trace tag carried by every request envelope. -export interface ExtMapEntry { - key?: pb<1, string>; - value?: pb<2, string>; -} - -// ── GetMediaList: list media in a group album with pagination ────── - -export interface ReqInfo { - groupId?: pb<1, string>; - albumId?: pb<2, string>; - field3?: pb<3, int_32>; - attachInfo?: pb<4, string>; // 翻页 cursor — empty for the first page - field5?: pb<5, string>; -} - -export interface GetMediaListRequest { - field1?: pb<1, int_32>; - field2?: pb<2, bytes>; - field3?: pb<3, bytes>; - reqInfo?: pb<4, ReqInfo>; - traceId?: pb<5, string>; - extMap?: pb_repeated<10, ExtMapEntry>; -} - -export interface UrlInfo { - url?: pb<1, string>; - width?: pb<2, uint_32>; - height?: pb<3, uint_32>; -} - -export interface PhotoUrl { - spec?: pb<1, uint_32>; - url?: pb<2, UrlInfo>; -} - -export interface ImageInfo { - name?: pb<1, string>; - sloc?: pb<2, string>; - lloc?: pb<3, string>; - photoUrls?: pb_repeated<4, PhotoUrl>; - defaultUrl?: pb<5, UrlInfo>; - isGif?: pb<6, bool>; - hasRaw?: pb<7, bool>; -} - -export interface MediaInfo { - type?: pb<1, uint_32>; - image?: pb<2, ImageInfo>; - uploader?: pb<6, string>; - batchId?: pb<7, uint_64>; - uploadTime?: pb<8, uint_64>; -} - -// Inline-in-legacy: `GetMediaListRspDataSchema.albumInfo.schema`. -export interface GetMediaListAlbumInfo { - albumId?: pb<1, string>; - owner?: pb<2, string>; - name?: pb<3, string>; -} - -export interface GetMediaListRspData { - albumInfo?: pb<1, GetMediaListAlbumInfo>; - mediaList?: pb_repeated<3, MediaInfo>; - prevAttachInfo?: pb<4, string>; - nextAttachInfo?: pb<5, string>; -} - -export interface GetMediaListResponse { - field1?: pb<1, int_32>; - field2?: pb<2, bytes>; - field3?: pb<3, bytes>; - data?: pb<4, GetMediaListRspData>; -} - -// ── DoQunComment: post a comment on a media item ─────────────────── - -export interface CommentContentItem { - type?: pb<1, uint_32>; - content?: pb<2, string>; -} - -export interface CommentUser { - uin?: pb<13, string>; -} - -// Inline-in-legacy: `CommentReqContentSchema.field3.schema`. -export interface CommentReqContentMeta { - field1?: pb<1, uint_32>; - field2?: pb<2, string>; - field3?: pb<3, string>; - field4?: pb<4, string>; - field5?: pb<5, uint_32>; - field6?: pb<6, string>; -} - -export interface CommentReqContent { - field2?: pb<2, CommentUser>; - field3?: pb<3, CommentReqContentMeta>; - clientKey?: pb<7, string>; -} - -// Inline-in-legacy: `CommentReqPhotoInfoSchema.field1.schema.field2.schema`. -export interface CommentReqPhotoMeta { - field1?: pb<1, uint_32>; - field2?: pb<2, string>; - lloc?: pb<3, string>; - field4?: pb<4, string>; - field6?: pb<6, string>; - field7?: pb<7, uint_32>; - field8?: pb<8, uint_32>; - field9?: pb<9, uint_32>; - field14?: pb<14, uint_32>; - field15?: pb<15, uint_32>; - field17?: pb<17, uint_32>; -} - -// Inline-in-legacy: `CommentReqPhotoInfoSchema.field1.schema`. -export interface CommentReqPhotoWrap { - field2?: pb<2, CommentReqPhotoMeta>; -} - -export interface CommentReqPhotoInfo { - field1?: pb<1, CommentReqPhotoWrap>; - albumId?: pb<3, string>; - field5?: pb<5, uint_32>; -} - -// Inline-in-legacy: `CommentReqBodySchema.field1.schema`. -export interface CommentReqBodyHeader { - field3?: pb<3, uint_32>; - field4?: pb<4, string>; -} - -// Inline-in-legacy: `CommentReqBodySchema.field2.schema`. -export interface CommentReqBodyUserWrap { - field1?: pb<1, CommentUser>; -} - -export interface CommentReqBody { - field1?: pb<1, CommentReqBodyHeader>; - field2?: pb<2, CommentReqBodyUserWrap>; - field5?: pb<5, CommentReqPhotoInfo>; // 抓包证实评论文本在 field 5 -} - -// Inline-in-legacy: `DoQunCommentRequestSchema.body.schema`. -export interface DoQunCommentRequestBody { - groupId?: pb<2, string>; - field3?: pb<3, uint_32>; - reqBody?: pb<4, CommentReqBody>; - field5?: pb<5, CommentReqContent>; // 评论文本在外层 field 5 -} - -export interface DoQunCommentRequest { - field1?: pb<1, int_32>; - field2?: pb<2, bytes>; - field3?: pb<3, bytes>; - body?: pb<4, DoQunCommentRequestBody>; - traceId?: pb<5, string>; - extMap?: pb_repeated<10, ExtMapEntry>; -} - -export interface CommentRespUser { - uin?: pb<13, string>; -} - -export interface CommentRespContent { - type?: pb<1, uint_32>; - content?: pb<2, string>; -} - -export interface CommentRespData { - id?: pb<1, string>; - user?: pb<2, CommentRespUser>; - content?: pb_repeated<3, CommentRespContent>; - time?: pb<4, uint_64>; - clientKey?: pb<7, string>; -} - -// Inline-in-legacy: `DoQunCommentResponseSchema.comment.schema`. -export interface DoQunCommentResponseComment { - data?: pb<2, CommentRespData>; -} - -export interface DoQunCommentResponse { - field1?: pb<1, int_32>; - comment?: pb<4, DoQunCommentResponseComment>; -} - -// ── DoQunLike: like / unlike a media item ────────────────────────── - -export interface DoQunLikeReqLikeInfo { - id?: pb<1, string>; - status?: pb<3, uint_32>; -} - -export interface DoQunLikeReqCellCommon { - time?: pb<3, uint_64>; - feedId?: pb<4, string>; -} - -export interface DoQunLikeReqCellUser { - uin?: pb<13, string>; // 抓包证实 uin 是 field 13 -} - -export interface DoQunLikeReqCellUserInfo { - user?: pb<1, DoQunLikeReqCellUser>; -} - -export interface DoQunLikeReqCellQunInfo { - qunId?: pb<1, string>; -} - -export interface DoQunLikeReqCellMedia { - albumId?: pb<3, string>; - batchId?: pb<5, uint_64>; -} - -export interface DoQunLikeReqFeedPublish { - cellCommon?: pb<1, DoQunLikeReqCellCommon>; - cellUserInfo?: pb<2, DoQunLikeReqCellUserInfo>; - cellMedia?: pb<5, DoQunLikeReqCellMedia>; - cellQunInfo?: pb<12, DoQunLikeReqCellQunInfo>; -} - -export interface DoQunLikeReqBody { - type?: pb<2, uint_32>; - like?: pb<3, DoQunLikeReqLikeInfo>; - publish?: pb<4, DoQunLikeReqFeedPublish>; - clientKey?: pb<5, string>; -} - -export interface DoQunLikeRequest { - field1?: pb<1, int_32>; - field2?: pb<2, string>; - field3?: pb<3, string>; - body?: pb<4, DoQunLikeReqBody>; - extMap?: pb_repeated<10, ExtMapEntry>; -} - -export interface DoQunLikeRespBody { - like?: pb<2, DoQunLikeReqLikeInfo>; -} - -export interface DoQunLikeResponse { - field1?: pb<1, int_32>; - body?: pb<4, DoQunLikeRespBody>; -} - -// ── DeleteMedias: delete a media item from a group album ─────────── - -export interface DeleteMediasReqBody { - groupId?: pb<1, string>; - albumId?: pb<2, string>; - lloc?: pb<3, string>; -} - -export interface DeleteMediasRequest { - field1?: pb<1, int_32>; - field2?: pb<2, string>; - field3?: pb<3, string>; - body?: pb<4, DeleteMediasReqBody>; - traceId?: pb<5, string>; - extMap?: pb_repeated<10, ExtMapEntry>; -} - -export interface DeleteMediasResponse { - field1?: pb<1, int_32>; // expected 8694 for success - field2?: pb<2, int_32>; // error code (e.g. 10023) - field3?: pb<3, string>; // error message -} diff --git a/packages/core/src/bridge/web-actions/cookies.ts b/packages/core/src/bridge/web-actions/cookies.ts deleted file mode 100644 index fb398d79..00000000 --- a/packages/core/src/bridge/web-actions/cookies.ts +++ /dev/null @@ -1,149 +0,0 @@ -// Web-cookie / credential primitives — every other web-action in this -// directory builds on these. Each Bridge-level web call ends up doing -// roughly: forceFetchClientKey -> ptlogin2 jump -> cookie dict -> -// thread the cookies into a qun.qq.com REST endpoint. - -import type { Bridge } from '../bridge'; -import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; -import type { - OidbClientKeyReq, - OidbClientKeyResp, - OidbGetPskeyReq, - OidbGetPskeyResp, -} from '../proto/proton/oidb-action'; -import { RequestUtil } from '../web/request-util'; - -export async function forceFetchClientKey(bridge: Bridge) { - const env = makeOidbEnvelope(0x102A, 1, {}); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_1', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const clientKey = resp?.clientKey || ''; - // keyIndex falls back to "19" — origin unknown but the value is what - // every NapCat-derived implementation uses when the server omits it. - const keyIndex = String(resp?.keyIndex || '19'); - - return { - clientKey, - keyIndex, - expireTime: String(resp?.expireTime || '1800'), - }; -} - -export async function getPSkey(bridge: Bridge, domainList: string[]) { - const env = makeOidbEnvelope(0x102A, 0, { domainList }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_0', encodeOidbEnv(env)); - const resp = decodeOidbEnv(respBytes).body; - - const domainPskeyMap = new Map(); - - if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) { - for (const item of resp.pskeyItems) { - if (item.domain && item.pskey) { - domainPskeyMap.set(item.domain, item.pskey); - } - } - } - - return { domainPskeyMap }; -} - -export async function getCookies(bridge: Bridge, domain: string) { - const ClientKeyData = await forceFetchClientKey(bridge); - - // Build the ptlogin2 jump URL: this is the canonical way for the - // bot to swap its clientKey for cookie-jar entries on a given - // qq.com subdomain. - const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin + - '&clientkey=' + ClientKeyData.clientKey + - '&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex; - - const data = await RequestUtil.HttpsGetCookies(requestUrl); - - if (!data['p_skey'] || data['p_skey'].length === 0) { - // ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey - // for the same domain. Errors are swallowed so the caller can - // still proceed with whatever cookies it did get. - try { - const pskeyData = await getPSkey(bridge, [domain]); - const pskey = pskeyData.domainPskeyMap.get(domain); - if (pskey) { - data['p_skey'] = pskey; - } - } catch { - return data; - } - } - - return data; -} - -export async function getSKey(bridge: Bridge): Promise { - const ClientKeyData = await forceFetchClientKey(bridge); - - if (!ClientKeyData.clientKey) { - throw new Error('getClientKey Error: clientKey is empty'); - } - - const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0'); - const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' + - '&clientuin=' + bridge.identity.uin + - '&clientkey=' + ClientKeyData.clientKey + - '&u1=' + u1 + - '&keyindex=' + ClientKeyData.keyIndex; - - const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl); - const skey = cookies['skey']; - - if (!skey) { - throw new Error('SKey is Empty'); - } - - return skey; -} - -/** - * Standard QQ bkn hash (also known as token / csrf_token) derived from - * skey or p_skey. djb2 hash truncated to 31 bits. - */ -export function getBknFromSKey(skey: string): number { - let hash = 5381; - for (let i = 0; i < skey.length; i++) { - hash += (hash << 5) + skey.charCodeAt(i); - } - return hash & 2147483647; -} - -/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */ -export async function getCookiesStr(bridge: Bridge, domain: string): Promise { - const cookieObject = await getCookies(bridge, domain); - return Object.entries(cookieObject) - .map(([key, value]) => `${key}=${value}`) - .join('; '); -} - -/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */ -export async function getCsrfToken(bridge: Bridge): Promise { - const skey = await getSKey(bridge); - if (!skey) { - throw new Error('SKey is Empty'); - } - return getBknFromSKey(skey); -} - -/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */ -export async function getCredentials(bridge: Bridge, domain: string) { - const cookieObject = await getCookies(bridge, domain); - const cookiesStr = Object.entries(cookieObject) - .map(([key, value]) => `${key}=${value}`) - .join('; '); - - const skey = cookieObject['p_skey'] || cookieObject['skey'] || ''; - const token = skey ? getBknFromSKey(skey) : 0; - - return { - cookies: cookiesStr, - token: token, - csrf_token: token, - }; -} diff --git a/packages/core/src/bridge/web-actions/group-album.ts b/packages/core/src/bridge/web-actions/group-album.ts deleted file mode 100644 index 4f700605..00000000 --- a/packages/core/src/bridge/web-actions/group-album.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Group album actions via web API - -import type { Bridge } from '../bridge'; -import { getGroupAlbumList, uploadImageToGroupAlbum } from '../web/group-album'; -import { getCookies } from './cookies'; - -export async function getGroupAlbumListWeb(bridge: Bridge, groupId: number) { - const groupCode = groupId.toString(); - const uin = bridge.identity.uin; - const cookieObject = await getCookies(bridge, 'qzone.qq.com'); - - const albumData = await getGroupAlbumList(cookieObject, groupCode, uin); - - return albumData?.album || []; -} - -export async function uploadImageToGroupAlbumWeb( - bridge: Bridge, - groupId: number, - albumId: string, - albumName: string, - filePath: string -): Promise { - const groupCode = groupId.toString(); - const uin = bridge.identity.uin; - const cookieObject = await getCookies(bridge, 'qzone.qq.com'); - - await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin); -} diff --git a/packages/core/src/bridge/web-actions/group-essence.ts b/packages/core/src/bridge/web-actions/group-essence.ts deleted file mode 100644 index 55bb341c..00000000 --- a/packages/core/src/bridge/web-actions/group-essence.ts +++ /dev/null @@ -1,27 +0,0 @@ -// `get_essence_msg_list` — group essence (highlighted) messages. -// Two flavors: paginated (`getGroupEssence`) and the convenience -// fetch-everything (`getGroupEssenceAll`). - -import type { Bridge } from '../bridge'; -import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '../web/group-essence'; -import { getCookies } from './cookies'; - -/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */ -export async function getGroupEssence(bridge: Bridge, groupId: number, pageStart: number = 0, pageLimit: number = 50) { - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - - const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit); - - return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } }; -} - -/** Walks every page and returns the concatenated result. */ -export async function getGroupEssenceAll(bridge: Bridge, groupId: number) { - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - - const essenceDataAll = await getGroupEssenceMsgAll(cookieObject, groupCode); - - return essenceDataAll; -} diff --git a/packages/core/src/bridge/web-actions/group-honor.ts b/packages/core/src/bridge/web-actions/group-honor.ts deleted file mode 100644 index 6751c5c5..00000000 --- a/packages/core/src/bridge/web-actions/group-honor.ts +++ /dev/null @@ -1,45 +0,0 @@ -// `get_group_honor_info` — queries the per-group honor leaderboards -// (talkative / performer / legend / emotion / strong_newbie). -// Each honor type is a separate web call; ALL fetches all four -// non-newbie lists and folds them into one response. - -import type { Bridge } from '../bridge'; -import { getHonorListWebAPI, WebHonorType } from '../web/group-honor'; -import { getCookies } from './cookies'; - -export async function getGroupHonorInfo(bridge: Bridge, groupId: number, type: WebHonorType | string) { - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - - const honorInfo: any = { - group_id: groupId, - current_talkative: null, - talkative_list: [], - performer_list: [], - legend_list: [], - emotion_list: [], - strong_newbie_list: [], - }; - - if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) { - const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1); - if (talkativeList.length > 0) { - honorInfo.current_talkative = talkativeList[0]; - honorInfo.talkative_list = talkativeList; - } - } - - if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) { - honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2); - } - - if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) { - honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3); - } - - if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) { - honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6); - } - - return honorInfo; -} diff --git a/packages/core/src/bridge/web-actions/group-notice.ts b/packages/core/src/bridge/web-actions/group-notice.ts deleted file mode 100644 index d5a734ef..00000000 --- a/packages/core/src/bridge/web-actions/group-notice.ts +++ /dev/null @@ -1,118 +0,0 @@ -// Group notice (`群公告`) web actions: send / list / delete. -// `sendGroupNotice` can attach an optional image; when present it -// stages the bytes (HTTP URL or local file) and uploads via the -// notice-image endpoint before posting the notice itself. - -import type { Bridge } from '../bridge'; -import { - setGroupNoticeWebAPI, - getGroupNoticeWebAPI, - uploadGroupNoticeImage, - deleteGroupNotice, -} from '../web/group-notice'; -import { getCookies } from './cookies'; - -export async function sendGroupNotice( - bridge: Bridge, - groupId: number, - content: string, - options?: { - image?: string; // local path, http URL, or undefined (text-only) - pinned?: number; - type?: number; - confirm_required?: number; - }, -) { - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - - let picId = ''; - let imgWidth = 540; - let imgHeight = 300; - - if (options?.image) { - let imageBuffer: Buffer; - - if (options.image.startsWith('http://') || options.image.startsWith('https://')) { - const response = await fetch(options.image); - if (!response.ok) throw new Error(`Failed to download image: ${response.status}`); - imageBuffer = Buffer.from(await response.arrayBuffer()); - } else { - const { readFileSync } = await import('fs'); - imageBuffer = readFileSync(options.image); - } - - const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer); - if (picInfo) { - picId = picInfo.id; - imgWidth = picInfo.width; - imgHeight = picInfo.height; - } - } - - const ret = await setGroupNoticeWebAPI( - cookieObject, - groupCode, - content, - options?.pinned ?? 0, - options?.type ?? 1, - 1, - 1, - options?.confirm_required ?? 1, - picId, - imgWidth, - imgHeight, - ); - - if (!ret || ret.ec !== 0) { - throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`); - } - - return ret; -} - -export async function getGroupNotice(bridge: Bridge, groupId: number) { - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - - const ret = await getGroupNoticeWebAPI(cookieObject, groupCode); - if (!ret) { - throw new Error('获取公告失败'); - } - - const retNotices: any[] = []; - - if (ret.feeds) { - for (const key in ret.feeds) { - const feed = ret.feeds[key]; - if (!feed) continue; - - const image = feed.msg?.pics?.map((pic) => ({ - id: pic.id, - height: pic.h, - width: pic.w, - })) || []; - - retNotices.push({ - notice_id: feed.fid, - sender_id: feed.u, - publish_time: feed.pubt, - message: { - text: feed.msg?.text || '', - image: image, - images: image, - }, - settings: feed.settings, - read_num: feed.read_num, - }); - } - } - - return retNotices; -} - -export async function deleteGroupNoticeByFid(bridge: Bridge, groupId: number, fid: string): Promise { - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - return await deleteGroupNotice(cookieObject, groupCode, fid); -} diff --git a/packages/core/src/bridge/web-actions/index.ts b/packages/core/src/bridge/web-actions/index.ts deleted file mode 100644 index c7f834f8..00000000 --- a/packages/core/src/bridge/web-actions/index.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Barrel for the web-action themed split. `bridge.ts` imports -// everything from this directory as if it were a single file; the -// per-theme files keep the implementation discoverable. - -export { - forceFetchClientKey, - getPSkey, - getCookies, - getSKey, - getBknFromSKey, - getCookiesStr, - getCsrfToken, - getCredentials, -} from './cookies'; - -export { getGroupHonorInfo } from './group-honor'; - -export { - getGroupEssence, - getGroupEssenceAll, -} from './group-essence'; - -export { - sendGroupNotice, - getGroupNotice, - deleteGroupNoticeByFid, -} from './group-notice'; - -export { - getGroupAlbumListWeb, - uploadImageToGroupAlbumWeb, -} from './group-album'; diff --git a/packages/core/src/bridge/web/group-essence.ts b/packages/core/src/bridge/web/group-essence.ts deleted file mode 100644 index bf1710ce..00000000 --- a/packages/core/src/bridge/web/group-essence.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; -import { createLogger } from '../../utils/logger'; - -const log = createLogger('Bridge.Web'); - -// 定义接口返回类型 -export interface GroupEssenceMsgRet { - retcode: number; - data: { - is_end: boolean; - msg_list: any[]; // 具体结构视需要补充 - [key: string]: any; - }; - [key: string]: any; -} - - -/** - * 分页获取群精华消息 - */ -export async function getGroupEssenceMsg( - cookieObject: Record, - groupCode: string, - pageStart: number = 0, - pageLimit: number = 50 -): Promise { - const bkn = getBknFromCookie(cookieObject); - - const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({ - bkn: bkn, - page_start: pageStart.toString(), - page_limit: pageLimit.toString(), - group_code: groupCode, - }).toString()}`; - - try { - const ret = await RequestUtil.HttpGetJson( - url, - 'GET', - '', - { Cookie: cookieToString(cookieObject) } - ); - return ret.retcode === 0 ? ret : undefined; - } catch (e) { - log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s', - groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e)); - return undefined; - } -} - -/** - * 获取所有群精华消息 (最多循环 20 页) - */ -export async function getGroupEssenceMsgAll( - cookieObject: Record, - groupCode: string -): Promise { - const ret: GroupEssenceMsgRet[] = []; - - for (let i = 0; i < 20; i++) { - const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50); - - if (!data) break; - - ret.push(data); - - if (data.data?.is_end) break; - } - - return ret; -} \ No newline at end of file diff --git a/packages/core/src/bridge/web/group-honor.ts b/packages/core/src/bridge/web/group-honor.ts deleted file mode 100644 index c9162b09..00000000 --- a/packages/core/src/bridge/web/group-honor.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { RequestUtil, cookieToString } from './request-util'; -import { createLogger } from '../../utils/logger'; - -const log = createLogger('Bridge.Web'); - -export enum WebHonorType { - TALKATIVE = 'talkative', - PERFORMER = 'performer', - LEGEND = 'legend', - EMOTION = 'emotion', - ALL = 'all', -} - - -async function fetchHonorData(cookieObject: Record, groupCode: string, type: number) { - let resJson; - try { - const res = await RequestUtil.HttpGetText( - `https://qun.qq.com/interactive/honorlist?${new URLSearchParams({ - gc: groupCode, - type: type.toString(), - }).toString()}`, - 'GET', - '', - { Cookie: cookieToString(cookieObject) } - ); - const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res); - if (match?.[1]) { - resJson = JSON.parse(match[1].trim()); - } - return type === 1 ? resJson?.talkativeList : resJson?.actorList; - } catch (e) { - throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`); - } -} - -export async function getHonorListWebAPI(cookieObject: Record, groupCode: string, type: number) { - try { - const data = await fetchHonorData(cookieObject, groupCode, type); - if (!data) return []; - - return data.map((item: any) => ({ - user_id: item?.uin, - nickname: item?.name, - avatar: item?.avatar, - description: item?.desc, - })); - } catch (e) { - log.warn('getHonorListWebAPI failed (group=%s type=%d): %s', - groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e)); - return []; - } -} \ No newline at end of file diff --git a/packages/core/src/bridge/web/group-notice.ts b/packages/core/src/bridge/web/group-notice.ts deleted file mode 100644 index cbe98158..00000000 --- a/packages/core/src/bridge/web/group-notice.ts +++ /dev/null @@ -1,274 +0,0 @@ -import { RequestUtil, cookieToString } from './request-util'; -import https from 'node:https'; -import { createLogger } from '../../utils/logger'; - -const log = createLogger('Bridge.Web'); - -export interface SetNoticeRetSuccess { - ec?: number; - em?: string; - [key: string]: any; -} - -export interface UploadImageRetSuccess { - ec?: number; - id?: string; - [key: string]: any; -} - -export interface WebApiGroupNoticeFeed { - fid: string; - u: number; - pubt: number; - msg: { - text: string; - pics?: Array<{ id: string; w: number; h: number }>; - }; - settings: any; - read_num: number; - [key: string]: any; -} - -export interface WebApiGroupNoticeRet { - ec: number; - em?: string; - feeds?: Record; - [key: string]: any; -} - -export function calculateBkn(key: string): string { - let hash = 5381; - for (let i = 0; i < key.length; i++) { - const code = key.charCodeAt(i); - hash = hash + (hash << 5) + code; - } - return (hash & 0x7FFFFFFF).toString(); -} - -/** - * 发送群公告 Web API - */ -export async function setGroupNoticeWebAPI( - cookieObject: Record, - groupCode: string, - content: string, - pinned: number = 0, - type: number = 1, - isShowEditCard: number = 1, - tipWindowType: number = 1, - confirmRequired: number = 1, - picId: string = '', - imgWidth: number = 540, - imgHeight: number = 300 -): Promise { - try { - // 分别获取 skey 和 p_skey - const skey = cookieObject['skey'] || ''; - const pskey = cookieObject['p_skey'] || skey; - - const bodyBkn = calculateBkn(skey); - const urlBkn = calculateBkn(pskey); - // - // console.log(skey) - // console.log(pskey) - // - // console.log(urlBkn); - // console.log(bodyBkn) - - const settings = JSON.stringify({ - is_show_edit_card: isShowEditCard, - tip_window_type: tipWindowType, - confirm_required: confirmRequired, - }); - - const bodyParams: Record = { - qid: groupCode, - bkn: bodyBkn, - text: content, - pinned: pinned.toString(), - type: type.toString(), - settings, - }; - - if (picId !== '') { - bodyParams.pic = picId; - bodyParams.imgWidth = imgWidth.toString(); - bodyParams.imgHeight = imgHeight.toString(); - } - - // 注意这里:URL 必须使用 skey 算出来的 bkn - const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`; - const body = new URLSearchParams(bodyParams).toString(); - - const ret = await RequestUtil.HttpGetJson( - url, - 'POST', - body, - { - Cookie: cookieToString(cookieObject), - 'Content-Type': 'application/x-www-form-urlencoded' - }, - true, - false - ); - return ret; - } catch (e) { - log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); - return undefined; - } -} - -/** - * 获取群公告列表 Web API - */ -export async function getGroupNoticeWebAPI( - cookieObject: Record, - groupCode: string, - start: number = -1, // -1 表示第一页 - count: number = 20 // 抓包中是 10,你可以根据需要调整 -): Promise { - try { - const skey = cookieObject['skey'] || ''; - const pskey = cookieObject['p_skey'] || skey; - - const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn - const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn - - const bodyParams = new URLSearchParams({ - qid: groupCode, - bkn: bodyBkn, // Body 中传入 p_skey 计算结果 - ft: '23', - s: start.toString(), // 分页游标 - n: count.toString(), // 获取数量 - i: '1', - ni: '1' - }).toString(); - - const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`; - - const ret = await RequestUtil.HttpGetJson( - url, - 'POST', - bodyParams, - { - Cookie: cookieToString(cookieObject), - 'Content-Type': 'application/x-www-form-urlencoded', - 'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148' - }, - true, - false - ); - // console.log(JSON.stringify(ret, null, 2)); - return ret?.ec === 0 ? ret : undefined; - } catch (e) { - log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); - return undefined; - } -} -/** - * 上传群公告图片 Web API - */ -export async function uploadGroupNoticeImage( - cookieObject: Record, - imageBuffer: Buffer -): Promise<{ id: string; width: number; height: number } | undefined> { - try { - const bkn = calculateBkn(cookieObject['skey']); - const boundary = `-----------------------------${Date.now()}`; - - const parts: Buffer[] = []; - parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`)); - parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`)); - parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`)); - parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`)); - parts.push(imageBuffer); - parts.push(Buffer.from(`\r\n--${boundary}--\r\n`)); - - const body = Buffer.concat(parts); - - const url = 'https://web.qun.qq.com/cgi-bin/announce/upload_img'; - const options = { - hostname: 'web.qun.qq.com', - path: '/cgi-bin/announce/upload_img', - method: 'POST', - headers: { - 'Content-Type': `multipart/form-data; boundary=${boundary}`, - 'Content-Length': body.length, - 'Cookie': cookieToString(cookieObject), - }, - }; - - return new Promise((resolve, reject) => { - const req = https.request(options, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const result = JSON.parse(data) as UploadImageRetSuccess; - if (result.ec === 0 && result.id) { - const unescapedIdStr = result.id.replace(/"/g, '"'); - - const idObj = JSON.parse(unescapedIdStr); - resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) }); - } else { - resolve(undefined); - } - } catch { - resolve(undefined); - } - }); - }); - req.on('error', (err) => { - log.warn('uploadGroupNoticeImage transport error: %s', err.message); - resolve(undefined); - }); - req.write(body); - req.end(); - }); - } catch (e) { - log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); - return undefined; - } -} - -/** - * 删除群公告 Web API - */ -export async function deleteGroupNotice( - cookieObject: Record, - groupCode: string, - fid: string -): Promise { - try { - const skey = cookieObject['skey'] || ''; - const pskey = cookieObject['p_skey'] || skey; - - const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn - const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn - - const params = new URLSearchParams({ - bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn - fid: fid, - qid: groupCode, - }).toString(); - - // 注意这里:URL 拼接 urlBkn - const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`; - - const ret = await RequestUtil.HttpGetJson( - url, - 'POST', - params, - { - Cookie: cookieToString(cookieObject), - 'Content-Type': 'application/x-www-form-urlencoded' - }, - true, - false - ); - return ret?.ec === 0; - } catch (e) { - log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e)); - return false; - } -} \ No newline at end of file diff --git a/packages/core/src/bridge/web/request-util.ts b/packages/core/src/bridge/web/request-util.ts deleted file mode 100644 index 0c880a48..00000000 --- a/packages/core/src/bridge/web/request-util.ts +++ /dev/null @@ -1,127 +0,0 @@ -import https from 'node:https'; -import http from 'node:http'; - -export class RequestUtil { - static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> { - const client = url.startsWith('https') ? https : http; - return new Promise((resolve, reject) => { - const req = client.get(url, (res) => { - const cookies: { [key: string]: string; } = {}; - - res.on('data', () => { }); // 必须消耗流 - res.on('end', () => { - this.handleRedirect(res, url, cookies) - .then(resolve) - .catch(reject); - }); - - if (res.headers['set-cookie']) { - this.extractCookies(res.headers['set-cookie'], cookies); - } - }); - - req.on('error', (error: Error) => { - reject(error); - }); - }); - } - - private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> { - if (res.statusCode === 301 || res.statusCode === 302) { - if (res.headers.location) { - const redirectUrl = new URL(res.headers.location, url); - const redirectCookies = await this.HttpsGetCookies(redirectUrl.href); - return { ...cookies, ...redirectCookies }; - } - } - return cookies; - } - - private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) { - setCookieHeaders.forEach((cookie) => { - const parts = cookie.split(';')[0]?.split('='); - if (parts) { - const key = parts[0]; - const value = parts[1]; - if (key && value && key.length > 0 && value.length > 0) { - cookies[key] = value; - } - } - }); - } - - static async HttpGetJson(url: string, method: string = 'GET', data?: any, headers: { - [key: string]: string; - } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise { - const option = new URL(url); - const protocol = url.startsWith('https://') ? https : http; - const options = { - hostname: option.hostname, - port: option.port, - path: option.pathname + option.search, - method, - headers, - }; - - return new Promise((resolve, reject) => { - const req = protocol.request(options, (res: http.IncomingMessage) => { - if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) { - if (maxRedirects <= 0) { - reject(new Error('Too many redirects')); - return; - } - const redirectUrl = new URL(res.headers.location, url).href; - this.HttpGetJson(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1) - .then(resolve) - .catch(reject); - return; - } - - let responseBody = ''; - res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); }); - - res.on('end', () => { - try { - if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { - if (isJsonRet) { - resolve(JSON.parse(responseBody) as T); - } else { - resolve(responseBody as T); - } - } else { - reject(new Error(`Unexpected status code: ${res.statusCode}`)); - } - } catch (parseError: any) { - reject(new Error(parseError.message)); - } - }); - }); - - req.on('error', (error: Error) => reject(error)); - if (method === 'POST' || method === 'PUT' || method === 'PATCH') { - req.write(isArgJson ? JSON.stringify(data) : data); - } - req.end(); - }); - } - - static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) { - return this.HttpGetJson(url, method, data, headers, false, false); - } -} - -export function cookieToString(cookieObject: Record): string { - return Object.entries(cookieObject) - .map(([key, value]) => `${key}=${value}`) - .join('; '); -} - - -export function getBknFromCookie(cookieObject: Record): string { - const skey = cookieObject['p_skey'] || cookieObject['skey'] || ''; - let hash = 5381; - for (let i = 0; i < skey.length; i++) { - hash += (hash << 5) + skey.charCodeAt(i); - } - return (hash & 2147483647).toString(); -} diff --git a/packages/core/src/hook/hook-manager.ts b/packages/core/src/hook/hook-manager.ts index 18728c54..f5feed33 100644 --- a/packages/core/src/hook/hook-manager.ts +++ b/packages/core/src/hook/hook-manager.ts @@ -1,7 +1,7 @@ import fs from 'fs'; import type { BridgeManager } from '../bridge/manager'; -import type { PacketSink } from '../protocol/types'; -import { createLogger, type Logger } from '../utils/logger'; +import type { PacketSink } from '@snowluma/common/protocol-types'; +import { createLogger, type Logger } from '@snowluma/common/logger'; import { injectHookProcess, listHookProcesses, @@ -198,14 +198,25 @@ export class HookManager { const session = this.sessions.get(pid); if (session) session.onPipeDown(); }); - // After every tick, retry sessions that are stuck in 'connecting' - // while the pipe is up. Mirrors the original tickWatcher's per-tick - // reconcileConnect pass; onPipeUp is idempotent so calling it for an - // already-connected session is harmless. + // After every tick, retry sessions that are stuck in 'connecting' OR + // 'disconnected' while the pipe is up. Mirrors the original + // tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent + // so calling it for an already-connected session is harmless. + // + // The 'disconnected' branch matters on Windows: when the QQ-NT side of + // the named pipe stays alive but the SnowLuma-side socket dies (read + // EPIPE / idle-timeout / similar transient I/O fault), the watcher + // sees the pipe as still-live (the OS-level pipe is still listed by + // `listLivePipes`) so it never fires another `pipe-up`. Without + // retrying 'disconnected' sessions here the session is stranded + // forever — a real-world symptom users reported as "Windows running + // for a while then stops" with logs `pipe error: read EPIPE` → + // `session closed: UIN=…`. this.pipeWatcher.on('tick', () => { if (this.disposed) return; for (const session of this.sessions.values()) { - if (session.status === 'connecting' && this.pipeWatcher.isPipeLive(session.pid)) { + if ((session.status === 'connecting' || session.status === 'disconnected') + && this.pipeWatcher.isPipeLive(session.pid)) { session.onPipeUp(); } } diff --git a/packages/core/src/hook/hook-packet-client.ts b/packages/core/src/hook/hook-packet-client.ts index 30505eac..f2633737 100644 --- a/packages/core/src/hook/hook-packet-client.ts +++ b/packages/core/src/hook/hook-packet-client.ts @@ -1,4 +1,4 @@ -import type { PacketSender, SendPacketResult } from '../protocol/packet-sender'; +import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; import { QqHookClient, type QqHookSendReply } from './qq-hook-client'; export class HookPacketClient implements PacketSender { diff --git a/packages/core/src/hook/hook-session.ts b/packages/core/src/hook/hook-session.ts index d8c183ec..42f5645a 100644 --- a/packages/core/src/hook/hook-session.ts +++ b/packages/core/src/hook/hook-session.ts @@ -1,7 +1,6 @@ import { EventEmitter } from 'events'; -import type { PacketSender } from '../protocol/packet-sender'; -import type { PacketSink } from '../protocol/types'; -import { createLogger, type Logger } from '../utils/logger'; +import type { PacketSink } from '@snowluma/common/protocol-types'; +import { createLogger, type Logger } from '@snowluma/common/logger'; import { HookPacketClient } from './hook-packet-client'; import type { HookInjectResult } from './injector'; import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client'; diff --git a/packages/core/src/hook/pipe-watcher.ts b/packages/core/src/hook/pipe-watcher.ts index b69bb34e..59b87632 100644 --- a/packages/core/src/hook/pipe-watcher.ts +++ b/packages/core/src/hook/pipe-watcher.ts @@ -1,5 +1,5 @@ import { EventEmitter } from 'events'; -import { createLogger, type Logger } from '../utils/logger'; +import { createLogger, type Logger } from '@snowluma/common/logger'; import type { HookProcessBaseInfo } from './injector'; const DEFAULT_INTERVAL_MS = 1500; diff --git a/packages/core/src/hook/types.ts b/packages/core/src/hook/types.ts index 352b00bc..9fe03b0d 100644 --- a/packages/core/src/hook/types.ts +++ b/packages/core/src/hook/types.ts @@ -1,11 +1,5 @@ import type { HookProcessBaseInfo } from './injector'; -/** - * Lifecycle status of a single per-PID HookSession. - * - * Transitions live inside HookSession; this union only enumerates the - * states visible to API callers (WebUI, manager.listProcesses()). - */ export type HookProcessStatus = | 'available' | 'loading' diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 413024bc..d365a966 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,7 +1,7 @@ import { BridgeManager } from './bridge/manager'; -import { OneBotManager } from './onebot/manager'; -import { loadRuntimeConfig } from './common/runtime'; -import { closeLogger, createLogger } from './utils/logger'; +import { OneBotManager } from '@snowluma/onebot/manager'; +import { loadRuntimeConfig } from '@snowluma/common/runtime'; +import { closeLogger, createLogger } from '@snowluma/common/logger'; import { HookManager } from './hook/hook-manager'; const runtimeConfig = loadRuntimeConfig(); diff --git a/packages/core/src/protobuf/decode.ts b/packages/core/src/protobuf/decode.ts deleted file mode 100644 index 24a11f74..00000000 --- a/packages/core/src/protobuf/decode.ts +++ /dev/null @@ -1,241 +0,0 @@ -// Runtime schema-based protobuf decode/encode. -// TypeScript equivalent of the C++ proto_field DSL using plain schema objects. -// -// Usage: -// const MyMessageSchema = { -// fromUin: { field: 1, type: 'uint32' as const }, -// fromUid: { field: 2, type: 'string' as const }, -// grp: { field: 8, type: 'message' as const, schema: GrpSchema }, -// elements: { field: 2, type: 'repeated_message' as const, schema: ElemSchema }, -// }; -// type MyMessage = ProtoDecoded; -// const msg = protoDecode(rawBytes, MyMessageSchema); - -import { WireMessage, WireType, encodeVarint, encodeKey, decodeVarint } from './wire'; - -// --- Schema types --- - -export type FieldType = - | 'bool' | 'int32' | 'uint32' | 'int64' | 'uint64' - | 'string' | 'bytes' | 'message' - | 'repeated_varint' | 'repeated_uint32' | 'repeated_string' - | 'repeated_bytes' | 'repeated_message'; - -export interface FieldDef { - field: number; - type: FieldType; - schema?: ProtoSchema; // required for 'message' / 'repeated_message' -} - -export type ProtoSchema = { [key: string]: FieldDef }; - -// --- Decoded type inference --- - -type FieldTypeToTS = - T extends 'bool' ? boolean : - T extends 'int32' | 'uint32' ? number : - T extends 'int64' | 'uint64' ? bigint : - T extends 'string' ? string : - T extends 'bytes' ? Uint8Array : - T extends 'message' ? (S extends ProtoSchema ? ProtoDecoded : Record) : - T extends 'repeated_varint' | 'repeated_uint32' ? number[] : - T extends 'repeated_string' ? string[] : - T extends 'repeated_bytes' ? Uint8Array[] : - T extends 'repeated_message' ? (S extends ProtoSchema ? ProtoDecoded[] : Record[]) : - never; - -type IsRepeated = T extends `repeated_${string}` ? true : false; - -type FieldValue = - IsRepeated extends true - ? FieldTypeToTS - : FieldTypeToTS | undefined; - -export type ProtoDecoded = { - [K in keyof S]: FieldValue; -}; - -// --- Decode --- - -export function protoDecode( - data: Uint8Array | WireMessage, - schema: S -): ProtoDecoded | null { - const wire = data instanceof WireMessage ? data : WireMessage.decode(data); - if (!wire) return null; - - const result: Record = {}; - - for (const [key, def] of Object.entries(schema)) { - switch (def.type) { - case 'bool': { - const v = wire.getVarint(def.field); - if (v !== null) result[key] = v !== 0n; - break; - } - case 'int32': { - const v = wire.getInt32(def.field); - if (v !== null) result[key] = v; - break; - } - case 'uint32': { - const v = wire.getUint32(def.field); - if (v !== null) result[key] = v; - break; - } - case 'int64': { - const v = wire.getInt64(def.field); - if (v !== null) result[key] = v; - break; - } - case 'uint64': { - const v = wire.getUint64(def.field); - if (v !== null) result[key] = v; - break; - } - case 'string': { - const v = wire.getString(def.field); - if (v !== null) result[key] = v; - break; - } - case 'bytes': { - const v = wire.getBytes(def.field); - if (v !== null) result[key] = v; - break; - } - case 'message': { - const sub = wire.getMessage(def.field); - if (sub && def.schema) { - result[key] = protoDecode(sub, def.schema); - } - break; - } - case 'repeated_varint': { - const vals = wire.getRepeatedVarint(def.field); - result[key] = vals.map(v => Number(BigInt.asIntN(32, v))); - break; - } - case 'repeated_uint32': { - const vals = wire.getRepeatedVarint(def.field); - result[key] = vals.map(v => Number(BigInt.asUintN(32, v))); - break; - } - case 'repeated_string': { - result[key] = wire.getRepeatedString(def.field); - break; - } - case 'repeated_bytes': { - const flds = wire.fields(def.field); - result[key] = flds - .filter(f => f.wireType === WireType.LengthDelimited) - .map(f => f.bytes); - break; - } - case 'repeated_message': { - if (!def.schema) { result[key] = []; break; } - const msgs = wire.getRepeatedMessage(def.field); - result[key] = msgs - .map(m => protoDecode(m, def.schema!)) - .filter((m): m is NonNullable => m !== null); - break; - } - } - } - - return result as ProtoDecoded; -} - -// --- Encode --- - -export function protoEncode( - obj: Partial>, - schema: S -): Uint8Array { - const out: number[] = []; - const record = obj as Record; - - for (const [key, def] of Object.entries(schema)) { - const val = record[key]; - if (val === undefined || val === null) continue; - - switch (def.type) { - case 'bool': { - encodeKey(def.field, WireType.Varint, out); - encodeVarint(val ? 1 : 0, out); - break; - } - case 'int32': - case 'uint32': { - encodeKey(def.field, WireType.Varint, out); - encodeVarint(val as number, out); - break; - } - case 'int64': - case 'uint64': { - encodeKey(def.field, WireType.Varint, out); - encodeVarint(val as bigint, out); - break; - } - case 'string': { - const encoded = new TextEncoder().encode(val as string); - encodeKey(def.field, WireType.LengthDelimited, out); - encodeVarint(encoded.length, out); - for (const b of encoded) out.push(b); - break; - } - case 'bytes': { - const buf = val as Uint8Array; - encodeKey(def.field, WireType.LengthDelimited, out); - encodeVarint(buf.length, out); - for (const b of buf) out.push(b); - break; - } - case 'message': { - if (!def.schema) break; - const nested = protoEncode(val as any, def.schema); - encodeKey(def.field, WireType.LengthDelimited, out); - encodeVarint(nested.length, out); - for (const b of nested) out.push(b); - break; - } - case 'repeated_varint': - case 'repeated_uint32': { - for (const v of val as number[]) { - encodeKey(def.field, WireType.Varint, out); - encodeVarint(v, out); - } - break; - } - case 'repeated_string': { - const encoder = new TextEncoder(); - for (const s of val as string[]) { - const encoded = encoder.encode(s); - encodeKey(def.field, WireType.LengthDelimited, out); - encodeVarint(encoded.length, out); - for (const b of encoded) out.push(b); - } - break; - } - case 'repeated_bytes': { - for (const buf of val as Uint8Array[]) { - encodeKey(def.field, WireType.LengthDelimited, out); - encodeVarint(buf.length, out); - for (const b of buf) out.push(b); - } - break; - } - case 'repeated_message': { - if (!def.schema) break; - for (const item of val as any[]) { - const nested = protoEncode(item, def.schema); - encodeKey(def.field, WireType.LengthDelimited, out); - encodeVarint(nested.length, out); - for (const b of nested) out.push(b); - } - break; - } - } - } - - return new Uint8Array(out); -} diff --git a/packages/core/src/protobuf/wire.ts b/packages/core/src/protobuf/wire.ts deleted file mode 100644 index b708febe..00000000 --- a/packages/core/src/protobuf/wire.ts +++ /dev/null @@ -1,242 +0,0 @@ -// Protobuf wire-format decoder/encoder. -// Generic decoder that works without .proto schemas — decodes any protobuf -// binary into a field_number → value tree structure. -// Port of src/protobuf/wire.h + wire.cpp - -export enum WireType { - Varint = 0, - Fixed64 = 1, - LengthDelimited = 2, - Fixed32 = 5, -} - -export interface WireField { - fieldNumber: number; - wireType: WireType; - varint: bigint; // Varint, Fixed64, Fixed32 - bytes: Uint8Array; // LengthDelimited -} - -// --- Varint decode --- -export function decodeVarint(data: Uint8Array, offset: number): [bigint, number] | null { - let result = 0n; - for (let i = 0; i < 10 && offset + i < data.length; i++) { - result |= BigInt(data[offset + i] & 0x7f) << BigInt(7 * i); - if ((data[offset + i] & 0x80) === 0) { - return [result, i + 1]; - } - } - return null; -} - -// --- Varint encode --- -export function encodeVarint(value: bigint | number, out: number[]): void { - let v = typeof value === 'number' ? BigInt(value >>> 0) : value; - if (v < 0n) v = v + (1n << 64n); // treat as unsigned 64-bit - while (v >= 0x80n) { - out.push(Number(v & 0x7Fn) | 0x80); - v >>= 7n; - } - out.push(Number(v)); -} - -// --- Key encode --- -export function encodeKey(fieldNumber: number, wireType: WireType, out: number[]): void { - encodeVarint(BigInt(fieldNumber) << 3n | BigInt(wireType), out); -} - -// --- Field value helpers --- -export function fieldAsInt32(f: WireField): number { return Number(BigInt.asIntN(32, f.varint)); } -export function fieldAsUint32(f: WireField): number { return Number(BigInt.asUintN(32, f.varint)); } -export function fieldAsInt64(f: WireField): bigint { return BigInt.asIntN(64, f.varint); } -export function fieldAsUint64(f: WireField): bigint { return f.varint; } -export function fieldAsBool(f: WireField): boolean { return f.varint !== 0n; } -export function fieldAsString(f: WireField): string { - return new TextDecoder().decode(f.bytes); -} -export function fieldAsBytes(f: WireField): Uint8Array { - return f.bytes; -} - -export class WireMessage { - private fields_: WireField[]; - - private constructor(fields: WireField[]) { - this.fields_ = fields; - } - - static decode(data: Uint8Array): WireMessage | null { - if (!data || data.length === 0) return null; - - const fields: WireField[] = []; - let pos = 0; - - while (pos < data.length) { - const tagResult = decodeVarint(data, pos); - if (!tagResult) break; - const [tag, tagLen] = tagResult; - pos += tagLen; - - const fieldNum = Number(tag >> 3n); - const wireType = Number(tag & 0x07n) as WireType; - - if (fieldNum === 0) break; - - const field: WireField = { - fieldNumber: fieldNum, - wireType, - varint: 0n, - bytes: new Uint8Array(0), - }; - - switch (wireType) { - case WireType.Varint: { - const valResult = decodeVarint(data, pos); - if (!valResult) return null; - field.varint = valResult[0]; - pos += valResult[1]; - break; - } - case WireType.Fixed64: { - if (pos + 8 > data.length) return null; - const dv = new DataView(data.buffer, data.byteOffset + pos, 8); - field.varint = dv.getBigUint64(0, true); - pos += 8; - break; - } - case WireType.Fixed32: { - if (pos + 4 > data.length) return null; - const dv = new DataView(data.buffer, data.byteOffset + pos, 4); - field.varint = BigInt(dv.getUint32(0, true)); - pos += 4; - break; - } - case WireType.LengthDelimited: { - const lenResult = decodeVarint(data, pos); - if (!lenResult) return null; - const fieldLen = Number(lenResult[0]); - pos += lenResult[1]; - if (pos + fieldLen > data.length) return null; - field.bytes = data.subarray(pos, pos + fieldLen); - pos += fieldLen; - break; - } - default: - return null; - } - - fields.push(field); - } - - return new WireMessage(fields); - } - - // --- Single field access --- - - field(num: number): WireField | null { - for (const f of this.fields_) { - if (f.fieldNumber === num) return f; - } - return null; - } - - has(num: number): boolean { - return this.field(num) !== null; - } - - getVarint(num: number): bigint | null { - const f = this.field(num); - if (!f || f.wireType !== WireType.Varint) return null; - return f.varint; - } - - getInt32(num: number): number | null { - const v = this.getVarint(num); - return v !== null ? Number(BigInt.asIntN(32, v)) : null; - } - - getUint32(num: number): number | null { - const v = this.getVarint(num); - return v !== null ? Number(BigInt.asUintN(32, v)) : null; - } - - getInt64(num: number): bigint | null { - const v = this.getVarint(num); - return v !== null ? BigInt.asIntN(64, v) : null; - } - - getUint64(num: number): bigint | null { - return this.getVarint(num); - } - - getString(num: number): string | null { - const f = this.field(num); - if (!f || f.wireType !== WireType.LengthDelimited) return null; - return fieldAsString(f); - } - - getBytes(num: number): Uint8Array | null { - const f = this.field(num); - if (!f || f.wireType !== WireType.LengthDelimited) return null; - return f.bytes; - } - - getMessage(num: number): WireMessage | null { - const f = this.field(num); - if (!f || f.wireType !== WireType.LengthDelimited) return null; - return WireMessage.decode(f.bytes); - } - - // --- Repeated field access --- - - fields(num: number): WireField[] { - return this.fields_.filter(f => f.fieldNumber === num); - } - - getRepeatedVarint(num: number): bigint[] { - const result: bigint[] = []; - for (const f of this.fields_) { - if (f.fieldNumber !== num) continue; - if (f.wireType === WireType.Varint) { - result.push(f.varint); - } else if (f.wireType === WireType.LengthDelimited) { - // Packed repeated varint - let pos = 0; - while (pos < f.bytes.length) { - const r = decodeVarint(f.bytes, pos); - if (!r) break; - result.push(r[0]); - pos += r[1]; - } - } - } - return result; - } - - getRepeatedString(num: number): string[] { - const result: string[] = []; - const decoder = new TextDecoder(); - for (const f of this.fields_) { - if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) { - result.push(decoder.decode(f.bytes)); - } - } - return result; - } - - getRepeatedMessage(num: number): WireMessage[] { - const result: WireMessage[] = []; - for (const f of this.fields_) { - if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) { - const sub = WireMessage.decode(f.bytes); - if (sub) result.push(sub); - } - } - return result; - } - - // --- Raw iteration --- - - get allFields(): WireField[] { return this.fields_; } - get empty(): boolean { return this.fields_.length === 0; } -} diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index c8f6732e..f10bff81 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -1,7 +1,7 @@ +import { randomBytes, scryptSync, timingSafeEqual } from 'crypto'; import fs from 'fs'; import path from 'path'; -import { randomBytes, scryptSync, timingSafeEqual } from 'crypto'; -import { createLogger } from '../utils/logger'; +import { createLogger } from '@snowluma/common/logger'; const log = createLogger('WebUI.Auth'); @@ -13,11 +13,6 @@ const SCRYPT_N = 16384; // cost const SCRYPT_R = 8; const SCRYPT_P = 1; -/** - * Fixed credentials used when SNOWLUMA_DEV_MODE=1 is set. The state is kept - * entirely in memory and never written to `config/webui.json`, so toggling - * dev mode on/off never disturbs the real persisted password. - */ const DEV_PASSWORD = 'snowluma-dev'; export function isDevAuthMode(): boolean { @@ -27,9 +22,6 @@ export function isDevAuthMode(): boolean { function envBootstrapPassword(): string | null { const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; if (!raw || typeof raw !== 'string') return null; - // Minimum sanity: avoid accidental empty / 1-char seeds. Strength - // rules still don't apply because we want trusted launchers to be - // able to pick a high-entropy random secret (e.g. base64(16)). if (raw.length < 8) return null; return raw; } @@ -111,7 +103,6 @@ function atomicWrite(state: WebuiAuthState): void { ensureConfigDir(); const tmp = WEBUI_CONFIG_PATH + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 }); - // chmod again in case the file already existed with looser perms try { fs.chmodSync(tmp, 0o600); } catch { @@ -174,11 +165,6 @@ export class WebuiAuth { backupCorruptConfig(); } } - // SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD lets a trusted launcher seed the - // password on first run instead of having to scrape it from logs. - // Effect: write webui.json with the env-provided password, hashed, - // and mustChangePassword=false. Only honoured when there is NO existing - // webui.json — once persisted, password changes happen via the UI. const envPassword = envBootstrapPassword(); if (envPassword !== null) { const salt = randomBytes(16); @@ -235,10 +221,6 @@ export class WebuiAuth { } } - /** - * Update password atomically. Throws if the new password fails strength rules. - * After success, mustChangePassword=false and the file is rewritten on disk. - */ setPassword(newPassword: string): void { if (this.devMode) { throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改'); diff --git a/packages/core/src/webui/client-ip.ts b/packages/core/src/webui/client-ip.ts index a8765bc1..4251bc92 100644 --- a/packages/core/src/webui/client-ip.ts +++ b/packages/core/src/webui/client-ip.ts @@ -1,33 +1,5 @@ -// Resolve the request's "real" client IP for per-IP rate limiting. -// -// Threat model: -// - By default we ONLY trust the TCP socket peer. `X-Forwarded-For` and -// `X-Real-IP` are client-controllable, so honoring them lets any -// client rotate the header to escape the 5-attempts/15-min login -// lockout. -// - Operators who actually run behind a reverse proxy (nginx, Caddy, -// a SaaS CDN) need a way to opt back into the real client IP. The -// `SNOWLUMA_WEBUI_TRUST_PROXY` env var lets them say "when the -// immediate TCP peer is THIS, treat the headers as authoritative". -// -// Supported values for SNOWLUMA_WEBUI_TRUST_PROXY: -// - unset / empty — default; ignore headers, use socket peer -// - "loopback" — trust headers when the socket peer is 127.0.0.1 -// or ::1 (typical for nginx/Caddy on the same host) -// - "1" / "true" / — trust headers from any peer (only safe behind a -// "all" trusted SaaS CDN that strips client-set headers) -// - comma-separated — trust headers when the socket peer matches one -// IP list of these IPs (reverse proxy on another machine) -// -// When trusted, we prefer X-Real-IP (a single value the reverse proxy -// overwrites unconditionally) and fall back to the first hop of -// X-Forwarded-For. We never parse the FULL XFF chain — if the proxy -// chain isn't fully trusted, the leftmost value can still be spoofed -// by the original client, and a single-tier proxy is the only setup -// this app realistically sees. - -import type { Context } from 'hono'; import { getConnInfo } from '@hono/node-server/conninfo'; +import type { Context } from 'hono'; export type TrustProxyMode = | { kind: 'none' } @@ -69,12 +41,6 @@ function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean { } } -/** - * Pick the right "client IP" for rate-limit keying. - * - * Exposed as a pure function over a small dependency surface so the - * unit tests can fabricate request shapes without spinning up a server. - */ export function pickClientIp( c: Pick, mode: TrustProxyMode, diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 87cfa31d..03e19658 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -2,11 +2,11 @@ import { serve } from '@hono/node-server'; import { serveStatic } from '@hono/node-server/serve-static'; import { Hono, type Context } from 'hono'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; -import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '../utils/logger'; +import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; import { randomBytes } from 'crypto'; -import type { OneBotManager } from '../onebot/manager'; -import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config'; -import type { OneBotConfig } from '../onebot/types'; +import type { OneBotManager } from '@snowluma/onebot/manager'; +import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config'; +import type { OneBotConfig } from '@snowluma/onebot/types'; import type { HookManager, HookProcessInfo } from '../hook/hook-manager'; import path from 'path'; import { existsSync, readFileSync } from 'fs'; diff --git a/packages/core/tests/actions/_helpers.ts b/packages/core/tests/actions/_helpers.ts index 85c2d402..53b3b095 100644 --- a/packages/core/tests/actions/_helpers.ts +++ b/packages/core/tests/actions/_helpers.ts @@ -6,9 +6,115 @@ // // `mockBridge()` returns a minimal stand-in: enough state for the // actions to thread but no real packet/event machinery. +// +// As the #6 Api-on-ctx refactor moves business methods OFF Bridge and +// onto `bridge.apis..method()`, the mock grows an `apis` block +// matching the ApiHub shape. Each Api gets its own stub helper +// (e.g. `mockMessageApi()`) and tests can override individual entries +// via `mockBridge({ apis: { message: ... } })`. import { vi } from 'vitest'; -import type { SendPacketResult } from '../../src/protocol/packet-sender'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +/** Default receipt returned by sendGroup / sendPrivate / sendC2cFile mocks. */ +const STUB_RECEIPT = { messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 }; + +export interface MockMessageApi { + sendGroup: ReturnType; + sendPrivate: ReturnType; + sendC2cFile: ReturnType; + recallGroup: ReturnType; + recallPrivate: ReturnType; + markGroupRead: ReturnType; + markPrivateRead: ReturnType; +} + +export function mockMessageApi(): MockMessageApi { + return { + sendGroup: vi.fn(async () => STUB_RECEIPT), + sendPrivate: vi.fn(async () => STUB_RECEIPT), + sendC2cFile: vi.fn(async () => STUB_RECEIPT), + recallGroup: vi.fn(async () => undefined), + recallPrivate: vi.fn(async () => undefined), + markGroupRead: vi.fn(async () => undefined), + markPrivateRead: vi.fn(async () => undefined), + }; +} + +export interface MockContactsApi { + fetchFriendList: ReturnType; + fetchGroupList: ReturnType; + fetchGroupMemberList: ReturnType; + fetchUserProfile: ReturnType; + fetchGroupRequests: ReturnType; + fetchDownloadRKeys: ReturnType; +} + +export function mockContactsApi(): MockContactsApi { + return { + fetchFriendList: vi.fn(async () => []), + fetchGroupList: vi.fn(async () => []), + fetchGroupMemberList: vi.fn(async () => []), + fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })), + fetchGroupRequests: vi.fn(async () => []), + fetchDownloadRKeys: vi.fn(async () => []), + }; +} + +export interface MockGroupFileApi { + upload: ReturnType; + uploadPrivate: ReturnType; + publish: ReturnType; + getCount: ReturnType; + list: ReturnType; + getUrl: ReturnType; + getPrivateUrl: ReturnType; + getPttUrl: ReturnType; + getPrivatePttUrl: ReturnType; + getVideoUrl: ReturnType; + getPrivateVideoUrl: ReturnType; + delete: ReturnType; + move: ReturnType; + createFolder: ReturnType; + deleteFolder: ReturnType; + renameFolder: ReturnType; +} + +export function mockGroupFileApi(): MockGroupFileApi { + return { + upload: vi.fn(async () => ({ fileId: 'stub-fid' })), + uploadPrivate: vi.fn(async () => ({ fileId: 'stub-pfid', fileHash: 'stub-hash' })), + publish: vi.fn(async () => undefined), + getCount: vi.fn(async () => ({ fileCount: 0, maxCount: 10000 })), + list: vi.fn(async () => ({ files: [], folders: [] })), + getUrl: vi.fn(async () => 'stub://url'), + getPrivateUrl: vi.fn(async () => 'stub://private-url'), + getPttUrl: vi.fn(async () => 'stub://ptt-url'), + getPrivatePttUrl: vi.fn(async () => 'stub://private-ptt-url'), + getVideoUrl: vi.fn(async () => 'stub://video-url'), + getPrivateVideoUrl: vi.fn(async () => 'stub://private-video-url'), + delete: vi.fn(async () => undefined), + move: vi.fn(async () => undefined), + createFolder: vi.fn(async () => undefined), + deleteFolder: vi.fn(async () => undefined), + renameFolder: vi.fn(async () => undefined), + }; +} + +export interface MockApiHub { + message: MockMessageApi; + contacts: MockContactsApi; + groupFile: MockGroupFileApi; + // additional Apis added commit-by-commit as #6 progresses +} + +export function mockApiHub(overrides: Partial = {}): MockApiHub { + return { + message: overrides.message ?? mockMessageApi(), + contacts: overrides.contacts ?? mockContactsApi(), + groupFile: overrides.groupFile ?? mockGroupFileApi(), + }; +} export interface MockBridge { identity: { @@ -19,21 +125,14 @@ export interface MockBridge { findUinByUid: ReturnType; findGroupMember: ReturnType; }; + apis: MockApiHub; sendRawPacket: ReturnType; fetchFriendList: ReturnType; fetchGroupMemberList: ReturnType; fetchUserProfile: ReturnType; resolveUserUid: ReturnType; - // High-level message senders. Default to no-op resolves so actions - // that fire off a follow-up chat message after their main work - // (e.g. `upload_group_file` → `sendGroupFileMessage` to publish the - // file in chat) don't crash test setups that don't care about it. - sendGroupMessage: ReturnType; - sendPrivateMessage: ReturnType; - sendC2cFileMessage: ReturnType; - sendGroupFileMessage: ReturnType; - // Uploaded-file metadata cache helpers — actions like uploadGroupFile - // / uploadPrivateFile call these to remember the upload, so tests + // Uploaded-file metadata cache helpers — GroupFileApi.upload / + // uploadPrivate call these to remember the upload, so tests // covering those code paths get a default-no-op shim. rememberUploadedFile: ReturnType; recallUploadedFile: ReturnType; @@ -57,15 +156,12 @@ export function mockBridge(overrides: Partial = {}): MockBridge { findGroupMember: vi.fn(() => null), ...(overrides.identity ?? {}), } as MockBridge['identity'], + apis: overrides.apis ?? mockApiHub(), sendRawPacket: vi.fn(async () => defaultResp), fetchFriendList: vi.fn(async () => []), fetchGroupMemberList: vi.fn(async () => []), fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })), resolveUserUid: vi.fn(async () => 'resolved-uid'), - sendGroupMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), - sendPrivateMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), - sendC2cFileMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), - sendGroupFileMessage: vi.fn(async () => undefined), rememberUploadedFile: vi.fn(), recallUploadedFile: vi.fn(() => undefined), ...overrides, diff --git a/packages/core/tests/actions/extras.test.ts b/packages/core/tests/actions/extras.test.ts index 0278be45..66231fb8 100644 --- a/packages/core/tests/actions/extras.test.ts +++ b/packages/core/tests/actions/extras.test.ts @@ -1,21 +1,22 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbStrangerStatusResp, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { OidbAiVoiceListResp, OidbAiVoiceResp, -} from '../../src/bridge/proto/proton/oidb-action'; +} from '@snowluma/proto-defs/oidb-actions/media'; // `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers -// that the plugin substitutes at the call site with the inlined codec, so -// mocking them on the module object is a no-op. The only mockable point -// is `runOidb` (non-generic, untouched by proton) returning real bytes -// that the production-side codec then decodes. `makeOidbEnvelope` is a -// pure TS helper, so its mock works for introspection. -vi.mock('../../src/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '../../src/bridge/bridge-oidb', +// (substituted at the call site with the inlined codec). Mocking them on +// the module object is a no-op — proton has already inlined the call. +// We mock `runOidb` (non-generic) to return real proton-encoded bytes +// that the production-side codec actually decodes. +vi.mock('@snowluma/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '@snowluma/bridge/bridge-oidb', ); return { ...actual, @@ -24,23 +25,24 @@ vi.mock('../../src/bridge/bridge-oidb', async () => { }; }); -import * as oidb from '../../src/bridge/bridge-oidb'; -import * as extras from '../../src/bridge/actions/extras'; +import * as oidb from '@snowluma/bridge/bridge-oidb'; +import { ExtrasApi, AiVoiceChatType } from '../../src/bridge/apis/extras'; import { mockBridge } from './_helpers'; -describe('actions/extras / group todo (0xF90)', () => { +describe('apis/extras / group todo (0xF90)', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockClear(); vi.mocked(oidb.makeOidbEnvelope).mockClear(); }); it.each([ - ['setGroupTodo', extras.setGroupTodo, 'OidbSvcTrpcTcp.0xf90_1', 1], - ['completeGroupTodo', extras.completeGroupTodo, 'OidbSvcTrpcTcp.0xf90_2', 2], - ['cancelGroupTodo', extras.cancelGroupTodo, 'OidbSvcTrpcTcp.0xf90_3', 3], - ] as const)('%s dispatches the right subCmd with shared body', async (_name, fn, cmd, subCmd) => { + ['setGroupTodo', 'OidbSvcTrpcTcp.0xf90_1', 1] as const, + ['completeGroupTodo', 'OidbSvcTrpcTcp.0xf90_2', 2] as const, + ['cancelGroupTodo', 'OidbSvcTrpcTcp.0xf90_3', 3] as const, + ])('%s dispatches the right subCmd with shared body', async (method, cmd, subCmd) => { const bridge = mockBridge(); - await fn(bridge as any, 12345, 9876543210n); + const api = new ExtrasApi(bridge as any); + await (api as any)[method](12345, 9876543210n); const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(runCmd).toBe(cmd); const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; @@ -50,7 +52,7 @@ describe('actions/extras / group todo (0xF90)', () => { }); }); -describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { +describe('apis/extras / getStrangerStatus (0xFE1_2)', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); @@ -62,7 +64,7 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { data: { status: { value: 5n } } } }), ); - await extras.getStrangerStatus(bridge as any, 100200); + await new ExtrasApi(bridge as any).getStrangerStatus(100200); const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(runCmd).toBe('OidbSvcTrpcTcp.0xfe1_2'); const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; @@ -76,7 +78,7 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { data: { status: { value: 7n } } } }), ); - expect(await extras.getStrangerStatus(bridge as any, 1)).toEqual({ status: 70, ext_status: 0 }); + expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toEqual({ status: 70, ext_status: 0 }); }); it('high-band values decompose into the (0xff00 + (>>16 & 0xff)) status word', async () => { @@ -87,14 +89,14 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { data: { status: { value: 0x42F100n } } } }), ); - const status = await extras.getStrangerStatus(bridge as any, 1); + const status = await new ExtrasApi(bridge as any).getStrangerStatus(1); expect(status).toEqual({ status: 10, ext_status: 0xF142 }); }); it('returns null when the runner throws (transport error)', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockRejectedValueOnce(new Error('boom')); - expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull(); + expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull(); }); it('returns null when the server omits the status field', async () => { @@ -102,11 +104,11 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: {} }), ); - expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull(); + expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull(); }); }); -describe('actions/extras / AI voice (0x929D / 0x929B)', () => { +describe('apis/extras / AI voice (0x929D / 0x929B)', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); @@ -121,7 +123,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { content: fake } } as any), ); - const out = await extras.fetchAiVoiceList(bridge as any, 4242, extras.AiVoiceChatType.Sound); + const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(4242, AiVoiceChatType.Sound); expect(out).toEqual(fake); const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(runCmd).toBe('OidbSvcTrpcTcp.0x929d_0'); @@ -134,7 +136,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: {} }), ); - const out = await extras.fetchAiVoiceList(bridge as any, 1, 1 as any); + const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(1, 1); expect(out).toEqual([]); }); @@ -147,7 +149,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { .mockResolvedValueOnce(protobuf_encode>({ body: { statusCode: 2 } })) .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [] } } as any })) .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); - const out = await extras.fetchAiVoice(bridge as any, 100, 'voice-id', 'hi', extras.AiVoiceChatType.Sound); + const out = await new ExtrasApi(bridge as any).fetchAiVoice(100, 'voice-id', 'hi', AiVoiceChatType.Sound); expect(out).toMatchObject(node); expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; @@ -167,7 +169,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { vi.mocked(oidb.runOidb).mockResolvedValue( protobuf_encode>({ body: { statusCode: 1 } }), ); - await expect(extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any, 3)).rejects.toThrow( + await expect(new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1, 3)).rejects.toThrow( /AI voice synthesis did not complete/, ); expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); @@ -179,7 +181,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { vi.mocked(oidb.runOidb) .mockResolvedValueOnce(protobuf_encode>({ body: {} })) .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); - await extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any); + await new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1); const first = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any).session.sessionId; const second = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2] as any).session.sessionId; expect(first).toBe(second); diff --git a/packages/core/tests/actions/forward-file.test.ts b/packages/core/tests/actions/forward-file.test.ts index d63154e1..99320d3a 100644 --- a/packages/core/tests/actions/forward-file.test.ts +++ b/packages/core/tests/actions/forward-file.test.ts @@ -25,7 +25,7 @@ import { describe, it, expect, vi } from 'vitest'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ +vi.mock('@snowluma/bridge/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), @@ -40,17 +40,17 @@ vi.mock('../../src/bridge/bridge-oidb', () => ({ const { buildSendElemsMock } = vi.hoisted(() => ({ buildSendElemsMock: vi.fn(async (_elements: unknown[], _ctx?: Record) => []), })); -vi.mock('../../src/bridge/element-builder', () => ({ +vi.mock('@snowluma/bridge/element-builder', () => ({ buildSendElems: buildSendElemsMock, })); -import { protoEncode } from '../../src/protobuf/decode'; -import { SendLongMsgRespSchema } from '../../src/bridge/proto/longmsg'; -import * as forward from '../../src/bridge/actions/forward'; +import { protobuf_encode } from '@snowluma/proton'; +import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg'; +import { ForwardApi } from '../../src/bridge/apis/forward'; import { mockBridge } from './_helpers'; function uploadResponseWithResId(resId: string) { - const encoded = protoEncode({ result: { resId } }, SendLongMsgRespSchema); + const encoded = protobuf_encode({ result: { resId } }); return { success: true, gotResponse: true, @@ -70,7 +70,7 @@ describe('actions/forward — file segment inside forward node', () => { sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-grp-file')) as any, }); - await forward.uploadForwardNodes(bridge as any, [ + await new ForwardApi(bridge as any).upload([ { userUin: 10001, nickname: 'alice', @@ -100,7 +100,7 @@ describe('actions/forward — file segment inside forward node', () => { recallUploadedFile: vi.fn(() => undefined), }); - await forward.uploadForwardNodes(bridge as any, [ + await new ForwardApi(bridge as any).upload([ { userUin: 10001, nickname: 'alice', @@ -157,7 +157,7 @@ describe('actions/forward — file segment inside forward node', () => { recallUploadedFile, }); - await forward.uploadForwardNodes(bridge as any, [{ + await new ForwardApi(bridge as any).upload([{ userUin: 10001, nickname: 'alice', elements: [{ type: 'file', fileId: 'pfid-cached' } as any], diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index 8226118c..e354478b 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi } from 'vitest'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ +vi.mock('@snowluma/bridge/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), @@ -10,17 +10,17 @@ vi.mock('../../src/bridge/bridge-oidb', () => ({ // element-builder reaches into protoEncode with element-specific schemas // that we don't want to construct manually in tests; stub it to return // a benign placeholder. -vi.mock('../../src/bridge/element-builder', () => ({ +vi.mock('@snowluma/bridge/element-builder', () => ({ buildSendElems: vi.fn(async () => []), })); -import { protoEncode } from '../../src/protobuf/decode'; -import { SendLongMsgRespSchema } from '../../src/bridge/proto/longmsg'; -import * as forward from '../../src/bridge/actions/forward'; +import { protobuf_encode } from '@snowluma/proton'; +import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg'; +import { ForwardApi } from '../../src/bridge/apis/forward'; import { mockBridge } from './_helpers'; function uploadResponseWithResId(resId: string) { - const encoded = protoEncode({ result: { resId } }, SendLongMsgRespSchema); + const encoded = protobuf_encode({ result: { resId } }); return { success: true, gotResponse: true, @@ -33,7 +33,7 @@ function uploadResponseWithResId(resId: string) { describe('actions/forward', () => { it('uploadForwardNodes rejects empty arrays', async () => { const bridge = mockBridge(); - await expect(forward.uploadForwardNodes(bridge as any, [])) + await expect(new ForwardApi(bridge as any).upload([])) .rejects.toThrow(/required/); }); @@ -42,7 +42,7 @@ describe('actions/forward', () => { sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-001')) as any, }); - const resId = await forward.uploadForwardNodes(bridge as any, [ + const resId = await new ForwardApi(bridge as any).upload([ { userUin: 10001, nickname: 'alice', elements: [] }, ]); @@ -60,7 +60,7 @@ describe('actions/forward', () => { errorMessage: 'pipe broken', responseData: null, })) as any, }); - await expect(forward.uploadForwardNodes(bridge as any, [ + await expect(new ForwardApi(bridge as any).upload([ { userUin: 10001, nickname: 'a', elements: [] }, ])).rejects.toThrow(/pipe broken/); }); @@ -69,7 +69,7 @@ describe('actions/forward', () => { const bridge = mockBridge({ sendRawPacket: vi.fn(async () => uploadResponseWithResId('')) as any, }); - await expect(forward.uploadForwardNodes(bridge as any, [ + await expect(new ForwardApi(bridge as any).upload([ { userUin: 10001, nickname: 'a', elements: [] }, ])).rejects.toThrow(/missing res_id/); }); @@ -83,14 +83,14 @@ describe('actions/forward', () => { { userUin: 10002, nickname: 'bob', elements: [] }, ]; - const resId = await forward.uploadForwardNodes(bridge as any, nodes); + const resId = await new ForwardApi(bridge as any).upload(nodes); expect(resId).toBe('res-cache'); - const fetched = await forward.fetchForwardNodes(bridge as any, 'res-cache'); + const fetched = await new ForwardApi(bridge as any).fetch('res-cache'); // Same nicknames + uins; elements have been deep-copied so the shape // is preserved but the array reference is different. expect(fetched).toHaveLength(2); - expect(fetched.map(n => n.nickname)).toEqual(['alice', 'bob']); + expect(fetched.map((n: { nickname: string }) => n.nickname)).toEqual(['alice', 'bob']); expect(sendRawPacket).toHaveBeenCalledTimes(1); }); @@ -101,7 +101,7 @@ describe('actions/forward', () => { errorMessage: 'down', responseData: null, })) as any, }); - await expect(forward.fetchForwardNodes(bridge as any, 'cold-cache-miss')) + await expect(new ForwardApi(bridge as any).fetch('cold-cache-miss')) .rejects.toThrow(/download forward message failed|down/); }); @@ -117,7 +117,7 @@ describe('actions/forward', () => { const sendRawPacket = vi.fn(async () => uploadResponseWithResId(responses.shift()!)) as any; const bridge = mockBridge({ sendRawPacket }); - const resId = await forward.uploadForwardNodes(bridge as any, [ + const resId = await new ForwardApi(bridge as any).upload([ { userUin: 111, nickname: 'outer', @@ -142,7 +142,7 @@ describe('actions/forward', () => { const sendRawPacket = vi.fn(async () => uploadResponseWithResId('flat-res')) as any; const bridge = mockBridge({ sendRawPacket }); - const resId = await forward.uploadForwardNodes(bridge as any, [ + const resId = await new ForwardApi(bridge as any).upload([ { userUin: 10001, nickname: 'a', elements: [{ type: 'text', text: 'hello' }] }, { userUin: 10002, nickname: 'b', elements: [{ type: 'text', text: 'world' }] }, ]); diff --git a/packages/core/tests/actions/friend.test.ts b/packages/core/tests/actions/friend.test.ts index 919cd5ae..8f3b0d70 100644 --- a/packages/core/tests/actions/friend.test.ts +++ b/packages/core/tests/actions/friend.test.ts @@ -1,62 +1,62 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ +vi.mock('@snowluma/bridge/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), decodeOidbEnv: vi.fn(() => ({ body: {} })), })); -import * as oidb from '../../src/bridge/bridge-oidb'; -import * as friend from '../../src/bridge/actions/friend'; +import * as oidb from '@snowluma/bridge/bridge-oidb'; +import { FriendApi } from '../../src/bridge/apis/friend'; import { mockBridge } from './_helpers'; -describe('actions/friend', () => { +describe('apis/friend', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockClear(); vi.mocked(oidb.makeOidbEnvelope).mockClear(); - vi.mocked(oidb.encodeOidbEnv).mockClear(); - vi.mocked(oidb.decodeOidbEnv).mockClear(); }); - it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => { + it('handleRequest: numeric input is treated as UIN and resolved', async () => { const bridge = mockBridge(); - await friend.setFriendAddRequest(bridge as any, '10001', true); + await new FriendApi(bridge as any).handleRequest('10001', true); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' }); }); - it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => { + it('handleRequest: non-numeric flag is forwarded as-is', async () => { const bridge = mockBridge(); - await friend.setFriendAddRequest(bridge as any, 'flag-abc', false); + await new FriendApi(bridge as any).handleRequest('flag-abc', false); expect(bridge.resolveUserUid).not.toHaveBeenCalled(); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(body).toMatchObject({ accept: 5, targetUid: 'flag-abc' }); }); - it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => { + it('delete resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => { const bridge = mockBridge(); - await friend.deleteFriend(bridge as any, 10001, true); + await new FriendApi(bridge as any).delete(10001, true); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0x126b_0'); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect((body as any).field1.block).toBe(true); - expect(bridge.fetchFriendList).toHaveBeenCalled(); + expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalled(); }); - it('deleteFriend still succeeds when the friend-list refresh throws', async () => { - const bridge = mockBridge({ - fetchFriendList: vi.fn(async () => { throw new Error('cache miss'); }), - }); - await expect(friend.deleteFriend(bridge as any, 10001)) + it('delete still succeeds when the friend-list refresh throws', async () => { + const bridge = mockBridge(); + // `fetchFriendList` lives on `apis.contacts` post-#6 refactor; + // override the default no-op stub to make the friend-list refresh + // throw and verify delete swallows the error. + bridge.apis.contacts.fetchFriendList = vi.fn(async () => { throw new Error('cache miss'); }); + await expect(new FriendApi(bridge as any).delete(10001)) .resolves.toBeUndefined(); }); - it('setFriendRemark resolves UID and sends 0xb6e_2', async () => { + it('setRemark resolves UID and sends 0xb6e_2', async () => { const bridge = mockBridge(); - await friend.setFriendRemark(bridge as any, 10001, 'best-friend'); + await new FriendApi(bridge as any).setRemark(10001, 'best-friend'); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0xb6e_2'); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; diff --git a/packages/core/tests/actions/group-admin.test.ts b/packages/core/tests/actions/group-admin.test.ts index a7e0c5c7..fb49e146 100644 --- a/packages/core/tests/actions/group-admin.test.ts +++ b/packages/core/tests/actions/group-admin.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; -import type { Oidb0x8a7Resp } from '../../src/bridge/proto/proton/oidb-action'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x8a7Resp } from '@snowluma/proto-defs/oidb-actions/base'; // `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers // that the plugin substitutes at the call site with the inlined codec, so @@ -9,9 +9,9 @@ import type { Oidb0x8a7Resp } from '../../src/bridge/proto/proton/oidb-action'; // is `runOidb` (non-generic, untouched by proton) returning real bytes // that the production-side codec then decodes. `makeOidbEnvelope` is a // pure TS helper, so its mock works for introspection. -vi.mock('../../src/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '../../src/bridge/bridge-oidb', +vi.mock('@snowluma/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '@snowluma/bridge/bridge-oidb', ); return { ...actual, @@ -20,8 +20,8 @@ vi.mock('../../src/bridge/bridge-oidb', async () => { }; }); -import * as oidb from '../../src/bridge/bridge-oidb'; -import * as admin from '../../src/bridge/actions/group-admin'; +import * as oidb from '@snowluma/bridge/bridge-oidb'; +import { GroupAdminApi } from '../../src/bridge/apis/group-admin'; import { mockBridge } from './_helpers'; describe('actions/group-admin', () => { @@ -33,7 +33,7 @@ describe('actions/group-admin', () => { it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => { const bridge = mockBridge(); - await admin.muteGroupMember(bridge as any, 12345, 67890, 600); + await new GroupAdminApi(bridge as any).muteMember(12345, 67890, 600); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); expect(oidb.runOidb).toHaveBeenCalledOnce(); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; @@ -50,13 +50,13 @@ describe('actions/group-admin', () => { it('muteGroupAll flips the muteState flag based on enable', async () => { const bridge = mockBridge(); - await admin.muteGroupAll(bridge as any, 12345, true); + await new GroupAdminApi(bridge as any).muteAll(12345, true); expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF }, }); - await admin.muteGroupAll(bridge as any, 12345, false); + await new GroupAdminApi(bridge as any).muteAll(12345, false); expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2]).toMatchObject({ muteState: { state: 0 }, }); @@ -64,7 +64,7 @@ describe('actions/group-admin', () => { it('kickGroupMember resolves UID per-group and forwards reject + reason', async () => { const bridge = mockBridge(); - await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour'); + await new GroupAdminApi(bridge as any).kickMember(12345, 67890, true, 'bad behaviour'); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345, @@ -80,7 +80,7 @@ describe('actions/group-admin', () => { .mockResolvedValueOnce('uid-a') .mockResolvedValueOnce('uid-b'); - await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false); + await new GroupAdminApi(bridge as any).kickMembers(12345, [11, 22], false); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); const payload: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(payload.targetUids).toEqual(['uid-a', 'uid-b']); @@ -89,7 +89,7 @@ describe('actions/group-admin', () => { it('leaveGroup sends 0x1097_1 with the groupUin', async () => { const bridge = mockBridge(); - await admin.leaveGroup(bridge as any, 12345); + await new GroupAdminApi(bridge as any).leave(12345); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0x1097_1'); expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345 }); @@ -97,7 +97,7 @@ describe('actions/group-admin', () => { it('setGroupAdmin resolves UID and sends 0x1096_1', async () => { const bridge = mockBridge(); - await admin.setGroupAdmin(bridge as any, 12345, 67890, true); + await new GroupAdminApi(bridge as any).setAdmin(12345, 67890, true); expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345, uid: 'resolved-uid', isAdmin: true, }); @@ -105,12 +105,12 @@ describe('actions/group-admin', () => { it('setGroupCard / setGroupName / setGroupSpecialTitle / setGroupRemark / setGroupAddOption / setGroupSearch dispatch the right command', async () => { const bridge = mockBridge(); - await admin.setGroupCard(bridge as any, 1, 2, 'newCard'); - await admin.setGroupName(bridge as any, 1, 'newName'); - await admin.setGroupSpecialTitle(bridge as any, 1, 2, 'newTitle'); - await admin.setGroupRemark(bridge as any, 1, 'newRemark'); - await admin.setGroupAddOption(bridge as any, 1, 2); - await admin.setGroupSearch(bridge as any, 1); + await new GroupAdminApi(bridge as any).setCard(1, 2, 'newCard'); + await new GroupAdminApi(bridge as any).setName(1, 'newName'); + await new GroupAdminApi(bridge as any).setSpecialTitle(1, 2, 'newTitle'); + await new GroupAdminApi(bridge as any).setRemark(1, 'newRemark'); + await new GroupAdminApi(bridge as any).setAddOption(1, 2); + await new GroupAdminApi(bridge as any).setSearch(1); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]); expect(cmds).toEqual([ @@ -125,8 +125,8 @@ describe('actions/group-admin', () => { it('setGroupAddRequest picks _1 / _2 based on filtered flag', async () => { const bridge = mockBridge(); - await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, true, 'ok', false); - await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, false, 'no', true); + await new GroupAdminApi(bridge as any).setAddRequest(12345, 5, 1, true, 'ok', false); + await new GroupAdminApi(bridge as any).setAddRequest(12345, 5, 1, false, 'no', true); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]); expect(cmds).toEqual([ @@ -149,7 +149,7 @@ describe('actions/group-admin', () => { body: { canAtAll: true, groupRemain: 12, uinRemain: 5 } as any, }), ); - const out = await admin.getGroupAtAllRemain(bridge as any, 12345); + const out = await new GroupAdminApi(bridge as any).getAtAllRemain(12345); expect(out).toEqual({ can_at_all: true, remain_at_all_count_for_group: 12, @@ -164,6 +164,6 @@ describe('actions/group-admin', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({}), ); - await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/); + await expect(new GroupAdminApi(bridge as any).getAtAllRemain(12345)).rejects.toThrow(/empty/); }); }); diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 22394ae8..3250f35a 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -1,23 +1,25 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbGroupFileCountViewResp, OidbGroupFileResp, OidbGroupFileViewResp, - OidbPrivateFileUploadResp, OidbGroupFileFolderResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { + OidbPrivateFileUploadResp, NTV2RichMediaResp, -} from '../../src/bridge/proto/proton/oidb-action'; +} from '@snowluma/proto-defs/oidb-actions/media'; // `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers // (substituted at the call site with the inlined codec). Mocking them on // the module object is a no-op — proton has already inlined the call. // We mock `runOidb` (non-generic, proton leaves it alone) to return real // proton-encoded bytes, which the production-side codec then decodes. -vi.mock('../../src/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '../../src/bridge/bridge-oidb', +vi.mock('@snowluma/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '@snowluma/bridge/bridge-oidb', ); return { ...actual, @@ -26,12 +28,12 @@ vi.mock('../../src/bridge/bridge-oidb', async () => { }; }); -vi.mock('../../src/bridge/highway/highway-client', () => ({ +vi.mock('@snowluma/bridge/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({})), uploadHighwayHttp: vi.fn(async () => undefined), })); -vi.mock('../../src/bridge/highway/utils', () => ({ +vi.mock('@snowluma/bridge/highway/utils', () => ({ loadBinarySource: vi.fn(async (_src: string, fallback: string) => ({ bytes: new Uint8Array([1, 2, 3]), fileName: `${fallback}.bin`, @@ -41,9 +43,9 @@ vi.mock('../../src/bridge/highway/utils', () => ({ FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024, })); -import * as oidb from '../../src/bridge/bridge-oidb'; -import * as highwayClient from '../../src/bridge/highway/highway-client'; -import * as groupFile from '../../src/bridge/actions/group-file'; +import * as oidb from '@snowluma/bridge/bridge-oidb'; +import * as highwayClient from '@snowluma/bridge/highway'; +import { GroupFileApi } from '../../src/bridge/apis/group-file'; import { mockBridge } from './_helpers'; describe('actions/group-file', () => { @@ -55,27 +57,27 @@ describe('actions/group-file', () => { vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); }); - it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => { + it('getCount returns { fileCount, maxCount } from the OIDB response', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { count: { fileCount: 42, maxCount: 1000 } }, }), ); - const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); + const out = await new GroupFileApi(bridge as any).getCount(12345); expect(out).toEqual({ fileCount: 42, maxCount: 1000 }); }); - it('fetchGroupFileCount falls back to defaults on partial response', async () => { + it('getCount falls back to defaults on partial response', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { count: {} } }), ); - const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); + const out = await new GroupFileApi(bridge as any).getCount(12345); expect(out).toEqual({ fileCount: 0, maxCount: 10000 }); }); - it('uploadGroupFile skips highway when boolFileExist is true', async () => { + it('upload skips highway when boolFileExist is true', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ @@ -88,13 +90,16 @@ describe('actions/group-file', () => { } as any, }), ); - const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); + const api = new GroupFileApi(bridge as any); + // Suppress the auto-publish — that path is covered separately. + vi.spyOn(api, 'publish').mockResolvedValue(); + const out = await api.upload(12345, '/path/file.bin'); expect(out).toEqual({ fileId: 'fid-xyz' }); expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled(); expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled(); }); - it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => { + it('upload runs highway PUT when boolFileExist is false', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ @@ -111,90 +116,99 @@ describe('actions/group-file', () => { } as any, }), ); - await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); + const api = new GroupFileApi(bridge as any); + vi.spyOn(api, 'publish').mockResolvedValue(); + await api.upload(12345, '/path/file.bin'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); }); - it('uploadGroupFile throws on missing upload response', async () => { + it('upload throws on missing upload response', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: {} }), ); - await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) + await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin')) .rejects.toThrow(/response missing/); }); - it('uploadGroupFile bubbles up OIDB retCode errors', async () => { + it('upload bubbles up OIDB retCode errors', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { retCode: 999, retMsg: 'quota exceeded' } as any }, }), ); - await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) + await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin')) .rejects.toThrow(/code=999/); }); - it('uploadGroupFile publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => { + it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => { // Reproduces the bug report: OIDB upload + highway PUT alone only // stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB // call the file never appears in the chat. Earlier attempts used // PbSendMsg with a transElem(24) but the QQ-NT server rejects that // with result=79 (transElem(24) is a receive-side decoding shape, - // not a send-side one). Asserts that `bridge.sendGroupFileMessage` - // is invoked with the uploaded fileId. + // not a send-side one). Asserts that `this.publish` is invoked + // with the uploaded fileId. const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { fileId: 'fid-pub', boolFileExist: true } as any }, }), ); - await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt'); - expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce(); - const [groupId, fileId] = bridge.sendGroupFileMessage.mock.calls[0]!; + const api = new GroupFileApi(bridge as any); + const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue(); + await api.upload(12345, '/path/some-file.bin', 'mynote.txt'); + expect(publishSpy).toHaveBeenCalledOnce(); + const [groupId, fileId] = publishSpy.mock.calls[0]!; expect(groupId).toBe(12345); expect(fileId).toBe('fid-pub'); - // sendGroupMessage must NOT be touched — the previous wire shape + // sendGroup must NOT be touched — the previous wire shape // (PbSendMsg w/ transElem(24)) is the bug we're guarding against. - expect(bridge.sendGroupMessage).not.toHaveBeenCalled(); + expect(bridge.apis.message.sendGroup).not.toHaveBeenCalled(); }); - it('uploadGroupFile skips the chat post when uploadFile=false', async () => { + it('upload skips the chat post when uploadFile=false', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { fileId: 'fid-skip', boolFileExist: true } as any }, }), ); - await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false); - expect(bridge.sendGroupFileMessage).not.toHaveBeenCalled(); + const api = new GroupFileApi(bridge as any); + const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue(); + await api.upload(12345, '/path/file.bin', '', '/', false); + expect(publishSpy).not.toHaveBeenCalled(); }); - it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => { + it('upload returns success even when the chat post fails (file is still uploaded)', async () => { const bridge = mockBridge(); - vi.mocked(bridge.sendGroupFileMessage).mockRejectedValueOnce(new Error('message rejected')); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any }, }), ); - const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); + const api = new GroupFileApi(bridge as any); + const publishSpy = vi.spyOn(api, 'publish').mockRejectedValueOnce(new Error('message rejected')); + const out = await api.upload(12345, '/path/file.bin'); expect(out).toEqual({ fileId: 'fid-tolerant' }); - expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce(); + expect(publishSpy).toHaveBeenCalledOnce(); }); - it('uploadGroupFile caches the upload metadata for later resend by file_id', async () => { + it('upload caches the upload metadata for later resend by file_id', async () => { // After upload, a later `send_group_msg` carrying just the file_id // needs to recover the name/size/md5 from somewhere. Production - // populates `bridge.rememberUploadedFile` with the full tuple. + // populates `ctx.rememberUploadedFile` with the full tuple. const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { fileId: 'fid-cached', boolFileExist: true } as any }, }), ); - await groupFile.uploadGroupFile(bridge as any, 12345, '/path/x.bin', 'x.bin'); + const api = new GroupFileApi(bridge as any); + vi.spyOn(api, 'publish').mockResolvedValue(); + await api.upload(12345, '/path/x.bin', 'x.bin'); expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce(); const [meta] = bridge.rememberUploadedFile.mock.calls[0]!; expect(meta).toMatchObject({ @@ -205,13 +219,13 @@ describe('actions/group-file', () => { }); }); - it('sendGroupFileMessage hits OIDB 0x6d9_4 with the right body', async () => { + it('publish hits OIDB 0x6d9_4 with the right body', async () => { // Direct cover of the new bridge method. The previous send-shape // (PbSendMsg + transElem(24)) failed with result=79; this is the // Lagrange-V2-mirrored fix. const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce(new Uint8Array()); - await groupFile.sendGroupFileMessage(bridge as any, 12345, 'fid-publish'); + await new GroupFileApi(bridge as any).publish(12345, 'fid-publish'); expect(oidb.runOidb).toHaveBeenCalledOnce(); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0x6d9_4'); @@ -232,7 +246,7 @@ describe('actions/group-file', () => { ); }); - it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => { + it('uploadPrivate resolves both target + self UID before OIDB call', async () => { const bridge = mockBridge({ identity: { uin: '10001', @@ -251,17 +265,17 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'fid', fileAddon: 'hash', boolFileExist: true } as any }, }), ); - const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file'); + const out = await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file'); expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' }); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); }); - it('uploadPrivateFile publishes the file via sendC2cFileMessage after upload', async () => { + it('uploadPrivate publishes the file via apis.message.sendC2cFile after upload', async () => { // C2C files use `RichText.notOnlineFile` (not in the elems array), - // so `uploadPrivateFile` calls the dedicated `sendC2cFileMessage` - // path on the bridge rather than `sendPrivateMessage`. Same bug - // class as the group case — without this the recipient sees no - // message even though the bytes are on the server. + // so `uploadPrivate` calls the dedicated `sendC2cFile` path on + // the bridge rather than `sendPrivate`. Same bug class as the + // group case — without this the recipient sees no message even + // though the bytes are on the server. const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); vi.mocked(oidb.runOidb).mockResolvedValueOnce( @@ -269,21 +283,21 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/private-file.bin', 'doc.pdf'); - expect(bridge.sendC2cFileMessage).toHaveBeenCalledOnce(); - const [userUin, userUid, info] = bridge.sendC2cFileMessage.mock.calls[0]!; + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/private-file.bin', 'doc.pdf'); + expect(bridge.apis.message.sendC2cFile).toHaveBeenCalledOnce(); + const [userUin, userUid, info] = bridge.apis.message.sendC2cFile.mock.calls[0]!; expect(userUin).toBe(67890); expect(userUid).toBe('target-uid'); expect(info).toMatchObject({ fileId: 'pfid', fileName: 'doc.pdf', fileHash: 'phash' }); - expect(bridge.sendPrivateMessage).not.toHaveBeenCalled(); + expect(bridge.apis.message.sendPrivate).not.toHaveBeenCalled(); }); - it('uploadPrivateFile caches the upload metadata for later resend by file_id', async () => { + it('uploadPrivate caches the upload metadata for later resend by file_id', async () => { // C2C file resend (send_private_msg with just file_id) was the // "sends a 0 B file" bug: the wire packet needs fileSize/fileMd5/ // fileName/fileHash, but the OneBot caller only knows the file_id. // Caching the upload tuple lets the OneBot send-message path - // recover the rest via `bridge.recallUploadedFile(fileId)`. + // recover the rest via `ctx.recallUploadedFile(fileId)`. const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); vi.mocked(oidb.runOidb).mockResolvedValueOnce( @@ -291,7 +305,7 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'pfid-cache', fileAddon: 'addon-hash', boolFileExist: true } as any }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/cache-me.txt', 'cache-me.txt'); + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/cache-me.txt', 'cache-me.txt'); expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce(); const [meta] = bridge.rememberUploadedFile.mock.calls[0]!; expect(meta).toMatchObject({ @@ -303,7 +317,7 @@ describe('actions/group-file', () => { }); }); - it('uploadPrivateFile skips the chat post when uploadFile=false', async () => { + it('uploadPrivate skips the chat post when uploadFile=false', async () => { const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); vi.mocked(oidb.runOidb).mockResolvedValueOnce( @@ -311,11 +325,11 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file', '', false); - expect(bridge.sendC2cFileMessage).not.toHaveBeenCalled(); + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file', '', false); + expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled(); }); - it('uploadPrivateFile reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => { + it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => { // The 2026 QQ-NT server rollout moved the upload host out of the // legacy `uploadIp` (field 60) string into the new // `rtpMediaPlatformUploadAddress` (field 210, repeated IPv4 message). @@ -340,11 +354,11 @@ describe('actions/group-file', () => { }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin'); + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin'); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); }); - it('uploadPrivateFile falls back to uploadDomain when uploadIp is empty', async () => { + it('uploadPrivate falls back to uploadDomain when uploadIp is empty', async () => { // Regression: the server has been observed in the wild returning the // highway host in `uploadDomain` (field 70) instead of `uploadIp` // (field 60), causing "private file upload host is invalid". The @@ -369,11 +383,11 @@ describe('actions/group-file', () => { }, }), ); - await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin'); + await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin'); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); }); - it('uploadPrivateFile throws "host is invalid" only when every host field is empty', async () => { + it('uploadPrivate throws "host is invalid" only when every host field is empty', async () => { // The diagnostic warn-log lists every host slot to help users // report which one the server actually populated; this test just // asserts that the throw still fires when none of them carry a @@ -385,11 +399,11 @@ describe('actions/group-file', () => { body: { upload: { uuid: 'pfid', fileAddon: 'phash', uploadPort: 8080 } as any }, }), ); - await expect(groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin')) + await expect(new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin')) .rejects.toThrow(/upload host is invalid/); }); - it('fetchGroupFiles paginates files + folders out of OIDB items', async () => { + it('list paginates files + folders out of OIDB items', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ @@ -404,14 +418,14 @@ describe('actions/group-file', () => { }, }), ); - const out = await groupFile.fetchGroupFiles(bridge as any, 12345); + const out = await new GroupFileApi(bridge as any).list(12345); expect(out.files).toHaveLength(1); expect(out.files[0]).toMatchObject({ fileId: 'f1', fileName: 'a.txt', uploader: 1, uploaderName: 'alice' }); expect(out.folders).toHaveLength(1); expect(out.folders[0]).toMatchObject({ folderId: 'd1', folderName: 'dir', creator: 2, creatorName: 'bob' }); }); - it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => { + it('getUrl builds the https URL from downloadDns + hex-encoded path', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ @@ -423,44 +437,46 @@ describe('actions/group-file', () => { }, }), ); - const url = await groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'); + const url = await new GroupFileApi(bridge as any).getUrl(12345, 'fid-xyz'); expect(url).toBe('https://cdn.example.com/ftn_handler/0102/?fname=fid-xyz'); }); - it('fetchGroupFileUrl throws when response is missing dns or url', async () => { + it('getUrl throws when response is missing dns or url', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { download: {} as any }, }), ); - await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz')) + await expect(new GroupFileApi(bridge as any).getUrl(12345, 'fid-xyz')) .rejects.toThrow(/invalid/); }); - it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => { + it('delete / move dispatch the right sub-commands', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb) .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) .mockResolvedValueOnce(protobuf_encode>({ body: { move: {} as any } })); - await groupFile.deleteGroupFile(bridge as any, 12345, 'fid'); - await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b'); + const api = new GroupFileApi(bridge as any); + await api.delete(12345, 'fid'); + await api.move(12345, 'fid', '/a', '/b'); expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[1])).toEqual([3, 5]); }); - it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => { + it('createFolder / deleteFolder / renameFolder dispatch 0x6d7 family', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb) .mockResolvedValueOnce(protobuf_encode>({ body: { create: {} as any } })) .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) .mockResolvedValueOnce(protobuf_encode>({ body: { rename: {} as any } })); - await groupFile.createGroupFileFolder(bridge as any, 1, 'folder'); - await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid'); - await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname'); + const api = new GroupFileApi(bridge as any); + await api.createFolder(1, 'folder'); + await api.deleteFolder(1, 'fid'); + await api.renameFolder(1, 'fid', 'newname'); expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[0])).toEqual([0x6D7, 0x6D7, 0x6D7]); }); - it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => { + it('get*Url builds https://domain/path?rkey from the NTV2 response', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValue( protobuf_encode>({ @@ -473,7 +489,7 @@ describe('actions/group-file', () => { } as any, }), ); - const url = await groupFile.fetchGroupVideoUrlByNode(bridge as any, 12345, { fileUuid: 'uuid' }); + const url = await new GroupFileApi(bridge as any).getVideoUrl(12345, { fileUuid: 'uuid' }); expect(url).toBe('https://media.example.com/path/x?rkey=abc'); }); }); diff --git a/packages/core/tests/actions/group-message.test.ts b/packages/core/tests/actions/group-message.test.ts index 95281197..56ffcdcf 100644 --- a/packages/core/tests/actions/group-message.test.ts +++ b/packages/core/tests/actions/group-message.test.ts @@ -1,33 +1,35 @@ +// MessageApi recall + markRead coverage. (The send* paths live in their +// own test file because they need element-builder fixtures the recall +// paths don't.) Renamed from the legacy `actions/group-message` shape +// after #6 commit 1 moved the recall + markRead helpers onto MessageApi +// and #6 commit 6 absorbed setEssence into InteractionApi. + import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ +vi.mock('@snowluma/bridge/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), decodeOidbEnv: vi.fn(() => ({ body: {} })), })); -import * as oidb from '../../src/bridge/bridge-oidb'; -import * as msg from '../../src/bridge/actions/group-message'; +import { MessageApi } from '../../src/bridge/apis/message'; import { mockBridge } from './_helpers'; -describe('actions/group-message', () => { +describe('apis/message — recall + markRead', () => { beforeEach(() => { - vi.mocked(oidb.runOidb).mockClear(); - vi.mocked(oidb.makeOidbEnvelope).mockClear(); - vi.mocked(oidb.encodeOidbEnv).mockClear(); - vi.mocked(oidb.decodeOidbEnv).mockClear(); + // No global mock state to reset — sendRawPacket is per-bridge. }); - it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => { + it('recallGroup sends to SsoGroupRecallMsg with the group sequence', async () => { const bridge = mockBridge(); - await msg.recallGroupMessage(bridge as any, 12345, 999); + await new MessageApi(bridge as any).recallGroup(12345, 999); expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!; expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg'); }); - it('recallGroupMessage throws when sendRawPacket reports failure', async () => { + it('recallGroup throws when sendRawPacket reports failure', async () => { const bridge = mockBridge({ sendRawPacket: vi.fn(async () => ({ success: false, @@ -37,22 +39,23 @@ describe('actions/group-message', () => { responseData: null, })) as any, }); - await expect(msg.recallGroupMessage(bridge as any, 12345, 999)) + await expect(new MessageApi(bridge as any).recallGroup(12345, 999)) .rejects.toThrow(/network down/); }); - it('recallPrivateMessage resolves the target UID before dispatch', async () => { + it('recallPrivate resolves the target UID before dispatch', async () => { const bridge = mockBridge(); - await msg.recallPrivateMessage(bridge as any, 10001, 100, 200, 123, 1700000000); + await new MessageApi(bridge as any).recallPrivate(10001, 100, 200, 123, 1700000000); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!; expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg'); }); - it('markGroupMessageRead and markPrivateMessageRead both hit SsoReadedReport', async () => { + it('markGroupRead and markPrivateRead both hit SsoReadedReport', async () => { const bridge = mockBridge(); - await msg.markGroupMessageRead(bridge as any, 12345, 50); - await msg.markPrivateMessageRead(bridge as any, 10001, 60); + const api = new MessageApi(bridge as any); + await api.markGroupRead(12345, 50); + await api.markPrivateRead(10001, 60); expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2); const cmds = bridge.sendRawPacket.mock.calls.map((c: any) => c[0]); expect(cmds).toEqual([ @@ -60,12 +63,4 @@ describe('actions/group-message', () => { 'trpc.msg.msg_svc.MsgService.SsoReadedReport', ]); }); - - it('setGroupEssence picks _1 for enable and _2 for disable', async () => { - const bridge = mockBridge(); - await msg.setGroupEssence(bridge as any, 12345, 5, 7, true); - await msg.setGroupEssence(bridge as any, 12345, 5, 7, false); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]); - expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']); - }); }); diff --git a/packages/core/tests/actions/interaction.test.ts b/packages/core/tests/actions/interaction.test.ts index feace71a..7d5705b6 100644 --- a/packages/core/tests/actions/interaction.test.ts +++ b/packages/core/tests/actions/interaction.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; -import type { Oidb0x9083Resp } from '../../src/bridge/proto/proton/oidb-action'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x9083Resp } from '@snowluma/proto-defs/oidb-actions/base'; // `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers // that the plugin substitutes at the call site for the inlined codec. @@ -10,9 +10,9 @@ import type { Oidb0x9083Resp } from '../../src/bridge/proto/proton/oidb-action'; // is `runOidb` (non-generic, untouched by proton) returning real bytes // that the production-side codec actually decodes. `makeOidbEnvelope` is // a pure TS helper, so its mock works for introspection. -vi.mock('../../src/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '../../src/bridge/bridge-oidb', +vi.mock('@snowluma/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '@snowluma/bridge/bridge-oidb', ); return { ...actual, @@ -21,11 +21,11 @@ vi.mock('../../src/bridge/bridge-oidb', async () => { }; }); -import * as oidb from '../../src/bridge/bridge-oidb'; -import * as inter from '../../src/bridge/actions/interaction'; +import * as oidb from '@snowluma/bridge/bridge-oidb'; +import { InteractionApi } from '../../src/bridge/apis/interaction'; import { mockBridge } from './_helpers'; -describe('actions/interaction', () => { +describe('apis/interaction', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); @@ -34,35 +34,45 @@ describe('actions/interaction', () => { it('sendPoke group: groupUin set, friendUin=0', async () => { const bridge = mockBridge(); - await inter.sendPoke(bridge as any, true, 12345, 67890); + await new InteractionApi(bridge as any).sendPoke(true, 12345, 67890); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(body).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 }); }); it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => { const bridge = mockBridge(); - await inter.sendPoke(bridge as any, false, 67890); + await new InteractionApi(bridge as any).sendPoke(false, 67890); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(body).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 }); }); it('sendLike forwards target + count to 0x7e5_104', async () => { const bridge = mockBridge(); - await inter.sendLike(bridge as any, 10001, 3); + await new InteractionApi(bridge as any).sendLike(10001, 3); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0x7e5_104'); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(body).toMatchObject({ targetUin: 10001, count: 3 }); }); - it('setGroupReaction picks _1 for set and _2 for unset', async () => { + it('setReaction picks _1 for set and _2 for unset', async () => { const bridge = mockBridge(); - await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true); - await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false); + const api = new InteractionApi(bridge as any); + await api.setReaction(12345, 99, '128516', true); + await api.setReaction(12345, 99, '128516', false); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]); expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']); }); + it('setEssence picks _1 for enable and _2 for disable', async () => { + const bridge = mockBridge(); + const api = new InteractionApi(bridge as any); + await api.setEssence(12345, 99, 0, true); + await api.setEssence(12345, 99, 0, false); + const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]); + expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']); + }); + it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( @@ -73,7 +83,7 @@ describe('actions/interaction', () => { } as any, }), ); - const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516'); + const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516'); expect(out.users).toEqual([{ uin: 10001 }]); expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64')); expect(out.isLast).toBe(false); @@ -84,7 +94,7 @@ describe('actions/interaction', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: {} }), ); - const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516'); + const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516'); expect(out.users).toEqual([]); expect(out.isLast).toBe(true); }); diff --git a/packages/core/tests/actions/misc.test.ts b/packages/core/tests/actions/misc.test.ts index 09efd6e2..0c95a387 100644 --- a/packages/core/tests/actions/misc.test.ts +++ b/packages/core/tests/actions/misc.test.ts @@ -1,19 +1,19 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { Oidb0x990Resp, Oidb0x112eResp, -} from '../../src/bridge/proto/proton/oidb-action'; +} from '@snowluma/proto-defs/oidb-actions/base'; // `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers // — the plugin substitutes them at the call site with the inlined codec, // so mocking them on the module object is a no-op. We mock `runOidb` // (non-generic, untouched by proton) to return real proton-encoded bytes // that the production-side codec then actually decodes. -vi.mock('../../src/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '../../src/bridge/bridge-oidb', +vi.mock('@snowluma/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '@snowluma/bridge/bridge-oidb', ); return { ...actual, @@ -22,11 +22,11 @@ vi.mock('../../src/bridge/bridge-oidb', async () => { }; }); -import * as oidb from '../../src/bridge/bridge-oidb'; -import * as misc from '../../src/bridge/actions/misc'; +import * as oidb from '@snowluma/bridge/bridge-oidb'; +import { MiscApi } from '../../src/bridge/apis/misc'; import { mockBridge } from './_helpers'; -describe('actions/misc', () => { +describe('apis/misc', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); @@ -40,7 +40,7 @@ describe('actions/misc', () => { body: { translateResp: { dstWords: ['你好', '世界'] } } as any, }), ); - const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']); + const out = await new MiscApi(bridge as any).translateEn2Zh( ['hello', 'world']); expect(out).toEqual(['你好', '世界']); }); @@ -49,14 +49,14 @@ describe('actions/misc', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: {} }), ); - await expect(misc.translateEn2Zh(bridge as any, ['hello'])) + await expect(new MiscApi(bridge as any).translateEn2Zh( ['hello'])) .rejects.toThrow(/empty/); }); it('getMiniAppArk rejects unsupported types', async () => { const bridge = mockBridge(); await expect( - misc.getMiniAppArk(bridge as any, 'youtube', 't', 'd', 'p', 'u'), + new MiscApi(bridge as any).getMiniAppArk( 'youtube', 't', 'd', 'p', 'u'), ).rejects.toThrow(/unsupported type/); }); @@ -75,7 +75,7 @@ describe('actions/misc', () => { }); // With null responseData, the action should throw on decode — that // still proves the right serviceCmd was used. - await expect(misc.getMiniAppArk(bridge as any, 'bili', 't', 'd', 'p', 'u')).rejects.toThrow(); + await expect(new MiscApi(bridge as any).getMiniAppArk( 'bili', 't', 'd', 'p', 'u')).rejects.toThrow(); expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); expect(bridge.sendRawPacket.mock.calls[0]![0]) .toBe('LightAppSvc.mini_app_share.AdaptShareInfo'); @@ -88,13 +88,13 @@ describe('actions/misc', () => { body: { result: 1, errMsg: 'ok', promptText: 'hi' } as any, }), ); - const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100); + const out = await new MiscApi(bridge as any).clickInlineKeyboardButton( 1, 2, 'btn', 'data', 100); expect(out).toMatchObject({ result: 1, errMsg: 'ok', promptText: 'hi', status: 0 }); }); it('sendGroupSign dispatches to 0xEB7_1', async () => { const bridge = mockBridge(); - await misc.sendGroupSign(bridge as any, 12345); + await new MiscApi(bridge as any).sendGroupSign( 12345); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0xEB7_1'); }); diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index 6ec45f46..2d0a9c64 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -1,19 +1,22 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { + GroupAvatarExtra, Oidb0x7edResp, Oidb0xe17Resp, -} from '../../src/bridge/proto/proton/oidb-action'; + SetStatusReq, + SetStatusResp, +} from '@snowluma/proto-defs/oidb-actions/base'; // `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers // (substituted at the call site with the inlined codec). Mocking them on // the module object is a no-op — proton has already inlined the call. // We mock `runOidb` (non-generic) to return real proton-encoded bytes // that the production-side codec actually decodes. -vi.mock('../../src/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '../../src/bridge/bridge-oidb', +vi.mock('@snowluma/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '@snowluma/bridge/bridge-oidb', ); return { ...actual, @@ -22,23 +25,23 @@ vi.mock('../../src/bridge/bridge-oidb', async () => { }; }); -vi.mock('../../src/bridge/highway/highway-client', () => ({ +vi.mock('@snowluma/bridge/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({})), uploadHighwayHttp: vi.fn(async () => undefined), })); -vi.mock('../../src/bridge/highway/utils', () => ({ +vi.mock('@snowluma/bridge/highway/utils', () => ({ loadBinarySource: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), fileName: 'avatar.bin' })), computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })), computeMd5: vi.fn(() => new Uint8Array(16)), })); -import * as oidb from '../../src/bridge/bridge-oidb'; -import * as highwayClient from '../../src/bridge/highway/highway-client'; -import * as profile from '../../src/bridge/actions/profile'; +import * as oidb from '@snowluma/bridge/bridge-oidb'; +import * as highwayClient from '@snowluma/bridge/highway'; +import { ProfileApi } from '../../src/bridge/apis/profile'; import { mockBridge } from './_helpers'; -describe('actions/profile', () => { +describe('apis/profile', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); @@ -49,14 +52,14 @@ describe('actions/profile', () => { it('setOnlineStatus sends to status_svc.SetStatus and accepts an empty response', async () => { const bridge = mockBridge(); - await profile.setOnlineStatus(bridge as any, 11, 0, 100); + await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100); const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!; expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus'); }); it('setOnlineStatus does NOT include the customExt field 4 (varint 0x22 absent in body)', async () => { const bridge = mockBridge(); - await profile.setOnlineStatus(bridge as any, 11, 0, 100); + await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100); const [, body] = bridge.sendRawPacket.mock.calls[0]!; // proto field 4 length-delimited tag = (4 << 3) | 2 = 0x22. The // body should not contain that byte; if encoder ever leaks an @@ -66,32 +69,28 @@ describe('actions/profile', () => { it('setDiyOnlineStatus hardcodes status=10 / extStatus=2000 and packs faceId+wording+faceType into customExt', async () => { const bridge = mockBridge(); - await profile.setDiyOnlineStatus(bridge as any, 1234, '摸鱼中', 2); + await new ProfileApi(bridge as any).setDiyOnlineStatus( 1234, '摸鱼中', 2); const [serviceCmd, body] = bridge.sendRawPacket.mock.calls[0]!; expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus'); // Decode the wire bytes back through the same schema to assert // every field landed in the right place. - const { protoDecode } = await import('../../src/protobuf/decode'); - const { SetStatusReqSchema } = await import('../../src/bridge/proto/oidb-action'); - const decoded = protoDecode(body as Uint8Array, SetStatusReqSchema); + const decoded = protobuf_decode(body as Uint8Array); expect(decoded).toMatchObject({ status: 10, extStatus: 2000, - batteryStatus: 0, customExt: { faceId: 1234, text: '摸鱼中', faceType: 2 }, }); + expect(decoded.batteryStatus ?? 0).toBe(0); }); it('setDiyOnlineStatus surfaces server errors via the same path as setOnlineStatus', async () => { const bridge = mockBridge(); // Build a response that decodes to errCode != 0. - const { protoEncode } = await import('../../src/protobuf/decode'); - const { SetStatusRespSchema } = await import('../../src/bridge/proto/oidb-action'); - const respBuf = Buffer.from(protoEncode({ errCode: 1, errMsg: 'denied' }, SetStatusRespSchema)); + const respBuf = Buffer.from(protobuf_encode({ errCode: 1, errMsg: 'denied' })); bridge.sendRawPacket.mockResolvedValueOnce({ success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf, } as any); - await expect(profile.setDiyOnlineStatus(bridge as any, 1, 't', 1)).rejects.toThrow(/denied/); + await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/denied/); }); it('setDiyOnlineStatus rejects when the transport itself fails', async () => { @@ -99,18 +98,18 @@ describe('actions/profile', () => { bridge.sendRawPacket.mockResolvedValueOnce({ success: false, gotResponse: false, errorCode: -1, errorMessage: 'pipe closed', responseData: null, } as any); - await expect(profile.setDiyOnlineStatus(bridge as any, 1, 't', 1)).rejects.toThrow(/pipe closed/); + await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/pipe closed/); }); it('setProfile is a no-op when both arguments are undefined', async () => { const bridge = mockBridge(); - await profile.setProfile(bridge as any); + await new ProfileApi(bridge as any).setProfile(); expect(oidb.runOidb).not.toHaveBeenCalled(); }); it('setProfile only sends non-undefined fields', async () => { const bridge = mockBridge(); - await profile.setProfile(bridge as any, 'New Nick'); + await new ProfileApi(bridge as any).setProfile('New Nick'); expect(oidb.runOidb).toHaveBeenCalledOnce(); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect((body as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); @@ -118,14 +117,14 @@ describe('actions/profile', () => { it('setSelfLongNick wraps the long nick in profile tag 102', async () => { const bridge = mockBridge(); - await profile.setSelfLongNick(bridge as any, 'hello world'); + await new ProfileApi(bridge as any).setSelfLongNick( 'hello world'); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect((body as any).profile).toEqual({ tag: 102, value: 'hello world' }); }); it('setInputStatus resolves UID first and sends 0xcd4_1', async () => { const bridge = mockBridge(); - await profile.setInputStatus(bridge as any, 10001, 1); + await new ProfileApi(bridge as any).setInputStatus( 10001, 1); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0xcd4_1'); @@ -133,7 +132,7 @@ describe('actions/profile', () => { it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => { const bridge = mockBridge(); - await profile.setAvatar(bridge as any, '/some/avatar.png'); + await new ProfileApi(bridge as any).setAvatar( '/some/avatar.png'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!; @@ -143,16 +142,14 @@ describe('actions/profile', () => { it('setGroupAvatar uses cmdId 3000 and packs the Lagrange GroupAvatarExtra constants', async () => { const bridge = mockBridge(); - await profile.setGroupAvatar(bridge as any, 12345, '/some/group-avatar.png'); + await new ProfileApi(bridge as any).setGroupAvatar( 12345, '/some/group-avatar.png'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!; expect(cmdId).toBe(3000); // Decode the extra blob back through the schema and assert every // protocol-prescribed constant lands where it should. - const { protoDecode } = await import('../../src/protobuf/decode'); - const { GroupAvatarExtraSchema } = await import('../../src/bridge/proto/oidb-action'); - const decoded = protoDecode(extend as Uint8Array, GroupAvatarExtraSchema); + const decoded = protobuf_decode(extend as Uint8Array); expect(decoded).toEqual({ type: 101, groupUin: 12345, @@ -164,11 +161,11 @@ describe('actions/profile', () => { it('setGroupAvatar rejects an empty file before hitting highway', async () => { const bridge = mockBridge(); - const { loadBinarySource } = await import('../../src/bridge/highway/utils'); + const { loadBinarySource } = await import('@snowluma/bridge/highway/utils'); vi.mocked(loadBinarySource).mockResolvedValueOnce({ bytes: new Uint8Array(0), fileName: 'empty.png', } as any); - await expect(profile.setGroupAvatar(bridge as any, 1, 'empty.png')).rejects.toThrow(/empty/); + await expect(new ProfileApi(bridge as any).setGroupAvatar( 1, 'empty.png')).rejects.toThrow(/empty/); expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled(); }); @@ -186,7 +183,7 @@ describe('actions/profile', () => { } as any, }), ); - const out = await profile.getProfileLike(bridge as any); + const out = await new ProfileApi(bridge as any).getLike(); expect(out.favoriteInfo.total_count).toBe(5); expect(out.voteInfo.total_count).toBe(7); }); @@ -196,7 +193,7 @@ describe('actions/profile', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { userLikeInfos: [] } as any }), ); - await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/); + await expect(new ProfileApi(bridge as any).getLike()).rejects.toThrow(/empty/); }); it('getUnidirectionalFriendList parses the embedded JSON body', async () => { @@ -206,7 +203,7 @@ describe('actions/profile', () => { body: { jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }) } as any, }), ); - const out = await profile.getUnidirectionalFriendList(bridge as any); + const out = await new ProfileApi(bridge as any).getUnidirectionalFriendList(); expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]); }); }); diff --git a/packages/core/tests/bridge-event-bus.test.ts b/packages/core/tests/bridge-event-bus.test.ts index 576bb40a..4a441ea7 100644 --- a/packages/core/tests/bridge-event-bus.test.ts +++ b/packages/core/tests/bridge-event-bus.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; -import { BridgeEventBus } from '../src/bridge/event-bus'; -import type { FriendMessage, GroupMessage } from '../src/bridge/events'; +import { BridgeEventBus } from '@snowluma/bridge/event-bus'; +import type { FriendMessage, GroupMessage } from '@snowluma/bridge/events'; function makeFriendMessage(): FriendMessage { return { diff --git a/packages/core/tests/bridge-member-identity.test.ts b/packages/core/tests/bridge-member-identity.test.ts index 6e62f84e..720bb99c 100644 --- a/packages/core/tests/bridge-member-identity.test.ts +++ b/packages/core/tests/bridge-member-identity.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest'; import { Bridge } from '../src/bridge/bridge'; -import { IdentityService } from '../src/bridge/identity-service'; -import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info'; -import type { GroupMemberJoin, QQEventVariant } from '../src/bridge/events'; -import type { PacketInfo } from '../src/protocol/types'; +import { IdentityService } from '@snowluma/bridge/identity-service'; +import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/bridge/qq-info'; +import type { GroupMemberJoin, QQEventVariant } from '@snowluma/bridge/events'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; const SELF_UIN = '10001'; const GROUP_ID = 123456789; @@ -39,14 +39,22 @@ class RefreshingBridge extends Bridge { constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) { super(identity); - } - - override async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise { - this.memberFetches.push({ groupId, force: Boolean(options.force) }); - for (const member of this.refreshedMembers) { - this.identity.updateGroupMember(groupId, member); - } - return this.refreshedMembers; + // `fetchGroupMemberList` moved from Bridge onto `apis.contacts` + // under the #6 refactor — patch the method on the constructed + // ContactsApi instance to intercept calls + record them for + // assertions. (Direct property assignment works because the + // method is just an own property on the Api instance, not on + // its prototype.) + this.apis.contacts.fetchGroupMemberList = async ( + groupId: number, + options: { force?: boolean } = {}, + ): Promise => { + this.memberFetches.push({ groupId, force: Boolean(options.force) }); + for (const member of this.refreshedMembers) { + this.identity.updateGroupMember(groupId, member); + } + return this.refreshedMembers; + }; } } diff --git a/packages/core/tests/bridge-private-routing.test.ts b/packages/core/tests/bridge-private-routing.test.ts index 443ce172..6c2c61af 100644 --- a/packages/core/tests/bridge-private-routing.test.ts +++ b/packages/core/tests/bridge-private-routing.test.ts @@ -1,17 +1,17 @@ import { describe, expect, it, vi } from 'vitest'; -import type { SendPacketResult } from '../src/protocol/packet-sender'; -import { protoDecode, protoEncode } from '../src/protobuf/decode'; -import { SendMessageRequestSchema, SendMessageResponseSchema } from '../src/bridge/proto/action'; -import { FileExtraSchema } from '../src/bridge/proto/message'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action'; +import type { FileExtra } from '@snowluma/proto-defs/message'; -vi.mock('../src/bridge/element-builder', () => ({ +vi.mock('@snowluma/bridge/element-builder', () => ({ buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]), })); describe('Bridge private media routing', () => { it('includes resolved uid in the final c2c send request for media messages', async () => { const { Bridge } = await import('../src/bridge/bridge'); - const { IdentityService } = await import('../src/bridge/identity-service'); + const { IdentityService } = await import('@snowluma/bridge/identity-service'); class TestBridge extends Bridge { capturedBody: Uint8Array | null = null; @@ -29,20 +29,21 @@ describe('Bridge private media routing', () => { gotResponse: true, errorCode: 0, errorMessage: '', - responseData: Buffer.from(protoEncode({ + responseData: Buffer.from(protobuf_encode({ result: 0, + errMsg: '', privateSequence: 88, timestamp1: 1710000000, - }, SendMessageResponseSchema)), + })), }; } } const bridge = new TestBridge(IdentityService.memory('10000')); - await bridge.sendPrivateMessage(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]); + await bridge.apis.message.sendPrivate(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]); expect(bridge.capturedBody).toBeInstanceOf(Uint8Array); - const request = protoDecode(bridge.capturedBody as Uint8Array, SendMessageRequestSchema); + const request = protobuf_decode(bridge.capturedBody as Uint8Array); expect(request?.routingHead?.c2c).toMatchObject({ uin: 12345, uid: 'u_peer_12345', @@ -59,7 +60,7 @@ describe('Bridge private media routing', () => { // implementation wrote c2c routing + richText.notOnlineFile + // c2cCmd=11 — the QQ-NT server rejected every c2c file send. const { Bridge } = await import('../src/bridge/bridge'); - const { IdentityService } = await import('../src/bridge/identity-service'); + const { IdentityService } = await import('@snowluma/bridge/identity-service'); class TestBridge extends Bridge { capturedBody: Uint8Array | null = null; @@ -67,16 +68,16 @@ describe('Bridge private media routing', () => { this.capturedBody = body; return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', - responseData: Buffer.from(protoEncode({ - result: 0, privateSequence: 88, timestamp1: 1710000000, - }, SendMessageResponseSchema)), + responseData: Buffer.from(protobuf_encode({ + result: 0, errMsg: '', privateSequence: 88, timestamp1: 1710000000, + })), }; } } const bridge = new TestBridge(IdentityService.memory('10000')); const fileMd5 = new Uint8Array([0xde, 0xad, 0xbe, 0xef]); - await bridge.sendC2cFileMessage(67890, 'u_peer_xyz', { + await bridge.apis.message.sendC2cFile(67890, 'u_peer_xyz', { fileId: 'uuid-abc-123', fileName: 'doc.txt', fileSize: 1024, @@ -84,27 +85,24 @@ describe('Bridge private media routing', () => { fileHash: 'hash-xyz', }); - const request = protoDecode(bridge.capturedBody as Uint8Array, SendMessageRequestSchema); + const request = protobuf_decode(bridge.capturedBody as Uint8Array); // Routing: must be trans0x211 with ccCmd=4 + uid, no c2c slot. expect(request?.routingHead?.trans0x211).toMatchObject({ ccCmd: 4, uid: 'u_peer_xyz', }); - expect(request?.routingHead?.c2c).toBeUndefined(); + expect(request?.routingHead?.c2c ?? undefined).toBeUndefined(); // Body: msgContent carries the FileExtra; richText is absent (no // elems, no notOnlineFile slot — both lived on the wrong place). expect(request?.messageBody?.msgContent).toBeInstanceOf(Uint8Array); - expect(request?.messageBody?.richText).toBeUndefined(); + expect(request?.messageBody?.richText ?? undefined).toBeUndefined(); // Decode the msgContent and verify the NotOnlineFile fields land // at the correct tags (Lagrange's NotOnlineFile schema, not the // dead FileExtraInfo one). - const fileExtra = protoDecode( - request!.messageBody!.msgContent as Uint8Array, - FileExtraSchema, - ); + const fileExtra = protobuf_decode(request!.messageBody!.msgContent as Uint8Array); expect(fileExtra?.file).toMatchObject({ fileUuid: 'uuid-abc-123', fileName: 'doc.txt', diff --git a/packages/core/tests/decode.test.ts b/packages/core/tests/decode.test.ts deleted file mode 100644 index 15d8a2dc..00000000 --- a/packages/core/tests/decode.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { protoDecode, protoEncode, type ProtoSchema } from '../src/protobuf/decode'; -import { WireMessage, encodeKey, encodeVarint, WireType } from '../src/protobuf/wire'; - -describe('protoDecode', () => { - const SimpleSchema = { - name: { field: 1, type: 'string' as const }, - age: { field: 2, type: 'uint32' as const }, - active: { field: 3, type: 'bool' as const }, - }; - - function buildProto(): Uint8Array { - const out: number[] = []; - // field 1 string "Alice" - encodeKey(1, WireType.LengthDelimited, out); - const str = new TextEncoder().encode('Alice'); - encodeVarint(str.length, out); - out.push(...str); - // field 2 uint32 = 30 - encodeKey(2, WireType.Varint, out); - encodeVarint(30, out); - // field 3 bool = true - encodeKey(3, WireType.Varint, out); - encodeVarint(1, out); - return new Uint8Array(out); - } - - it('decodes all fields', () => { - const result = protoDecode(buildProto(), SimpleSchema); - expect(result).not.toBeNull(); - expect(result!.name).toBe('Alice'); - expect(result!.age).toBe(30); - expect(result!.active).toBe(true); - }); - - it('handles missing fields', () => { - // Only field 1 - const out: number[] = []; - encodeKey(1, WireType.LengthDelimited, out); - const str = new TextEncoder().encode('Bob'); - encodeVarint(str.length, out); - out.push(...str); - - const result = protoDecode(new Uint8Array(out), SimpleSchema); - expect(result).not.toBeNull(); - expect(result!.name).toBe('Bob'); - expect(result!.age).toBeUndefined(); - expect(result!.active).toBeUndefined(); - }); - - it('returns null for empty data', () => { - expect(protoDecode(new Uint8Array(0), SimpleSchema)).toBeNull(); - }); - - it('decodes nested messages', () => { - const InnerSchema = { - value: { field: 1, type: 'uint32' as const }, - }; - const OuterSchema = { - inner: { field: 1, type: 'message' as const, schema: InnerSchema }, - }; - - // Build inner - const innerOut: number[] = []; - encodeKey(1, WireType.Varint, innerOut); - encodeVarint(99, innerOut); - - // Build outer - const outerOut: number[] = []; - encodeKey(1, WireType.LengthDelimited, outerOut); - encodeVarint(innerOut.length, outerOut); - outerOut.push(...innerOut); - - const result = protoDecode(new Uint8Array(outerOut), OuterSchema); - expect(result).not.toBeNull(); - expect(result!.inner).not.toBeUndefined(); - expect(result!.inner!.value).toBe(99); - }); - - it('decodes repeated messages', () => { - const ItemSchema = { - id: { field: 1, type: 'uint32' as const }, - }; - const ListSchema = { - items: { field: 1, type: 'repeated_message' as const, schema: ItemSchema }, - }; - - const out: number[] = []; - for (const id of [1, 2, 3]) { - const itemOut: number[] = []; - encodeKey(1, WireType.Varint, itemOut); - encodeVarint(id, itemOut); - - encodeKey(1, WireType.LengthDelimited, out); - encodeVarint(itemOut.length, out); - out.push(...itemOut); - } - - const result = protoDecode(new Uint8Array(out), ListSchema); - expect(result).not.toBeNull(); - expect(result!.items).toHaveLength(3); - expect(result!.items.map((i) => i.id)).toEqual([1, 2, 3]); - }); - - it('accepts WireMessage directly', () => { - const wire = WireMessage.decode(buildProto()); - const result = protoDecode(wire!, SimpleSchema); - expect(result!.name).toBe('Alice'); - }); -}); - -describe('protoEncode', () => { - const SimpleSchema = { - name: { field: 1, type: 'string' as const }, - age: { field: 2, type: 'uint32' as const }, - active: { field: 3, type: 'bool' as const }, - }; - - it('encodes and decodes roundtrip', () => { - const data = { name: 'Charlie', age: 25, active: true }; - const encoded = protoEncode(data, SimpleSchema); - const decoded = protoDecode(encoded, SimpleSchema); - expect(decoded).not.toBeNull(); - expect(decoded!.name).toBe('Charlie'); - expect(decoded!.age).toBe(25); - expect(decoded!.active).toBe(true); - }); - - it('skips undefined fields', () => { - const data = { name: 'Dave', age: undefined, active: undefined }; - const encoded = protoEncode(data as any, SimpleSchema); - const decoded = protoDecode(encoded, SimpleSchema); - expect(decoded!.name).toBe('Dave'); - expect(decoded!.age).toBeUndefined(); - expect(decoded!.active).toBeUndefined(); - }); - - it('encodes bytes', () => { - const ByteSchema = { - payload: { field: 1, type: 'bytes' as const }, - }; - const data = { payload: new Uint8Array([0xDE, 0xAD]) }; - const encoded = protoEncode(data, ByteSchema); - const decoded = protoDecode(encoded, ByteSchema); - expect(decoded!.payload).toEqual(new Uint8Array([0xDE, 0xAD])); - }); - - it('encodes nested messages', () => { - const InnerSchema = { - value: { field: 1, type: 'uint32' as const }, - }; - const OuterSchema = { - inner: { field: 1, type: 'message' as const, schema: InnerSchema }, - }; - - const data = { inner: { value: 42 } }; - const encoded = protoEncode(data, OuterSchema); - const decoded = protoDecode(encoded, OuterSchema); - expect(decoded!.inner!.value).toBe(42); - }); - - it('encodes int64/uint64', () => { - const BigSchema = { - signed: { field: 1, type: 'int64' as const }, - unsigned: { field: 2, type: 'uint64' as const }, - }; - const data = { signed: -1n, unsigned: 0xFFFFFFFFFFFFFFFFn }; - const encoded = protoEncode(data, BigSchema); - const decoded = protoDecode(encoded, BigSchema); - expect(decoded!.signed).toBe(-1n); - expect(decoded!.unsigned).toBe(0xFFFFFFFFFFFFFFFFn); - }); -}); diff --git a/packages/core/tests/element-builder.test.ts b/packages/core/tests/element-builder.test.ts index 50ca621e..2e80b797 100644 --- a/packages/core/tests/element-builder.test.ts +++ b/packages/core/tests/element-builder.test.ts @@ -16,17 +16,17 @@ import { describe, expect, it, vi } from 'vitest'; -vi.mock('../src/bridge/highway/image-upload', () => ({ +vi.mock('@snowluma/bridge/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])), })); -vi.mock('../src/bridge/highway/ptt-upload', () => ({ +vi.mock('@snowluma/bridge/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn(async () => new Uint8Array([4, 5, 6])), })); -vi.mock('../src/bridge/highway/video-upload', () => ({ +vi.mock('@snowluma/bridge/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])), })); -import { buildSendElems } from '../src/bridge/element-builder'; +import { buildSendElems } from '@snowluma/bridge/element-builder'; const fakeBridge = {} as any; diff --git a/packages/core/tests/event-format.test.ts b/packages/core/tests/event-format.test.ts index fd4400e9..b41149ad 100644 --- a/packages/core/tests/event-format.test.ts +++ b/packages/core/tests/event-format.test.ts @@ -12,8 +12,8 @@ import { formatMessageSegments, formatReply, formatUser, -} from '../src/utils/event-format'; -import type { QQEventVariant } from '../src/bridge/events'; +} from '@snowluma/bridge/format'; +import type { QQEventVariant } from '@snowluma/bridge/events'; // ─── Test fakes (just the find* surface event-format uses) ─── diff --git a/packages/core/tests/hex.test.ts b/packages/core/tests/hex.test.ts index 8190b9a0..b3d506ca 100644 --- a/packages/core/tests/hex.test.ts +++ b/packages/core/tests/hex.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { toHex, fromHex, hexPreview } from '../src/utils/hex'; +import { toHex, fromHex, hexPreview } from '@snowluma/common/hex'; describe('toHex', () => { it('converts empty buffer', () => { diff --git a/packages/core/tests/highway-utils.test.ts b/packages/core/tests/highway-utils.test.ts index 130f8e68..8e79595e 100644 --- a/packages/core/tests/highway-utils.test.ts +++ b/packages/core/tests/highway-utils.test.ts @@ -2,8 +2,8 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; import { pathToFileURL } from 'url'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { loadBinarySource, resolveLocalFilePath } from '@snowluma/bridge/highway/utils'; describe('highway source paths', () => { it('normalizes file URLs with an extra leading slash on POSIX', () => { diff --git a/packages/core/tests/highway/image-upload.test.ts b/packages/core/tests/highway/image-upload.test.ts index 451f737f..a35e8cc9 100644 --- a/packages/core/tests/highway/image-upload.test.ts +++ b/packages/core/tests/highway/image-upload.test.ts @@ -5,13 +5,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('../../src/bridge/highway/pipeline', () => ({ +vi.mock('@snowluma/bridge/highway/pipeline', () => ({ runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })), finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xCA, 0xFE])), hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)), })); -vi.mock('../../src/bridge/highway/utils', () => ({ +vi.mock('@snowluma/bridge/highway/utils', () => ({ loadBinarySource: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), fileName: 'src.jpg' })), computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), @@ -22,9 +22,9 @@ vi.mock('../../src/bridge/highway/utils', () => ({ detectImageFormat: vi.fn(() => ({ format: 1000, width: 800, height: 600 })), })); -import * as pipeline from '../../src/bridge/highway/pipeline'; -import { uploadImageMsgInfo } from '../../src/bridge/highway/image-upload'; -import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '../../src/bridge/highway/highway-client'; +import * as pipeline from '@snowluma/bridge/highway/pipeline'; +import { uploadImageMsgInfo } from '@snowluma/bridge/highway/image-upload'; +import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '@snowluma/bridge/highway'; describe('image-upload', () => { beforeEach(() => { diff --git a/packages/core/tests/highway/pipeline.test.ts b/packages/core/tests/highway/pipeline.test.ts index af7dc72a..8a08cf79 100644 --- a/packages/core/tests/highway/pipeline.test.ts +++ b/packages/core/tests/highway/pipeline.test.ts @@ -6,8 +6,9 @@ // the actual decode path inside the pipeline. import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -vi.mock('../../src/bridge/highway/highway-client', () => ({ +vi.mock('@snowluma/bridge/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })), uploadHighwayHttp: vi.fn(async () => undefined), buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])), @@ -15,21 +16,16 @@ vi.mock('../../src/bridge/highway/highway-client', () => ({ GROUP_IMAGE_CMD_ID: 1004, })); -import * as highway from '../../src/bridge/highway/highway-client'; +import * as highway from '@snowluma/bridge/highway'; import { finalizeMediaMsgInfo, hexToBytes, makeClientRandomId, runNtv2Upload, type MediaSubFileUpload, -} from '../../src/bridge/highway/pipeline'; -import { protoDecode, protoEncode } from '../../src/protobuf/decode'; -import { makeOidbBaseSchema } from '../../src/bridge/proto/oidb'; -import { - EncodableMediaMsgInfoSchema, - NTV2UploadRichMediaReqSchema, - NTV2UploadRichMediaRespSchema, -} from '../../src/bridge/proto/highway'; +} from '@snowluma/bridge/highway/pipeline'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { EncodableMediaMsgInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway'; interface FakeUploadResponse { upload?: { @@ -48,8 +44,7 @@ interface FakeUploadResponse { } function encodeOidbResponse(body: FakeUploadResponse, opts: { errorCode?: number; errorMsg?: string } = {}): Buffer { - const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema); - return Buffer.from(protoEncode({ + return Buffer.from(protobuf_encode>({ command: 0x11C4, subCommand: 100, errorCode: opts.errorCode ?? 0, @@ -58,7 +53,7 @@ function encodeOidbResponse(body: FakeUploadResponse, opts: { errorCode?: number body: body as unknown as Record, errorMsg: opts.errorMsg ?? '', reserved: 1, - }, baseSchema)); + } as OidbBase)); } type SendPacketResult = { @@ -125,8 +120,7 @@ describe('pipeline — runNtv2Upload', () => { // The request roundtrips through the real OIDB envelope and carries // the requestId / businessType / scene fields we passed. - const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema); - const decoded: any = protoDecode(requestBytes as Uint8Array, baseSchema); + const decoded: any = protobuf_decode>(requestBytes as Uint8Array); expect(decoded.command).toBe(0x11C4); expect(decoded.body.reqHead.common.requestId).toBe(1); expect(decoded.body.reqHead.scene.businessType).toBe(1); @@ -141,7 +135,7 @@ describe('pipeline — runNtv2Upload', () => { await runNtv2Upload(baseParams({ bridge, isGroup: false, targetIdOrUid: 'recipient-uid' })); const requestBytes = bridge.sendRawPacket.mock.calls[0]![1]; - const decoded: any = protoDecode(requestBytes as Uint8Array, makeOidbBaseSchema(NTV2UploadRichMediaReqSchema)); + const decoded: any = protobuf_decode>(requestBytes as Uint8Array); expect(decoded.body.reqHead.scene.sceneType).toBe(1); expect(decoded.body.reqHead.scene.c2c.targetUid).toBe('recipient-uid'); }); @@ -336,7 +330,7 @@ describe('pipeline — finalizeMediaMsgInfo', () => { msgInfo: { msgInfoBody: [], extBizInfo: {} }, }, { bizType: 7, textSummary: '[image]' }); - const decoded: any = protoDecode(out, EncodableMediaMsgInfoSchema); + const decoded: any = protobuf_decode(out); expect(decoded.extBizInfo.pic.bizType).toBe(7); expect(decoded.extBizInfo.pic.textSummary).toBe('[image]'); }); @@ -345,10 +339,10 @@ describe('pipeline — finalizeMediaMsgInfo', () => { const out = finalizeMediaMsgInfo({ msgInfo: { msgInfoBody: [], extBizInfo: {} }, }); - const decoded: any = protoDecode(out, EncodableMediaMsgInfoSchema); + const decoded: any = protobuf_decode(out); // An empty extBizInfo proto roundtrips to undefined; either way the // pic field never got materialised. - expect(decoded?.extBizInfo?.pic).toBeUndefined(); + expect(decoded?.extBizInfo?.pic ?? undefined).toBeUndefined(); }); }); diff --git a/packages/core/tests/highway/ptt-upload.test.ts b/packages/core/tests/highway/ptt-upload.test.ts index b640eb3e..72efe321 100644 --- a/packages/core/tests/highway/ptt-upload.test.ts +++ b/packages/core/tests/highway/ptt-upload.test.ts @@ -7,14 +7,14 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('../../src/bridge/highway/pipeline', () => ({ +vi.mock('@snowluma/bridge/highway/pipeline', () => ({ runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })), finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xAA, 0xBB])), hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)), })); -import * as pipeline from '../../src/bridge/highway/pipeline'; -import { uploadPttMsgInfo, GROUP_PTT_CMD_ID, PRIVATE_PTT_CMD_ID } from '../../src/bridge/highway/ptt-upload'; +import * as pipeline from '@snowluma/bridge/highway/pipeline'; +import { uploadPttMsgInfo, GROUP_PTT_CMD_ID, PRIVATE_PTT_CMD_ID } from '@snowluma/bridge/highway/ptt-upload'; const FINGERPRINT = { noByteFallback: true, diff --git a/packages/core/tests/highway/video-upload.test.ts b/packages/core/tests/highway/video-upload.test.ts index 0d352d31..a7910cc2 100644 --- a/packages/core/tests/highway/video-upload.test.ts +++ b/packages/core/tests/highway/video-upload.test.ts @@ -11,20 +11,20 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('../../src/bridge/highway/pipeline', () => ({ +vi.mock('@snowluma/bridge/highway/pipeline', () => ({ runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })), finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0x12, 0x34])), hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)), })); -import * as pipeline from '../../src/bridge/highway/pipeline'; +import * as pipeline from '@snowluma/bridge/highway/pipeline'; import { uploadVideoMsgInfo, GROUP_VIDEO_CMD_ID, GROUP_VIDEO_THUMB_CMD_ID, PRIVATE_VIDEO_CMD_ID, PRIVATE_VIDEO_THUMB_CMD_ID, -} from '../../src/bridge/highway/video-upload'; +} from '@snowluma/bridge/highway/video-upload'; const FINGERPRINT = { noByteFallback: true, diff --git a/packages/core/tests/hook-manager.test.ts b/packages/core/tests/hook-manager.test.ts index 87c0e15c..de1aaf13 100644 --- a/packages/core/tests/hook-manager.test.ts +++ b/packages/core/tests/hook-manager.test.ts @@ -8,7 +8,7 @@ import { PipeWatcher } from '../src/hook/pipe-watcher'; import type { ManualMapHandle } from '../src/hook/injector'; import type { BridgeManager } from '../src/bridge/manager'; import type { QqHookClient } from '../src/hook/qq-hook-client'; -import { createLogger } from '../src/utils/logger'; +import { createLogger } from '@snowluma/common/logger'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; const flush = () => new Promise(r => setImmediate(r)); diff --git a/packages/core/tests/hook-session.test.ts b/packages/core/tests/hook-session.test.ts index 26127d27..8a14f335 100644 --- a/packages/core/tests/hook-session.test.ts +++ b/packages/core/tests/hook-session.test.ts @@ -3,7 +3,7 @@ import { EventEmitter } from 'events'; import { HookSession } from '../src/hook/hook-session'; import type { ManualMapHandle } from '../src/hook/injector'; import type { QqHookClient, QqHookPacket } from '../src/hook/qq-hook-client'; -import type { PacketSink } from '../src/protocol/types'; +import type { PacketSink } from '@snowluma/common/protocol-types'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; diff --git a/packages/core/tests/identity-service.test.ts b/packages/core/tests/identity-service.test.ts index df4a51e9..327e87d0 100644 --- a/packages/core/tests/identity-service.test.ts +++ b/packages/core/tests/identity-service.test.ts @@ -1,8 +1,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import fs from 'fs'; import path from 'path'; -import { IdentityService } from '../src/bridge/identity-service'; -import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '../src/bridge/qq-info'; +import { IdentityService } from '@snowluma/bridge/identity-service'; +import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/bridge/qq-info'; const SELF_UIN = '10001'; const GROUP_ID = 123456789; diff --git a/packages/core/tests/log-file-transport.test.ts b/packages/core/tests/log-file-transport.test.ts index b07c6dcb..4bd48404 100644 --- a/packages/core/tests/log-file-transport.test.ts +++ b/packages/core/tests/log-file-transport.test.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { FileTransport } from '../src/utils/log-file-transport'; +import { FileTransport } from '@snowluma/common/log-file-transport'; let tmpDir: string; const ENV_KEYS = [ diff --git a/packages/core/tests/logger.test.ts b/packages/core/tests/logger.test.ts index 16342153..ea5dd1ea 100644 --- a/packages/core/tests/logger.test.ts +++ b/packages/core/tests/logger.test.ts @@ -11,8 +11,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { createLogger, getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '../src/utils/logger'; -import { _resetFileTransportForTesting } from '../src/utils/log-file-transport'; +import { createLogger, getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger'; +import { _resetFileTransportForTesting } from '@snowluma/common/log-file-transport'; let tmpDir: string; const ENV_KEYS = [ diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index c40ca4c8..ef96567a 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -1,10 +1,8 @@ import { describe, expect, it } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; -import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push'; -import { IdentityService } from '../src/bridge/identity-service'; -import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info'; -import { PushMsgSchema } from '../src/bridge/proto/message'; -import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify'; +import { parseMsgPush, MSG_PUSH_CMD } from '@snowluma/bridge/msg-push'; +import { IdentityService } from '@snowluma/bridge/identity-service'; +import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/bridge/qq-info'; // Proton's call-site analyzer keys off the literal type identifier // printed in `protobuf_encode` — it walks imports by *original* // name (not alias). If both `import { X } from 'proto/notify'` and @@ -15,19 +13,19 @@ import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notif // name) — we don't need to import it directly since assertions can // inline-extract the kind. import type { - NewFriend, FriendRecall, SelfJoinInGroup, -} from '../src/bridge/proto/proton/notify'; + GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, +} from '@snowluma/proto-defs/notify'; +import type { PushMsg } from '@snowluma/proto-defs/message'; import type { GroupMemberJoin, FriendAddEvent, QQEventVariant, -} from '../src/bridge/events'; +} from '@snowluma/bridge/events'; // Local alias for the event-side recall type — derived via Extract so // we avoid an `import { FriendRecall as X }` that collides with the // proton import above. type FriendRecallEvent = Extract; -import type { PacketInfo } from '../src/protocol/types'; -import { protoEncode } from '../src/protobuf/decode'; -import { subscribeLogs } from '../src/utils/logger'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import { subscribeLogs } from '@snowluma/common/logger'; const SELF_UIN = '10001'; const GROUP_ID = 123456789; @@ -67,21 +65,21 @@ function makeIdentity(members: GroupMemberInfo[] = []): IdentityService { function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = GROUP_ID): PacketInfo { const operatorBytes = operatorUid - ? protoEncode({ operatorField: { uid: operatorUid } } as any, OperatorInfoSchema) + ? protobuf_encode({ operatorField: { uid: operatorUid } }) : new Uint8Array(0); - const content = protoEncode({ + const content = protobuf_encode({ groupUin: GROUP_ID, memberUid, operatorBytes, - } as any, GroupChangeSchema); - const body = protoEncode({ + }); + const body = protobuf_encode({ message: { responseHead: { fromUin }, contentHead: { msgType: 33, timestamp: 1710000000 }, body: { msgContent: content }, }, status: 0, - } as any, PushMsgSchema); + }); return { pid: 1, @@ -129,7 +127,7 @@ describe('parseMsgPush Event0x210 subType=38 (acknowledged-but-silent)', () => { // drop silently — no OneBot-level event, and — critically — // **no** "unknown subType=38" fallback log spam anymore. function makeEvent0x210Packet(subType: number, content = new Uint8Array(0)): PacketInfo { - const body = protoEncode({ + const body = protobuf_encode({ message: { responseHead: { fromUin: 22222, type: 0, sigMap: 0 }, // 528 = Event0x210 @@ -137,7 +135,7 @@ describe('parseMsgPush Event0x210 subType=38 (acknowledged-but-silent)', () => { body: { msgContent: content }, }, status: 0, - } as any, PushMsgSchema); + }); return { pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, retCode: 0, fromClient: false, body, @@ -186,14 +184,14 @@ describe('parseMsgPush Event0x210 subType=38 (acknowledged-but-silent)', () => { // that we were previously dropping into the "unknown" fallback. ── function makeEvent0x210PacketAny(subType: number, content: Uint8Array): PacketInfo { - const body = protoEncode({ + const body = protobuf_encode({ message: { responseHead: { fromUin: 22222, type: 0, sigMap: 0 }, contentHead: { msgType: 528, subType, timestamp: 1710000000 }, body: { msgContent: content }, }, status: 0, - } as any, PushMsgSchema); + }); return { pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, retCode: 0, fromClient: false, body, @@ -313,14 +311,14 @@ describe('parseMsgPush PkgType 85 (bot self-joined a group)', () => { field6: 48, field7: '', }); - const body = protoEncode({ + const body = protobuf_encode({ message: { responseHead: { fromUin: groupId, type: 0, sigMap: 0 }, contentHead: { msgType: 85, subType: 0, timestamp: 1710000000 }, body: { msgContent: content }, }, status: 0, - } as any, PushMsgSchema); + }); return { pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, retCode: 0, fromClient: false, body, diff --git a/packages/core/tests/observability-logs.test.ts b/packages/core/tests/observability-logs.test.ts index ee3a871e..12798493 100644 --- a/packages/core/tests/observability-logs.test.ts +++ b/packages/core/tests/observability-logs.test.ts @@ -10,9 +10,10 @@ // network I/O. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { subscribeLogs, type LogEntry } from '../src/utils/logger'; +import { protobuf_encode } from '@snowluma/proton'; +import { subscribeLogs, type LogEntry } from '@snowluma/common/logger'; -vi.mock('../src/bridge/highway/highway-client', () => ({ +vi.mock('@snowluma/bridge/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })), uploadHighwayHttp: vi.fn(async () => undefined), buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])), @@ -23,23 +24,19 @@ vi.mock('../src/bridge/highway/highway-client', () => ({ import { runNtv2Upload, type MediaSubFileUpload, -} from '../src/bridge/highway/pipeline'; -import { protoEncode } from '../src/protobuf/decode'; -import { makeOidbBaseSchema } from '../src/bridge/proto/oidb'; -import { - NTV2UploadRichMediaRespSchema, -} from '../src/bridge/proto/highway'; -import { MsgPushRegistry } from '../src/bridge/msg-push/registry'; -import type { MsgPushContext } from '../src/bridge/msg-push/context'; -import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc'; +} from '@snowluma/bridge/highway/pipeline'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway'; +import { MsgPushRegistry } from '@snowluma/bridge/msg-push/registry'; +import type { MsgPushContext } from '@snowluma/bridge/msg-push/context'; +import { decodeEvent0x2DC } from '@snowluma/bridge/msg-push/decoders/event-0x2dc'; function encodeOidbResponse(body: unknown): Buffer { - const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema); - return Buffer.from(protoEncode({ + return Buffer.from(protobuf_encode>({ command: 0x11C4, subCommand: 100, errorCode: 0, body: body as Record, errorMsg: '', reserved: 1, - }, baseSchema)); + } as OidbBase)); } function fakeBridge(responseData: Buffer, uin = '12345'): any { diff --git a/packages/core/tests/pipe-watcher.test.ts b/packages/core/tests/pipe-watcher.test.ts index 5486971d..048a3e3d 100644 --- a/packages/core/tests/pipe-watcher.test.ts +++ b/packages/core/tests/pipe-watcher.test.ts @@ -2,8 +2,6 @@ import { describe, it, expect } from 'vitest'; import { PipeWatcher } from '../src/hook/pipe-watcher'; import type { HookProcessBaseInfo } from '../src/hook/injector'; -const flush = () => new Promise(r => setImmediate(r)); - function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set }) { let processes = initial.processes; let live = initial.live; diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts deleted file mode 100644 index a6531434..00000000 --- a/packages/core/tests/proton-parity.test.ts +++ /dev/null @@ -1,815 +0,0 @@ -// Proof-of-concept: verify that codec generated by @snowluma/proton's Vite -// plugin produces wire bytes byte-identical to the legacy runtime schema -// encoder for the same input. If this passes, the migration pattern is sound -// for the schemas covered here. - -import { describe, it, expect } from 'vitest'; -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; -import { protoEncode, protoDecode } from '../src/protobuf/decode'; - -import { - SendLongMsgRespSchema, - SendLongMsgReqSchema, - RecvLongMsgReqSchema, - RecvLongMsgRespSchema, - LongMsgSettingsSchema, - LongMsgResultSchema, -} from '../src/bridge/proto/longmsg'; -import { - TextElemSchema, - NotOnlineImageSchema, - ExtraInfoSchema, - SrcMsgSchema, - ElemSchema, - MsgInfoSchema, -} from '../src/bridge/proto/element'; -import { - ResponseHeadSchema, - PushMsgBodySchema, - PushMsgSchema, -} from '../src/bridge/proto/message'; -import { - GroupChangeSchema, - GroupAdminSchema, - NotifyMessageBodySchema, - GroupReactNotifySchema, - FriendRequestSchema, - GroupJoinSchema, -} from '../src/bridge/proto/notify'; -import { - RoutingHeadSchema, - SendMessageRequestSchema, - SendMessageResponseSchema, - MentionExtraSendSchema, - MarkdownDataSchema, -} from '../src/bridge/proto/action'; -import { - HttpConn0x6FF501RequestSchema, - HttpConn0x6FF501ResponseSchema, - ReqDataHighwayHeadSchema, - NTV2RichMediaHighwayExtSchema, - FileUploadExtSchema, -} from '../src/bridge/proto/highway'; -import { makeOidbBaseSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema } from '../src/bridge/proto/oidb'; -import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../src/bridge/bridge-oidb'; -import { - GetMediaListRequestSchema, - DoQunCommentRequestSchema, - DoQunLikeRequestSchema, - DeleteMediasRequestSchema, - DeleteMediasResponseSchema, -} from '../src/bridge/proto/oidb-action'; - -import type { - SendLongMsgResp, - SendLongMsgReq, - RecvLongMsgReq, - RecvLongMsgResp, - LongMsgSettings, - LongMsgResult, -} from '../src/bridge/proto/proton/longmsg'; -import type { - TextElem, - NotOnlineImage, - ExtraInfo, - SrcMsg, - Elem, - MsgInfo, -} from '../src/bridge/proto/proton/element'; -import type { - ResponseHead, - PushMsgBody, - PushMsg, -} from '../src/bridge/proto/proton/message'; -import type { - GroupChange, - GroupAdmin, - NotifyMessageBody, - GroupReactNotify, - FriendRequest as FriendRequestNotify, - GroupJoin, -} from '../src/bridge/proto/proton/notify'; -import type { - RoutingHead, - SendMessageRequest, - SendMessageResponse, - MentionExtraSend, - MarkdownData, -} from '../src/bridge/proto/proton/action'; -import type { - HttpConn0x6FF501Request, - HttpConn0x6FF501Response, - ReqDataHighwayHead, - NTV2RichMediaHighwayExt, - FileUploadExt, -} from '../src/bridge/proto/proton/highway'; -import type { - OidbBase, - OidbSvcTrpcTcp0xFE5_2Response, -} from '../src/bridge/proto/proton/oidb'; -import type { - GetMediaListRequest, - DoQunCommentRequest, - DoQunLikeRequest, - DeleteMediasRequest, - DeleteMediasResponse, -} from '../src/bridge/proto/proton/oidb-action'; - -function hex(buf: Uint8Array): string { - return Buffer.from(buf).toString('hex'); -} - -describe('proton ↔ legacy parity (longmsg subset)', () => { - it('encodes LongMsgSettings identically', () => { - const data: LongMsgSettings = { field1: 1, field2: 2, field3: 3, field4: 4 }; - const legacy = protoEncode(data as any, LongMsgSettingsSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes SendLongMsgResp (nested message) identically', () => { - const data: SendLongMsgResp = { result: { resId: 'res-001' } }; - const legacy = protoEncode(data as any, SendLongMsgRespSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes SendLongMsgReq with bytes + nested + settings identically', () => { - // NOTE: all numeric fields are non-zero — proton follows proto3 semantics - // and omits default-valued fields from the wire, whereas the legacy runtime - // encoder always writes them. Parity is therefore only expected when no - // numeric field equals its default. See the explicit divergence test below. - const data: SendLongMsgReq = { - info: { - type: 1, - uid: { uid: 'u_test' }, - groupUin: 123456, - payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]), - }, - settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, - }; - const legacy = protoEncode(data as any, SendLongMsgReqSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes RecvLongMsgReq with bool field identically', () => { - const data: RecvLongMsgReq = { - info: { uid: { uid: 'u_recv' }, resId: 'r-9', acquire: true }, - settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, - }; - const legacy = protoEncode(data as any, RecvLongMsgReqSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes RecvLongMsgResp (with bytes payload) identically', () => { - const data: RecvLongMsgResp = { - result: { resId: 'r-1', payload: new Uint8Array([1, 2, 3, 4, 5]) }, - settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, - }; - const legacy = protoEncode(data as any, RecvLongMsgRespSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - // ── element.ts coverage ───────────────────────────────────────────── - - it('encodes TextElem (only primitive bytes + strings) identically', () => { - const data: TextElem = { - str: 'hello', - link: 'https://example.com', - attr6Buf: new Uint8Array([1, 2, 3]), - buf: new Uint8Array([0xff, 0xee]), - }; - const legacy = protoEncode(data as any, TextElemSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes NotOnlineImage with nested PbReserve identically', () => { - const data: NotOnlineImage = { - filePath: 'pic.jpg', - fileLen: 12345, - picMd5: new Uint8Array([0x11, 0x22, 0x33, 0x44]), - picHeight: 600, - picWidth: 800, - resId: 'res-abc', - original: 1, - bigUrl: 'https://q.qq.com/big/abc', - bizType: 5, - pbRes: { - subType: 1, - summary: '[picture]', - field10: 7, - field20: { field1: 1, field2: 'inner', field3: 2, field4: 3, field5: 4, field7: 'tail' }, - url: 'https://q.qq.com/abc', - md5Str: 'abc123', - }, - }; - const legacy = protoEncode(data as any, NotOnlineImageSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes ExtraInfo (mix of bytes + int32 + uint64) identically', () => { - const data: ExtraInfo = { - nick: new Uint8Array([0x41, 0x42]), - groupCard: new Uint8Array([0x43]), - level: 7, - flags: 1, - groupMask: 2, - msgTailId: 3, - uin: 10001n, - msgStateFlag: 4, - }; - const legacy = protoEncode(data as any, ExtraInfoSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes SrcMsg with repeated_uint32 + repeated_bytes identically', () => { - const data: SrcMsg = { - origSeqs: [100, 200, 300, 400], - senderUin: 10001n, - time: 1234567890, - flag: 1, - elemsRaw: [new Uint8Array([1, 2]), new Uint8Array([3, 4]), new Uint8Array([5, 6])], - type: 1, - toUin: 20002n, - }; - const legacy = protoEncode(data as any, SrcMsgSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes Elem (oneOf-style union) identically across multiple shapes', () => { - const textOnly: Elem = { text: { str: 'hi', link: 'lnk' } }; - expect(hex(protobuf_encode(textOnly))).toBe(hex(protoEncode(textOnly as any, ElemSchema))); - - const faceOnly: Elem = { face: { index: 42, buf: new Uint8Array([1, 2, 3]) } }; - expect(hex(protobuf_encode(faceOnly))).toBe(hex(protoEncode(faceOnly as any, ElemSchema))); - - const generalFlags: Elem = { generalFlags: { uin: 10001n, longTextFlag: 1, longTextResId: 'rs' } }; - expect(hex(protobuf_encode(generalFlags))).toBe(hex(protoEncode(generalFlags as any, ElemSchema))); - }); - - it('encodes MsgInfo with repeated_message + deeply nested ExtBizInfo identically', () => { - const data: MsgInfo = { - msgInfoBody: [ - { - index: { - info: { fileSize: 1024, fileHash: 'sha-1', fileSha1: 'sha-2', fileName: 'a.png', type: { type: 1, picFormat: 2, videoFormat: 3, voiceFormat: 4 }, width: 100, height: 200, time: 99, original: 1 }, - fileUuid: 'uuid-1', storeId: 5, uploadTime: 1000, ttl: 86400, subType: 1, - }, - picture: { - urlPath: '/p/1', - ext: { originalParameter: 'op', bigParameter: 'bp', thumbParameter: 'tp' }, - domain: 'q.qq.com', - }, - fileExist: true, - }, - ], - extBizInfo: { - pic: { - bizType: 5, textSummary: '[pic]', - extData: { subType: 2, textSummary: 'sum' }, - fromScene: 1, toScene: 2, oldFileId: 999, - }, - busiType: 3, - }, - }; - const legacy = protoEncode(data as any, MsgInfoSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - // ── message.ts coverage ───────────────────────────────────────────── - - it('encodes ResponseHead (nested forward + grp) identically', () => { - const data: ResponseHead = { - fromUin: 10001, fromUid: 'u_a', type: 1, sigMap: 2, toUin: 20002, toUid: 'u_b', - forward: { friendName: 'Alice' }, - grp: { groupUin: 555, memberName: 'Bob', groupName: 'TestGroup' }, - }; - const legacy = protoEncode(data as any, ResponseHeadSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes PushMsgBody (with RichText holding Elem[]) identically', () => { - const data: PushMsgBody = { - responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 3, fromUid: 'a', toUid: 'b' }, - contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 99, sequence: 100, timestamp: 1234567890 }, - body: { - richText: { - elems: [ - { text: { str: 'hi ' } }, - { text: { str: 'world', link: 'lnk' } }, - ], - }, - }, - }; - const legacy = protoEncode(data as any, PushMsgBodySchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes PushMsg (top-level) identically', () => { - const data: PushMsg = { - message: { - responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 1, fromUid: 'a', toUid: 'b' }, - contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 1, sequence: 1, timestamp: 1 }, - body: { richText: { elems: [{ text: { str: 'x' } }] } }, - }, - status: 1, - }; - const legacy = protoEncode(data as any, PushMsgSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - // ── longmsg.ts: full migration (Content / Action / Result) ───────── - - it('encodes LongMsgResult (repeated Action → Content → PushMsgBody[]) identically', () => { - const inner: PushMsgBody = { - responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 1, fromUid: 'a', toUid: 'b' }, - contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 1, sequence: 1, timestamp: 1 }, - body: { richText: { elems: [{ text: { str: 'forwarded' } }] } }, - }; - const data: LongMsgResult = { - action: [ - { - actionCommand: 'MultiMsg', - actionData: { msgBody: [inner, inner] }, - }, - ], - }; - const legacy = protoEncode(data as any, LongMsgResultSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - // ── notify.ts coverage ────────────────────────────────────────────── - - it('encodes GroupChange identically', () => { - const data: GroupChange = { - groupUin: 555, - flag: 1, - memberUid: 'u_x', - decreaseType: 130, - operatorBytes: new Uint8Array([1, 2, 3]), - increaseType: 1, - }; - const legacy = protoEncode(data as any, GroupChangeSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes GroupAdmin (extraEnable variant) identically', () => { - const data: GroupAdmin = { - groupUin: 777, flag: 1, isPromote: true, - body: { extraEnable: { adminUid: 'u_admin', isPromote: true } }, - }; - const legacy = protoEncode(data as any, GroupAdminSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes NotifyMessageBody (recall variant with repeated RecallMessage) identically', () => { - const data: NotifyMessageBody = { - type: 17, - groupUin: 555, - recall: { - operatorUid: 'u_op', - recallMessages: [ - { sequence: 1, time: 100, random: 42, type: 1, flag: 1, authorUid: 'u_a' }, - { sequence: 2, time: 200, random: 43, type: 1, flag: 1, authorUid: 'u_a' }, - ], - groupType: 1, opType: 2, - tipInfo: { tip: 'recalled' }, - }, - msgSequence: 99, - }; - const legacy = protoEncode(data as any, NotifyMessageBodySchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes GroupReactNotify (deeply nested) identically', () => { - const data: GroupReactNotify = { - groupUin: 555n, - field13: 35, - groupReactionData: { - data: { - data: { - groupReactionTarget: { seq: 12345n }, - groupReactionDataContent: { code: '128516', count: 1, operatorUid: 'u_op', type: 1 }, - }, - }, - }, - }; - const legacy = protoEncode(data as any, GroupReactNotifySchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes FriendRequest identically', () => { - const data: FriendRequestNotify = { - info: { targetUid: 'u_me', sourceUid: 'u_them', newSource: 'qrcode', message: 'hello!', source: 'web' }, - }; - const legacy = protoEncode(data as any, FriendRequestSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes GroupJoin identically', () => { - const data: GroupJoin = { - groupUin: 555, field2: 1, targetUid: 'u_them', field4: 1, - field6: 1, field7: 'reason', field8: 1, field9: new Uint8Array([0xaa]), - }; - const legacy = protoEncode(data as any, GroupJoinSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - // ── action.ts coverage ───────────────────────────────────────────── - - it('encodes RoutingHead (c2c variant) identically', () => { - const data: RoutingHead = { c2c: { uin: 10001, uid: 'u_a' } }; - const legacy = protoEncode(data as any, RoutingHeadSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes RoutingHead (group variant) identically', () => { - const data: RoutingHead = { grp: { groupCode: 555n } }; - const legacy = protoEncode(data as any, RoutingHeadSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes SendMessageRequest (group with two text elements) identically', () => { - const data: SendMessageRequest = { - routingHead: { grp: { groupCode: 555n } }, - contentHead: { type: 1, subType: 1, c2cCmd: 11 }, - messageBody: { - richText: { - elems: [ - { text: { str: 'hi ' } }, - { text: { str: 'world', link: 'lnk' } }, - ], - }, - }, - clientSequence: 1, - random: 12345, - syncCookie: new Uint8Array([0xaa, 0xbb]), - via: 1, - dataStatist: 1, - multiSendSeq: 1, - }; - const legacy = protoEncode(data as any, SendMessageRequestSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes SendMessageResponse identically', () => { - const data: SendMessageResponse = { - result: 1, errMsg: 'ok', timestamp1: 1234567890, - field10: 1, groupSequence: 100, timestamp2: 1234567891, privateSequence: 200, - }; - const legacy = protoEncode(data as any, SendMessageResponseSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes MentionExtraSend identically', () => { - const data: MentionExtraSend = { type: 2, uin: 10001, field5: 1, uid: 'u_a' }; - const legacy = protoEncode(data as any, MentionExtraSendSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes MarkdownData identically', () => { - const data: MarkdownData = { content: '**bold** _italic_' }; - const legacy = protoEncode(data as any, MarkdownDataSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - // ── highway.ts coverage ──────────────────────────────────────────── - - it('encodes HttpConn0x6FF501Request (high-numbered field tag 0x501) identically', () => { - const data: HttpConn0x6FF501Request = { - httpConn: { - field1: 1, field2: 2, field3: 16, field4: 1, field6: 3, - serviceTypes: [1, 5, 10, 21], - field9: 2, field10: 9, field11: 8, ver: '1.0.1', - }, - }; - const legacy = protoEncode(data as any, HttpConn0x6FF501RequestSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes HttpConn0x6FF501Response (with repeated server infos) identically', () => { - const data: HttpConn0x6FF501Response = { - httpConn: { - sigSession: new Uint8Array([1, 2, 3]), - sessionKey: new Uint8Array([4, 5, 6]), - serverInfos: [ - { serviceType: 1, serverAddrs: [{ type: 1, ip: 0x01020304, port: 8080, area: 1 }] }, - { serviceType: 2, serverAddrs: [{ type: 1, ip: 0x05060708, port: 8081, area: 2 }] }, - ], - }, - }; - const legacy = protoEncode(data as any, HttpConn0x6FF501ResponseSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes ReqDataHighwayHead (multiple nested messages) identically', () => { - const data: ReqDataHighwayHead = { - msgBaseHead: { - version: 1, uin: '10001', command: 'PicUp.DataUp', seq: 1, retryTimes: 1, - appId: 1600001604, dataFlag: 16, commandId: 1003, - }, - msgSegHead: { - serviceId: 1, filesize: 100n, dataOffset: 50n, dataLength: 100, - retCode: 1, serviceTicket: new Uint8Array([1, 2, 3]), flag: 1, - md5: new Uint8Array([4, 5, 6]), fileMd5: new Uint8Array([7, 8, 9]), - cacheAddr: 1, cachePort: 80, - }, - bytesReqExtendInfo: new Uint8Array([0xab, 0xcd]), - timestamp: 1234567890n, - msgLoginSigHead: { loginSigType: 8, appId: 1600001604 }, - }; - const legacy = protoEncode(data as any, ReqDataHighwayHeadSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes NTV2RichMediaHighwayExt (repeated_bytes hash) identically', () => { - const data: NTV2RichMediaHighwayExt = { - fileUuid: 'uuid-1', - uKey: 'key-1', - network: { ipv4s: [{ domain: { isEnable: true, ip: '127.0.0.1' }, port: 80 }] }, - blockSize: 1048576, - hash: { fileSha1: [new Uint8Array([1, 2]), new Uint8Array([3, 4])] }, - }; - const legacy = protoEncode(data as any, NTV2RichMediaHighwayExtSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes FileUploadExt (high-numbered tags 100/200/400/600/700) identically', () => { - const data: FileUploadExt = { - unknown1: 100, - unknown2: 1, - unknown3: 1, - entry: { - busiBuff: { - busId: 102, - senderUin: 10001n, - receiverUin: 555n, - groupCode: 555n, - }, - fileEntry: { - fileSize: 12345n, - md5: new Uint8Array([0x11, 0x22]), - checkKey: new Uint8Array([0x33, 0x44]), - md5S2: new Uint8Array([0x55]), - fileId: 'file-1', - uploadKey: new Uint8Array([0x66]), - }, - clientInfo: { - clientType: 3, appId: '100', terminalType: 3, clientVer: '1.1.1', unknown: 4, - }, - fileNameInfo: { fileName: 'a.bin' }, - host: { - hosts: [ - { url: { unknown: 1, host: 'upload.qq.com' }, port: 80 }, - ], - }, - }, - unknown200: 1, - }; - const legacy = protoEncode(data as any, FileUploadExtSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - // ── oidb.ts coverage (OidbBase generic envelope) ──────────────── - - it('encodes OidbBase identically to makeOidbBaseSchema', () => { - // This is the exact pattern runOidb uses for the OIDB envelope. Proton's - // OidbBase generic interface should monomorphize to a codec that is - // byte-equivalent to the legacy makeOidbBaseSchema(InnerSchema) factory. - // The inner Body type used here is a real schema (group-list response). - const body: OidbSvcTrpcTcp0xFE5_2Response = { - groups: [ - { - groupUin: 555, - info: { - groupOwner: { uid: 'u_owner' }, - createdTime: 1234567890, memberMax: 100, memberCount: 50, - groupName: 'TestGroup', description: 'desc', question: 'q?', - announcement: 'announcement', - }, - customInfo: { remark: 'remark' }, - }, - ], - }; - const envelope = { - command: 0xFE5, - subCommand: 2, - errorCode: 1, // non-zero so it isn't proto3-omitted - body, - errorMsg: 'ok', - reserved: 1, - }; - const legacy = protoEncode(envelope as any, makeOidbBaseSchema(OidbSvcTrpcTcp0xFE5_2ResponseSchema)); - const proton = protobuf_encode>(envelope); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodeOidbEnv pass-through wrapper byte-equivalent to direct codec', () => { - // The bridge-oidb.ts module exposes encodeOidbEnv / decodeOidbEnv - // as pure pass-through wrappers around protobuf_encode/decode>. - // Proton wrapper-binds them and substitutes each call site with the - // monomorphized codec, so byte-output must match a direct call. - const body: OidbSvcTrpcTcp0xFE5_2Response = { - groups: [{ groupUin: 100, info: { groupName: 'G' } }], - }; - const env = makeOidbEnvelope(0xFE5, 2, body, false); - const viaWrapper = encodeOidbEnv(env); - const viaDirect = protobuf_encode>(env); - expect(hex(viaWrapper)).toBe(hex(viaDirect)); - - const back = decodeOidbEnv(viaWrapper); - expect(back.body?.groups?.[0]?.groupUin).toBe(100); - expect(back.body?.groups?.[0]?.info?.groupName).toBe('G'); - }); - - it('round-trips OidbBase with non-trivial nested body', () => { - const body: OidbSvcTrpcTcp0xFE5_2Response = { - groups: [{ groupUin: 100, info: { groupName: 'G' } }], - }; - const envelope: OidbBase = { - command: 0xFE5, subCommand: 2, errorCode: 1, body, errorMsg: 'ok', reserved: 1, - }; - const encoded = protobuf_encode>(envelope); - const decoded = protobuf_decode>(encoded); - expect(decoded.command).toBe(0xFE5); - expect(decoded.errorCode).toBe(1); - expect(decoded.body?.groups?.[0]?.groupUin).toBe(100); - expect(decoded.body?.groups?.[0]?.info?.groupName).toBe('G'); - }); - - // ── Documented divergence: proto3 default-value omission ──────────── - - it('proton omits default-valued numeric fields (legacy emits them)', () => { - // proto3 wire format says fields equal to their default value MUST NOT be - // emitted. Proton follows that; the legacy runtime encoder always emits. - // Either form is round-trippable through a conforming proto3 reader — the - // missing field decodes as its default. This test pins that behaviour. - const data: LongMsgSettings = { field1: 0, field2: 0, field3: 0, field4: 0 }; - const legacy = protoEncode(data as any, LongMsgSettingsSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(''); // nothing on the wire - expect(legacy.length).toBeGreaterThan(0); // legacy emits all zeros - // Legacy emits explicit zero values; a proto3-conforming reader sees them - // back when decoding. (Decoding the empty wire returns null because the - // legacy decoder treats an empty buffer as "no message at all" — that's - // also semantically equivalent to "all-default values" in proto3.) - expect(protoDecode(legacy, LongMsgSettingsSchema)).toMatchObject({ - field1: 0, field2: 0, field3: 0, field4: 0, - }); - }); - - // ── round-trip via decode ─────────────────────────────────────────── - - it('round-trips SendLongMsgResp through proton encode → legacy decode', () => { - const data: SendLongMsgResp = { result: { resId: 'rt-1' } }; - const encoded = protobuf_encode(data); - const decoded = protoDecode(encoded, SendLongMsgRespSchema); - expect(decoded?.result?.resId).toBe('rt-1'); - }); - - it('round-trips SendLongMsgResp through legacy encode → proton decode', () => { - const data: SendLongMsgResp = { result: { resId: 'rt-2' } }; - const encoded = protoEncode(data as any, SendLongMsgRespSchema); - const decoded = protobuf_decode(encoded); - expect(decoded.result?.resId).toBe('rt-2'); - }); - - // ── Group album TRPC envelopes (PR #31) ───────────────────────────── - // - // Raw TRPC packets — not OIDB-wrapped — that the group-album actions - // ship to `QunAlbum.trpc.qzone.webapp_qun_*`. Field names are mostly - // positional (`field1`/`field2`/...) because the upstream protocol - // doesn't expose semantic names; the byte-for-byte parity below is - // what guarantees the migration preserved every numbered field. - - // NOTE: every numeric/bytes field below is non-zero / non-empty — - // proton follows proto3 semantics and skips default-valued fields on - // the wire, while the legacy runtime encoder writes them all. Byte - // parity therefore only holds when no field equals its default. The - // actual production callers in `actions/group-album.ts` *do* pass - // some zero-valued fields (e.g. `field1: 0`), which means the - // post-migration packet drops a few leading zero tags — semantically - // equivalent to a proto3-conforming reader, see the explicit - // divergence test earlier in this file. - - it('encodes GetMediaListRequest (nested ReqInfo + extMap) identically', () => { - const data: GetMediaListRequest = { - field1: 1, // proto3 non-default - field2: new Uint8Array([0xab]), - field3: new Uint8Array([0xcd]), - reqInfo: { groupId: '555', albumId: 'alb-1', field3: 7, attachInfo: 'cursor', field5: 'tag' }, - traceId: '_1700000000_12345', - extMap: [{ key: 'fc-appid', value: '100' }], - }; - const legacy = protoEncode(data as any, GetMediaListRequestSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes DoQunCommentRequest (deeply nested anonymous-in-legacy schemas) identically', () => { - const data: DoQunCommentRequest = { - field1: 8527, - field2: new Uint8Array([0x01]), - field3: new Uint8Array([0x02]), - body: { - groupId: '555', - field3: 2, - reqBody: { - field1: { field3: 3, field4: 'h' }, - field2: { field1: { uin: '10001' } }, - field5: { - field1: { - field2: { - field1: 1, field2: 'a', lloc: 'lloc-x', - field4: 'b', field6: 'c', field7: 1, field8: 1, field9: 1, - field14: 1, field15: 1, field17: 1, - }, - }, - albumId: 'alb-1', - field5: 1, - }, - }, - field5: { - field2: { uin: '10001' }, - field3: { field1: 1, field2: 'hello', field3: 'd', field4: 'e', field5: 1, field6: 'f' }, - clientKey: 'ck-1', - }, - }, - traceId: '_1700000000_12345', - extMap: [{ key: 'fc-appid', value: '100' }], - }; - const legacy = protoEncode(data as any, DoQunCommentRequestSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes DoQunLikeRequest (with bigint time/batchId) identically', () => { - const data: DoQunLikeRequest = { - field1: 5495, - field2: 'h5_test', - field3: 'h5_test', - body: { - type: 2, - like: { id: '421_1_0_555|alb|42', status: 1 }, // non-default - publish: { - cellCommon: { time: 1700000000000n, feedId: '422_0_42' }, - cellUserInfo: { user: { uin: '10001' } }, - cellMedia: { albumId: 'alb', batchId: 42n }, - cellQunInfo: { qunId: '555' }, - }, - clientKey: 'ck', - }, - extMap: [{ key: 'fc-appid', value: '100' }], - }; - const legacy = protoEncode(data as any, DoQunLikeRequestSchema); - const proton = protobuf_encode(data); - expect(hex(proton)).toBe(hex(legacy)); - }); - - it('encodes DeleteMediasRequest + decodes DeleteMediasResponse identically', () => { - const req: DeleteMediasRequest = { - field1: 8694, field2: 'h5_test', field3: 'h5_test', - body: { groupId: '555', albumId: 'alb', lloc: 'lloc-x' }, - traceId: 'tr-1', - extMap: [{ key: 'fc-appid', value: '100' }], - }; - expect(hex(protobuf_encode(req))) - .toBe(hex(protoEncode(req as any, DeleteMediasRequestSchema))); - - // Response: encode with legacy, decode with proton, fields stay aligned. - const respBytes = protoEncode({ field1: 8694, field2: 10023, field3: 'no right delete' } as any, DeleteMediasResponseSchema); - const decoded = protobuf_decode(respBytes); - expect(decoded.field1).toBe(8694); - expect(decoded.field2).toBe(10023); - expect(decoded.field3).toBe('no right delete'); - }); -}); diff --git a/packages/core/tests/web-actions/cookies.test.ts b/packages/core/tests/web-actions/cookies.test.ts deleted file mode 100644 index fdf54624..00000000 --- a/packages/core/tests/web-actions/cookies.test.ts +++ /dev/null @@ -1,245 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; -import type { - OidbClientKeyResp, - OidbGetPskeyResp, -} from '../../src/bridge/proto/proton/oidb-action'; - -// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers -// — the plugin substitutes them at the call site with the inlined codec, -// so mocking them on the module object is a no-op. We mock `runOidb` -// (non-generic, untouched by proton) to return real proton-encoded bytes -// that the production-side codec then decodes. -vi.mock('../../src/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '../../src/bridge/bridge-oidb', - ); - return { - ...actual, - runOidb: vi.fn(async () => new Uint8Array()), - makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), - }; -}); - -// Mock the actual HTTP cookie fetch. -vi.mock('../../src/bridge/web/request-util', () => ({ - RequestUtil: { - HttpsGetCookies: vi.fn(async () => ({}) as Record), - }, -})); - -import * as oidb from '../../src/bridge/bridge-oidb'; -import { RequestUtil } from '../../src/bridge/web/request-util'; -import { - forceFetchClientKey, - getPSkey, - getCookies, - getSKey, - getBknFromSKey, - getCookiesStr, - getCsrfToken, - getCredentials, -} from '../../src/bridge/web-actions/cookies'; - -const bridge = { identity: { uin: '10001' } } as any; - -function resetOidbMocks() { - vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); - vi.mocked(oidb.makeOidbEnvelope).mockClear(); -} - -// Bake the encoded OidbBase bytes a test wants `runOidb` to return. -// Keeping these inline as `protobuf_encode>({body: ...})` -// — proton substitutes them with the inlined codec at this file's -// transform time, just like for production code. - -describe('cookies — forceFetchClientKey', () => { - beforeEach(() => { resetOidbMocks(); }); - - it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ - body: { clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600 } as any, - }), - ); - const out = await forceFetchClientKey(bridge); - expect(out).toEqual({ clientKey: 'ck-xyz', keyIndex: '42', expireTime: '3600' }); - }); - - it('falls back to default keyIndex/expireTime when the response omits them', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: { clientKey: 'ck' } as any }), - ); - const out = await forceFetchClientKey(bridge); - expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' }); - }); -}); - -describe('cookies — getPSkey', () => { - beforeEach(() => { resetOidbMocks(); }); - - it('folds pskeyItems into a domain → pskey Map', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ - body: { - pskeyItems: [ - { domain: 'qun.qq.com', pskey: 'psk-a' }, - { domain: 'qzone.qq.com', pskey: 'psk-b' }, - { domain: 'corrupt', pskey: '' }, - ], - } as any, - }), - ); - const { domainPskeyMap } = await getPSkey(bridge, ['qun.qq.com', 'qzone.qq.com']); - expect(domainPskeyMap.get('qun.qq.com')).toBe('psk-a'); - expect(domainPskeyMap.get('qzone.qq.com')).toBe('psk-b'); - expect(domainPskeyMap.has('corrupt')).toBe(false); // empty pskey skipped - }); -}); - -describe('cookies — getCookies', () => { - beforeEach(() => { - resetOidbMocks(); - vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); - }); - - it('builds the ptlogin2 jump URL with the right query params', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ - body: { clientKey: 'ck', keyIndex: 19 } as any, - }), - ); - vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ - p_skey: 'psk', - skey: 'sk', - }); - - const out = await getCookies(bridge, 'qun.qq.com'); - expect(out).toEqual({ p_skey: 'psk', skey: 'sk' }); - - const url = vi.mocked(RequestUtil.HttpsGetCookies).mock.calls[0]![0]; - expect(url).toContain('ssl.ptlogin2.qq.com/jump'); - expect(url).toContain('clientuin=10001'); - expect(url).toContain('clientkey=ck'); - expect(url).toContain('keyindex=19'); - }); - - it('falls back to getPSkey when p_skey is missing in the cookie response', async () => { - vi.mocked(oidb.runOidb) - .mockResolvedValueOnce( - protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), - ) - .mockResolvedValueOnce( - protobuf_encode>({ - body: { pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }] } as any, - }), - ); - vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); - - const out = await getCookies(bridge, 'qun.qq.com'); - expect(out['p_skey']).toBe('psk-from-oidb'); - }); - - it('returns whatever cookies it got if getPSkey fallback throws', async () => { - vi.mocked(oidb.runOidb) - .mockResolvedValueOnce( - protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), - ) - .mockRejectedValueOnce(new Error('pskey unavailable')); - vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' }); - - const out = await getCookies(bridge, 'qun.qq.com'); - expect(out).toEqual({ skey: 'sk' }); // no p_skey, but no throw - }); -}); - -describe('cookies — getSKey', () => { - beforeEach(() => { - resetOidbMocks(); - vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); - }); - - it('returns skey from the qzone-targeted ptlogin2 jump', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), - ); - vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' }); - expect(await getSKey(bridge)).toBe('the-skey'); - }); - - it('throws when clientKey comes back empty', async () => { - // Empty clientKey is the proto3 default; omit so it decodes back to ''. - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: {} }), - ); - await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/); - }); - - it('throws when the jump response omits skey', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), - ); - vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); - await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/); - }); -}); - -describe('cookies — pure helpers', () => { - beforeEach(() => { resetOidbMocks(); }); - - it('getBknFromSKey: deterministic djb2 truncated to 31 bits', () => { - // Two calls on the same input → same number; different input → different. - const a = getBknFromSKey('hello'); - const b = getBknFromSKey('hello'); - const c = getBknFromSKey('world'); - expect(a).toBe(b); - expect(a).not.toBe(c); - expect(a).toBeGreaterThanOrEqual(0); - expect(a).toBeLessThanOrEqual(2147483647); - }); - - it('getCookiesStr: joins cookies with "; "', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), - ); - vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); - const out = await getCookiesStr(bridge, 'qun.qq.com'); - expect(out).toBe('p_skey=p; skey=s'); - }); - - it('getCsrfToken: combines getSKey + getBknFromSKey', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), - ); - vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' }); - const csrf = await getCsrfToken(bridge); - expect(csrf).toBe(getBknFromSKey('abc')); - }); - - it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), - ); - vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); - - const out = await getCredentials(bridge, 'qun.qq.com'); - expect(out.cookies).toBe('p_skey=p; skey=s'); - expect(out.token).toBe(getBknFromSKey('p')); - expect(out.csrf_token).toBe(out.token); - }); - - it('getCredentials: token is 0 when no skey/p_skey available', async () => { - vi.mocked(oidb.runOidb) - .mockResolvedValueOnce( - protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), - ) - .mockRejectedValueOnce(new Error('no pskey')); - vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); - - const out = await getCredentials(bridge, 'qun.qq.com'); - expect(out.token).toBe(0); - expect(out.cookies).toBe(''); - }); -}); diff --git a/packages/core/tests/web-actions/group-essence.test.ts b/packages/core/tests/web-actions/group-essence.test.ts deleted file mode 100644 index 83d16992..00000000 --- a/packages/core/tests/web-actions/group-essence.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; - -vi.mock('../../src/bridge/web-actions/cookies', () => ({ - getCookies: vi.fn(async () => ({ p_skey: 'psk' })), -})); - -vi.mock('../../src/bridge/web/group-essence', () => ({ - getGroupEssenceMsg: vi.fn(async () => null), - getGroupEssenceMsgAll: vi.fn(async () => []), -})); - -import * as cookies from '../../src/bridge/web-actions/cookies'; -import * as essenceWeb from '../../src/bridge/web/group-essence'; -import { - getGroupEssence, - getGroupEssenceAll, -} from '../../src/bridge/web-actions/group-essence'; - -const bridge = {} as any; - -describe('group-essence', () => { - beforeEach(() => { - vi.mocked(cookies.getCookies).mockClear(); - vi.mocked(essenceWeb.getGroupEssenceMsg).mockReset(); - vi.mocked(essenceWeb.getGroupEssenceMsgAll).mockReset(); - }); - - it('getGroupEssence: passes pageStart + pageLimit through to the web API', async () => { - vi.mocked(essenceWeb.getGroupEssenceMsg).mockResolvedValueOnce({ - retcode: 0, - data: { is_end: true, msg_list: [{ a: 1 }] }, - } as any); - - const out = await getGroupEssence(bridge, 12345, 10, 20); - const args = vi.mocked(essenceWeb.getGroupEssenceMsg).mock.calls[0]!; - expect(args[1]).toBe('12345'); // groupCode - expect(args[2]).toBe(10); // pageStart - expect(args[3]).toBe(20); // pageLimit - expect((out as any).data.msg_list).toHaveLength(1); - }); - - it('getGroupEssence: defaults pageStart=0 + pageLimit=50', async () => { - vi.mocked(essenceWeb.getGroupEssenceMsg).mockResolvedValueOnce({ - retcode: 0, - data: { is_end: true, msg_list: [] }, - } as any); - await getGroupEssence(bridge, 12345); - const args = vi.mocked(essenceWeb.getGroupEssenceMsg).mock.calls[0]!; - expect(args[2]).toBe(0); - expect(args[3]).toBe(50); - }); - - it('getGroupEssence: falls back to an empty result envelope when the API returns null', async () => { - vi.mocked(essenceWeb.getGroupEssenceMsg).mockResolvedValueOnce(null as any); - const out = await getGroupEssence(bridge, 12345); - expect(out).toEqual({ retcode: -1, data: { is_end: true, msg_list: [] } }); - }); - - it('getGroupEssenceAll: delegates to the all-pages web helper', async () => { - vi.mocked(essenceWeb.getGroupEssenceMsgAll).mockResolvedValueOnce([ - { retcode: 0, data: { is_end: false, msg_list: [{}] } }, - { retcode: 0, data: { is_end: true, msg_list: [{}, {}] } }, - ] as any); - const out = await getGroupEssenceAll(bridge, 12345); - expect(out).toHaveLength(2); - expect(vi.mocked(essenceWeb.getGroupEssenceMsgAll).mock.calls[0]![1]).toBe('12345'); - }); -}); diff --git a/packages/core/tests/web-actions/group-honor.test.ts b/packages/core/tests/web-actions/group-honor.test.ts deleted file mode 100644 index 7b38d2bd..00000000 --- a/packages/core/tests/web-actions/group-honor.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; - -vi.mock('../../src/bridge/web-actions/cookies', () => ({ - getCookies: vi.fn(async () => ({ p_skey: 'psk' })), -})); - -vi.mock('../../src/bridge/web/group-honor', async () => { - // Keep the real WebHonorType enum so the function-under-test still - // sees the same constants as production code; only the network call - // (`getHonorListWebAPI`) is faked. - const actual = await vi.importActual('../../src/bridge/web/group-honor'); - return { - ...actual, - getHonorListWebAPI: vi.fn(async () => [] as Array), - }; -}); - -import * as cookies from '../../src/bridge/web-actions/cookies'; -import * as honorWeb from '../../src/bridge/web/group-honor'; -import { WebHonorType } from '../../src/bridge/web/group-honor'; -import { getGroupHonorInfo } from '../../src/bridge/web-actions/group-honor'; - -const bridge = {} as any; - -describe('group-honor — getGroupHonorInfo', () => { - beforeEach(() => { - vi.mocked(cookies.getCookies).mockClear(); - vi.mocked(honorWeb.getHonorListWebAPI).mockReset(); - }); - - it('TALKATIVE: calls API only for type=1, populates current_talkative + talkative_list', async () => { - vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([ - { uin: 10001, nick: 'alice', avatar: '', desc: '' }, - { uin: 10002, nick: 'bob', avatar: '', desc: '' }, - ]); - - const out = await getGroupHonorInfo(bridge, 12345, WebHonorType.TALKATIVE); - expect(honorWeb.getHonorListWebAPI).toHaveBeenCalledTimes(1); - expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![2]).toBe(1); - expect(out.current_talkative).toEqual({ uin: 10001, nick: 'alice', avatar: '', desc: '' }); - expect(out.talkative_list).toHaveLength(2); - expect(out.performer_list).toEqual([]); - expect(out.legend_list).toEqual([]); - expect(out.emotion_list).toEqual([]); - }); - - it('TALKATIVE with empty list: current_talkative stays null', async () => { - vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([]); - const out = await getGroupHonorInfo(bridge, 12345, WebHonorType.TALKATIVE); - expect(out.current_talkative).toBeNull(); - expect(out.talkative_list).toEqual([]); - }); - - it('PERFORMER: dispatches API with type=2 only', async () => { - vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([{ uin: 1, nick: 'p', avatar: '', desc: '' }]); - const out = await getGroupHonorInfo(bridge, 12345, WebHonorType.PERFORMER); - expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![2]).toBe(2); - expect(out.performer_list).toHaveLength(1); - expect(out.talkative_list).toEqual([]); - }); - - it('LEGEND: type=3', async () => { - vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([]); - await getGroupHonorInfo(bridge, 12345, WebHonorType.LEGEND); - expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![2]).toBe(3); - }); - - it('EMOTION: type=6', async () => { - vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([]); - await getGroupHonorInfo(bridge, 12345, WebHonorType.EMOTION); - expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![2]).toBe(6); - }); - - it('ALL: fetches talkative + performer + legend + emotion (4 calls)', async () => { - vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValue([]); - await getGroupHonorInfo(bridge, 12345, WebHonorType.ALL); - expect(honorWeb.getHonorListWebAPI).toHaveBeenCalledTimes(4); - expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls.map(c => c[2])).toEqual([1, 2, 3, 6]); - }); - - it('groupId is stringified to groupCode', async () => { - vi.mocked(honorWeb.getHonorListWebAPI).mockResolvedValueOnce([]); - await getGroupHonorInfo(bridge, 99999, WebHonorType.TALKATIVE); - expect(vi.mocked(honorWeb.getHonorListWebAPI).mock.calls[0]![1]).toBe('99999'); - }); -}); diff --git a/packages/core/tests/web-actions/group-notice.test.ts b/packages/core/tests/web-actions/group-notice.test.ts deleted file mode 100644 index 268808a4..00000000 --- a/packages/core/tests/web-actions/group-notice.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; - -vi.mock('../../src/bridge/web-actions/cookies', () => ({ - getCookies: vi.fn(async () => ({ p_skey: 'psk' })), -})); - -vi.mock('../../src/bridge/web/group-notice', () => ({ - setGroupNoticeWebAPI: vi.fn(async () => ({ ec: 0 })), - getGroupNoticeWebAPI: vi.fn(async () => ({ feeds: {} })), - uploadGroupNoticeImage: vi.fn(async () => null), - deleteGroupNotice: vi.fn(async () => true), -})); - -import * as cookies from '../../src/bridge/web-actions/cookies'; -import * as noticeWeb from '../../src/bridge/web/group-notice'; -import { - sendGroupNotice, - getGroupNotice, - deleteGroupNoticeByFid, -} from '../../src/bridge/web-actions/group-notice'; - -const bridge = {} as any; - -describe('group-notice — sendGroupNotice', () => { - beforeEach(() => { - vi.mocked(cookies.getCookies).mockClear(); - vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockReset(); - vi.mocked(noticeWeb.uploadGroupNoticeImage).mockReset(); - }); - - it('text-only: dispatches with empty picId and default image dims (540x300)', async () => { - vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({ ec: 0 } as any); - await sendGroupNotice(bridge, 12345, 'hello'); - - expect(noticeWeb.uploadGroupNoticeImage).not.toHaveBeenCalled(); - const args = vi.mocked(noticeWeb.setGroupNoticeWebAPI).mock.calls[0]!; - expect(args[1]).toBe('12345'); // groupCode - expect(args[2]).toBe('hello'); // content - expect(args[3]).toBe(0); // pinned default - expect(args[4]).toBe(1); // type default - expect(args[7]).toBe(1); // confirm_required default - expect(args[8]).toBe(''); // picId - expect(args[9]).toBe(540); // imgWidth default - expect(args[10]).toBe(300); // imgHeight default - }); - - it('with options: forwards pinned / type / confirm_required overrides', async () => { - vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({ ec: 0 } as any); - await sendGroupNotice(bridge, 12345, 'pinned!', { - pinned: 1, - type: 2, - confirm_required: 0, - }); - const args = vi.mocked(noticeWeb.setGroupNoticeWebAPI).mock.calls[0]!; - expect(args[3]).toBe(1); - expect(args[4]).toBe(2); - expect(args[7]).toBe(0); - }); - - it('with http image: fetches bytes, uploads, threads pic info into the post', async () => { - const realFetch = global.fetch; - global.fetch = vi.fn(async () => ({ - ok: true, - arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer, - })) as any; - - vi.mocked(noticeWeb.uploadGroupNoticeImage).mockResolvedValueOnce({ - id: 'pic-xyz', width: 1024, height: 768, - } as any); - vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({ ec: 0 } as any); - - await sendGroupNotice(bridge, 12345, 'image notice', { image: 'https://example.com/x.png' }); - - expect(global.fetch).toHaveBeenCalledOnce(); - expect(noticeWeb.uploadGroupNoticeImage).toHaveBeenCalledOnce(); - const args = vi.mocked(noticeWeb.setGroupNoticeWebAPI).mock.calls[0]!; - expect(args[8]).toBe('pic-xyz'); - expect(args[9]).toBe(1024); - expect(args[10]).toBe(768); - - global.fetch = realFetch; - }); - - it('image fetch failure: throws "Failed to download image"', async () => { - const realFetch = global.fetch; - global.fetch = vi.fn(async () => ({ ok: false, status: 503 })) as any; - await expect(sendGroupNotice(bridge, 12345, 'x', { image: 'https://bad' })) - .rejects.toThrow(/Failed to download image: 503/); - global.fetch = realFetch; - }); - - it('throws when the web API returns non-zero ec', async () => { - vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({ - ec: 42, em: 'permission denied', - } as any); - await expect(sendGroupNotice(bridge, 12345, 'x')) - .rejects.toThrow(/permission denied/); - }); - - it('throws with a generic message when ec≠0 and em is missing', async () => { - vi.mocked(noticeWeb.setGroupNoticeWebAPI).mockResolvedValueOnce({ ec: 7 } as any); - await expect(sendGroupNotice(bridge, 12345, 'x')) - .rejects.toThrow(/Cookie过期或权限不足/); - }); -}); - -describe('group-notice — getGroupNotice', () => { - beforeEach(() => { vi.mocked(noticeWeb.getGroupNoticeWebAPI).mockReset(); }); - - it('flattens feeds into OneBot-shaped notice list', async () => { - vi.mocked(noticeWeb.getGroupNoticeWebAPI).mockResolvedValueOnce({ - feeds: { - f1: { - fid: 'f1', u: 10001, pubt: 1700000000, - msg: { text: 'first', pics: [{ id: 'p1', h: 100, w: 200 }] }, - settings: {}, read_num: 5, - } as any, - f2: { - fid: 'f2', u: 10002, pubt: 1700000100, - msg: { text: 'second' } as any, - settings: {}, read_num: 0, - } as any, - }, - } as any); - - const out = await getGroupNotice(bridge, 12345); - expect(out).toHaveLength(2); - expect(out[0]!.notice_id).toBe('f1'); - expect(out[0]!.message.text).toBe('first'); - expect(out[0]!.message.image).toEqual([{ id: 'p1', height: 100, width: 200 }]); - expect(out[0]!.message.images).toEqual(out[0]!.message.image); // alias - expect(out[1]!.message.image).toEqual([]); // no pics → empty - }); - - it('throws when the underlying web API returns null', async () => { - vi.mocked(noticeWeb.getGroupNoticeWebAPI).mockResolvedValueOnce(null as any); - await expect(getGroupNotice(bridge, 12345)).rejects.toThrow(/获取公告失败/); - }); - - it('returns an empty array when feeds is empty', async () => { - vi.mocked(noticeWeb.getGroupNoticeWebAPI).mockResolvedValueOnce({ feeds: {} } as any); - expect(await getGroupNotice(bridge, 12345)).toEqual([]); - }); -}); - -describe('group-notice — deleteGroupNoticeByFid', () => { - it('delegates to deleteGroupNotice with cookieObject + groupCode + fid', async () => { - vi.mocked(noticeWeb.deleteGroupNotice).mockResolvedValueOnce(true); - const ok = await deleteGroupNoticeByFid(bridge, 12345, 'fid-abc'); - expect(ok).toBe(true); - const args = vi.mocked(noticeWeb.deleteGroupNotice).mock.calls[0]!; - expect(args[1]).toBe('12345'); - expect(args[2]).toBe('fid-abc'); - }); -}); diff --git a/packages/core/tests/wire.test.ts b/packages/core/tests/wire.test.ts deleted file mode 100644 index 7e257204..00000000 --- a/packages/core/tests/wire.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { - WireType, - WireMessage, - decodeVarint, - encodeVarint, - encodeKey, - fieldAsInt32, - fieldAsUint32, - fieldAsString, - fieldAsBool, -} from '../src/protobuf/wire'; - -// Helper to build bytes from number array -function bytes(...vals: number[]): Uint8Array { - return new Uint8Array(vals); -} - -describe('decodeVarint', () => { - it('decodes single-byte varint', () => { - const result = decodeVarint(bytes(0x05), 0); - expect(result).toEqual([5n, 1]); - }); - - it('decodes zero', () => { - const result = decodeVarint(bytes(0x00), 0); - expect(result).toEqual([0n, 1]); - }); - - it('decodes multi-byte varint (300)', () => { - // 300 = 0b100101100 => 0xAC 0x02 - const result = decodeVarint(bytes(0xac, 0x02), 0); - expect(result).toEqual([300n, 2]); - }); - - it('decodes with offset', () => { - const result = decodeVarint(bytes(0xff, 0x01), 1); - expect(result).toEqual([1n, 1]); - }); - - it('returns null on empty data', () => { - const result = decodeVarint(bytes(), 0); - expect(result).toBeNull(); - }); -}); - -describe('encodeVarint', () => { - it('encodes small number', () => { - const out: number[] = []; - encodeVarint(5, out); - expect(out).toEqual([5]); - }); - - it('encodes 300', () => { - const out: number[] = []; - encodeVarint(300, out); - expect(out).toEqual([0xac, 0x02]); - }); - - it('encodes bigint', () => { - const out: number[] = []; - encodeVarint(300n, out); - expect(out).toEqual([0xac, 0x02]); - }); - - it('roundtrips', () => { - for (const val of [0, 1, 127, 128, 300, 65535, 2147483647]) { - const out: number[] = []; - encodeVarint(val, out); - const [decoded] = decodeVarint(new Uint8Array(out), 0)!; - expect(Number(decoded)).toBe(val); - } - }); -}); - -describe('encodeKey', () => { - it('encodes field 1 varint', () => { - const out: number[] = []; - encodeKey(1, WireType.Varint, out); - expect(out).toEqual([0x08]); // (1 << 3) | 0 = 8 - }); - - it('encodes field 2 length-delimited', () => { - const out: number[] = []; - encodeKey(2, WireType.LengthDelimited, out); - expect(out).toEqual([0x12]); // (2 << 3) | 2 = 18 - }); -}); - -describe('WireMessage', () => { - // Build a simple protobuf: field 1 = varint 150, field 2 = string "testing" - function buildSimpleMessage(): Uint8Array { - const out: number[] = []; - // field 1, varint = 150 - encodeKey(1, WireType.Varint, out); - encodeVarint(150, out); - // field 2, string = "testing" - encodeKey(2, WireType.LengthDelimited, out); - const str = new TextEncoder().encode('testing'); - encodeVarint(str.length, out); - out.push(...str); - return new Uint8Array(out); - } - - it('decodes empty data returns null', () => { - expect(WireMessage.decode(new Uint8Array(0))).toBeNull(); - }); - - it('decodes varint field', () => { - const msg = WireMessage.decode(buildSimpleMessage()); - expect(msg).not.toBeNull(); - expect(msg!.getUint32(1)).toBe(150); - }); - - it('decodes string field', () => { - const msg = WireMessage.decode(buildSimpleMessage()); - expect(msg).not.toBeNull(); - expect(msg!.getString(2)).toBe('testing'); - }); - - it('returns null for missing fields', () => { - const msg = WireMessage.decode(buildSimpleMessage()); - expect(msg!.getUint32(99)).toBeNull(); - expect(msg!.getString(99)).toBeNull(); - }); - - it('has() works', () => { - const msg = WireMessage.decode(buildSimpleMessage()); - expect(msg!.has(1)).toBe(true); - expect(msg!.has(2)).toBe(true); - expect(msg!.has(3)).toBe(false); - }); - - it('decodes nested message', () => { - const inner: number[] = []; - encodeKey(1, WireType.Varint, inner); - encodeVarint(42, inner); - - const outer: number[] = []; - encodeKey(3, WireType.LengthDelimited, outer); - encodeVarint(inner.length, outer); - outer.push(...inner); - - const msg = WireMessage.decode(new Uint8Array(outer)); - const nested = msg!.getMessage(3); - expect(nested).not.toBeNull(); - expect(nested!.getUint32(1)).toBe(42); - }); - - it('handles repeated fields', () => { - const out: number[] = []; - for (const v of [10, 20, 30]) { - encodeKey(1, WireType.Varint, out); - encodeVarint(v, out); - } - const msg = WireMessage.decode(new Uint8Array(out)); - const vals = msg!.getRepeatedVarint(1); - expect(vals.map(Number)).toEqual([10, 20, 30]); - }); - - it('field helpers work correctly', () => { - const out: number[] = []; - encodeKey(1, WireType.Varint, out); - encodeVarint(1, out); // bool true - encodeKey(2, WireType.Varint, out); - encodeVarint(0xFFFFFFFF, out); // uint32 max - - const msg = WireMessage.decode(new Uint8Array(out))!; - const f1 = msg.field(1)!; - const f2 = msg.field(2)!; - - expect(fieldAsBool(f1)).toBe(true); - expect(fieldAsUint32(f2)).toBe(0xFFFFFFFF); - }); -}); diff --git a/packages/core/vite.config.ts b/packages/core/vite.config.ts index 79cefc18..f7cd92a4 100644 --- a/packages/core/vite.config.ts +++ b/packages/core/vite.config.ts @@ -20,11 +20,14 @@ const rootPkg = JSON.parse( // vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators. const toPosix = (p: string) => p.replace(/\\/g, '/'); -// `@snowluma/websocket` is bundled (it's an in-tree TS workspace package), so -// it must NOT be marked external. Only Node builtins stay external. +// `@snowluma/websocket` and `@snowluma/sqlite` are bundled — they're +// in-tree TS workspace wrappers that route their native `.node` +// addons through `dist/native/`. Only Node builtins stay external; +// the actual `better-sqlite3` JS wrapper is pulled in via the +// `@snowluma/sqlite` re-export and bundled into `index.mjs`. const external: string[] = []; -const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat(); +const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat(); const runtimeSrc = toPosix(runtimeDir); const nativeSrc = toPosix(nativeDir); @@ -41,10 +44,22 @@ const runtimeDistFiles = ['package.json', ]; // Native binaries shipped for the selected target: -// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux). -// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms). +// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux). +// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms). +// * `better-sqlite3-v-*.node` – SQLite native binding consumed +// by @snowluma/sqlite. Two ABIs +// vendored side-by-side +// (v127 = Node 22 LTS, v137 = +// Node 24) so the runtime can +// pick whichever matches the +// host's `process.versions.modules`. +// Vendored via +// `tools/fetch-sqlite-prebuilts.mjs` +// from WiseLibs's prebuild releases. +const SQLITE_ABIS = ['v127', 'v137']; const nativeFiles = [ `websocket-${targetTriple}.node`, + ...SQLITE_ABIS.map((abi) => `better-sqlite3-${abi}-${targetTriple}.node`), ...(targetPlatform === 'win32' ? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`] : []), @@ -125,7 +140,27 @@ const BaseConfig = (source_map: boolean = false) => defineConfig({ fileName: (_, entryName) => `${entryName}.mjs` }, rollupOptions: { - external: [...nodeModules, ...external] + external: [...nodeModules, ...external], + output: { + // better-sqlite3's JS wrapper is pure CJS — its `require('fs')` / + // `require('path')` / `require('bindings')` calls get inlined into + // the ESM bundle as `__require("fs")` shims by rolldown. Those + // shims gate on `typeof require !== "undefined"`, which is true + // in CJS but FALSE in our `.mjs` output, so they fall through to + // a runtime `throw Error("Calling \`require\` ... in an environment + // that doesn't expose the \`require\` function.")` on first call — + // crashing the launcher immediately. + // + // Defining a module-scope `require` via `createRequire(import.meta.url)` + // at the very top of the bundle satisfies the `typeof` check, and + // the shim then transparently delegates every inlined CJS require + // to the real CJS loader. Node 18+ ships `createRequire` in the + // `node:module` builtin, so this is supported on every target. + banner: [ + "import { createRequire as __snowlumaCreateRequire } from 'node:module';", + "const require = __snowlumaCreateRequire(import.meta.url);", + ].join('\n'), + }, }, // Emit to monorepo root dist/ so the existing release pipeline keeps working. outDir: distDir, diff --git a/packages/onebot/bench/send.bench.ts b/packages/onebot/bench/send.bench.ts new file mode 100644 index 00000000..aaf68977 --- /dev/null +++ b/packages/onebot/bench/send.bench.ts @@ -0,0 +1,123 @@ +// Send-chain micro-benchmark (RoadMap #5). +// +// Measured paths: +// 1. `parseMessage` — OneBot input (CQ string / segment array) → +// MessageElement[]. The parse cost only. +// 2. `buildSendElems` — MessageElement[] → wire-proto Elem[]. The +// transform cost (skipped: image/video/record because they hit +// OIDB upload + need a Bridge; we only measure text-family). +// 3. `messageStore.storeMeta` — single SQLite write per send. The +// per-send DB cost. +// 4. `messageStore.storeEvent` — synthetic self-sent event store. +// Bigger DB write (includes JSON payload). +// +// Run via: pnpm -F @snowluma/onebot bench +// +// Output is `tinybench` ops/sec. Run before AND after a perf commit. + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { bench, describe } from 'vitest'; +import { parseMessage } from '../src/message-parser'; +import { MessageStore } from '../src/message-store'; +import type { JsonObject } from '@snowluma/common/json'; + +// ─── parseMessage inputs ─── + +const CQ_TEXT = 'hello world from bench'; +const CQ_MIXED = '[CQ:at,qq=123456] hello [CQ:face,id=76] world [CQ:reply,id=4242]'; + +const SEGMENTS_TEXT = [ + { type: 'text', data: { text: 'hello world from bench' } }, +]; +const SEGMENTS_MIXED = [ + { type: 'at', data: { qq: '123456' } }, + { type: 'text', data: { text: ' hello ' } }, + { type: 'face', data: { id: 76 } }, + { type: 'text', data: { text: ' world ' } }, + { type: 'reply', data: { id: 4242 } }, +]; + +// ─── messageStore setup ─── + +function makeMessageStore(): MessageStore { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-bench-send-')); + return new MessageStore(path.join(dir, 'messages.db')); +} + +const store = makeMessageStore(); + +const META = { + isGroup: true, + targetId: 123456789, + sequence: 1000, + eventName: 'message.group', + clientSequence: 12345, + random: 67890, + timestamp: 1710000000, +}; + +const SAMPLE_EVENT: JsonObject = { + time: 1710000000, + self_id: 10001, + post_type: 'message_sent', + message_type: 'group', + sub_type: 'normal', + message_id: 999999, + message_seq: 1000, + group_id: 123456789, + user_id: 10001, + message: [{ type: 'text', data: { text: 'hello world' } }], + raw_message: 'hello world', + font: 0, + sender: { user_id: 10001, nickname: '', sex: 'unknown', age: 0 }, +}; + +// ─── Benches ─── + +describe('parseMessage — OneBot input → MessageElement[]', () => { + bench('CQ string (text only)', async () => { + await parseMessage(CQ_TEXT, false); + }); + bench('CQ string (mixed 4 segments)', async () => { + await parseMessage(CQ_MIXED, false); + }); + bench('segment array (text only)', async () => { + await parseMessage(SEGMENTS_TEXT as any, false); + }); + bench('segment array (5 segments)', async () => { + await parseMessage(SEGMENTS_MIXED as any, false); + }); +}); + +describe('messageStore — SQLite writes per send', () => { + // Use a monotonically-incrementing messageId so each call hits the + // upsert path uniquely; otherwise we'd be testing the ON-CONFLICT + // branch which is a different cost profile. + let id1 = 100_000; + let id2 = 200_000; + bench('storeMeta', () => { + store.storeMeta(id1++, META); + }); + bench('storeEvent (JSON payload ~250 bytes)', () => { + store.storeEvent(id2++, true, META.targetId, META.sequence, META.eventName, SAMPLE_EVENT); + }); +}); + +describe('messageStore — read paths', () => { + // Seed a small set of records so findEvent / findMeta have hits. + for (let i = 0; i < 100; i++) { + store.storeMeta(500_000 + i, META); + store.storeEvent(600_000 + i, true, META.targetId, META.sequence + i, META.eventName, SAMPLE_EVENT); + } + bench('findMeta (hit)', () => { + store.findMeta(500_050); + }); + bench('findMeta (miss)', () => { + store.findMeta(9_999_999); + }); + bench('findEvent (hit, JSON.parse on read)', () => { + store.findEvent(600_050); + }); +}); diff --git a/packages/onebot/package.json b/packages/onebot/package.json new file mode 100644 index 00000000..a08313bf --- /dev/null +++ b/packages/onebot/package.json @@ -0,0 +1,105 @@ +{ + "name": "@snowluma/onebot", + "version": "1.9.1", + "private": true, + "type": "module", + "description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis..method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/'` collapses to `import { … } from '@snowluma/onebot/'`.", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./manager": { + "types": "./src/manager.ts", + "default": "./src/manager.ts" + }, + "./instance": { + "types": "./src/instance.ts", + "default": "./src/instance.ts" + }, + "./instance-context": { + "types": "./src/instance-context.ts", + "default": "./src/instance-context.ts" + }, + "./api-handler": { + "types": "./src/api-handler.ts", + "default": "./src/api-handler.ts" + }, + "./config": { + "types": "./src/config.ts", + "default": "./src/config.ts" + }, + "./types": { + "types": "./src/types.ts", + "default": "./src/types.ts" + }, + "./message-id": { + "types": "./src/message-id.ts", + "default": "./src/message-id.ts" + }, + "./message-parser": { + "types": "./src/message-parser.ts", + "default": "./src/message-parser.ts" + }, + "./message-store": { + "types": "./src/message-store.ts", + "default": "./src/message-store.ts" + }, + "./media-store": { + "types": "./src/media-store.ts", + "default": "./src/media-store.ts" + }, + "./media-indexer": { + "types": "./src/media-indexer.ts", + "default": "./src/media-indexer.ts" + }, + "./media-url-resolver": { + "types": "./src/media-url-resolver.ts", + "default": "./src/media-url-resolver.ts" + }, + "./event-filter": { + "types": "./src/event-filter.ts", + "default": "./src/event-filter.ts" + }, + "./event-pipeline": { + "types": "./src/event-pipeline.ts", + "default": "./src/event-pipeline.ts" + }, + "./event-converter": { + "types": "./src/event-converter/index.ts", + "default": "./src/event-converter/index.ts" + }, + "./event-converter/utils": { + "types": "./src/event-converter/utils.ts", + "default": "./src/event-converter/utils.ts" + }, + "./instance-rkey": { + "types": "./src/instance-rkey.ts", + "default": "./src/instance-rkey.ts" + } + }, + "scripts": { + "test": "vitest run", + "bench": "vitest bench --run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@snowluma/bridge": "workspace:*", + "@snowluma/common": "workspace:*", + "@snowluma/core": "workspace:*", + "@snowluma/proto-defs": "workspace:*", + "@snowluma/proton": "workspace:*", + "@snowluma/sqlite": "workspace:*", + "@snowluma/websocket": "workspace:*" + }, + "devDependencies": { + "@hono/node-server": "^1.19.14", + "@types/node": "^24.12.2", + "hono": "^4.12.14", + "typescript": "catalog:", + "vite": "catalog:", + "vitest": "^4.1.4" + } +} diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/onebot/src/actions/extended.ts similarity index 91% rename from packages/core/src/onebot/actions/extended.ts rename to packages/onebot/src/actions/extended.ts index 3935872d..aae39bca 100644 --- a/packages/core/src/onebot/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1,12 +1,8 @@ -import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { asMessage, asNumber, asString, asBoolean } from '../api-handler'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { asBoolean, asMessage, asNumber, asString } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; import { RETCODE, failedResponse, okResponse } from '../types'; -// Bounded download for the OneBot `download_file` action. An authenticated -// client could otherwise hand us a multi-GB URL (or chunked response with -// no Content-Length) and OOM the bot — `await response.arrayBuffer()` -// happily allocates the whole payload before any size check fires. const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB const DOWNLOAD_FILE_TIMEOUT_MS = 60_000; @@ -92,7 +88,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userId = asNumber(params.user_id); const times = asNumber(params.times) || 1; if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.bridge.sendLike(userId, times); + await ctx.bridge.apis.interaction.sendLike(userId, times); return okResponse(); }); @@ -100,7 +96,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userId = asNumber(params.user_id); const targetId = asNumber(params.target_id) || undefined; if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.sendFriendPoke(userId, targetId); + await ctx.bridge.apis.interaction.sendPoke(false, userId, targetId); return okResponse(); }); @@ -108,7 +104,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const groupId = asNumber(params.group_id); const userId = asNumber(params.user_id); if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.sendGroupPoke(groupId, userId); + await ctx.bridge.apis.interaction.sendPoke(true, groupId, userId); return okResponse(); }); @@ -117,9 +113,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userId = asNumber(params.user_id); if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); if (groupId) { - await ctx.sendGroupPoke(groupId, userId); + await ctx.bridge.apis.interaction.sendPoke(true, groupId, userId); } else { - await ctx.sendFriendPoke(userId); + await ctx.bridge.apis.interaction.sendPoke(false, userId); } return okResponse(); }); @@ -150,7 +146,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const essenceDataAll = await ctx.bridge.getGroupEssenceAll(groupId); + const essenceDataAll = await ctx.bridge.apis.web.getEssenceAll(groupId); const allMsgs = essenceDataAll.flatMap((res: any) => res.data?.msg_list || []); @@ -181,7 +177,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); } - await ctx.bridge.setGroupReaction(meta.targetId, meta.sequence, code, isSet); + await ctx.bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, code, isSet); return okResponse(); }); @@ -221,7 +217,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); } - await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence); + await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence); return okResponse(); }); @@ -241,7 +237,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session'); } - await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence); + await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence); return okResponse(); }); @@ -260,9 +256,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } if (meta.isGroup) { - await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence); + await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence); } else { - await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence); + await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence); } return okResponse(); }); @@ -311,7 +307,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1, }; - await ctx.bridge.sendGroupNotice(groupId, content, options); + await ctx.bridge.apis.web.sendNotice(groupId, content, options); return okResponse(); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -324,7 +320,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const notices = await ctx.bridge.getGroupNotice(groupId); + const notices = await ctx.bridge.apis.web.getNotice(groupId); return okResponse(notices); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -341,7 +337,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const success = await ctx.bridge.deleteGroupNotice(groupId, fid); + const success = await ctx.bridge.apis.web.deleteNotice(groupId, fid); if (success) { return okResponse(); } else { @@ -487,7 +483,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const cookies = await ctx.bridge.getCookiesStr(domain); + const cookies = await ctx.bridge.apis.web.getCookiesStr(domain); return okResponse({ cookies }); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -497,7 +493,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_csrf_token', async () => { try { - const token = await ctx.bridge.getCsrfToken(); + const token = await ctx.bridge.apis.web.getCsrfToken(); return okResponse({ token }); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -509,7 +505,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const creds = await ctx.bridge.getCredentials(domain); + const creds = await ctx.bridge.apis.web.getCredentials(domain); return okResponse(creds); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -544,7 +540,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (params.remark === undefined) { return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); } - await ctx.bridge.setFriendRemark(userId, asString(params.remark)); + await ctx.bridge.apis.friend.setRemark(userId, asString(params.remark)); return okResponse(); }); @@ -554,7 +550,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (params.remark === undefined) { return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); } - await ctx.bridge.setGroupRemark(groupId, asString(params.remark)); + await ctx.bridge.apis.groupAdmin.setRemark(groupId, asString(params.remark)); return okResponse(); }); @@ -577,18 +573,10 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_group_file_system_info', async (params) => { const groupId = asNumber(params.group_id); if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (ctx.getGroupFileCount) { - const info = await ctx.getGroupFileCount(groupId); - return okResponse({ - file_count: info.fileCount, - limit_count: info.maxCount, - used_space: 0, - total_space: 10737418240, - }); - } + const info = await ctx.bridge.apis.groupFile.getCount(groupId); return okResponse({ - file_count: 0, - limit_count: 10000, + file_count: info.fileCount, + limit_count: info.maxCount, used_space: 0, total_space: 10737418240, }); @@ -665,7 +653,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setProfile(nickname, personalNote); + await ctx.bridge.apis.profile.setProfile(nickname, personalNote); return okResponse(); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -685,7 +673,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setOnlineStatus(status, extStatus, batteryStatus); + await ctx.bridge.apis.profile.setOnlineStatus(status, extStatus, batteryStatus); return okResponse(); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -703,7 +691,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const wording = asString(params.wording); if (!faceId) return failedResponse(RETCODE.BAD_REQUEST, 'face_id is required'); try { - await ctx.bridge.setDiyOnlineStatus(faceId, wording, faceType); + await ctx.bridge.apis.profile.setDiyOnlineStatus(faceId, wording, faceType); return okResponse(); } catch (err) { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); @@ -716,7 +704,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { // OneBot dialects clients use in the wild. const fetchFilteredGroupRequests = async () => { try { - return await ctx.bridge.fetchGroupRequests(true); + return await ctx.bridge.apis.contacts.fetchGroupRequests(true); } catch { return []; } @@ -802,7 +790,10 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const data = await ctx.getProfileLike(userId, start, count); + // getLike treats falsy userId as "self" (it does `isSelf = !userId` + // internally), so passing 0 or undefined is equivalent — matches the + // old `ctx.getProfileLike(userId, start, count)` wrapper exactly. + const data = await ctx.bridge.apis.profile.getLike(userId, start, count); return okResponse(data); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -812,7 +803,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('fetch_custom_face', async (params) => { const count = asNumber(params.count) || 10; try { - const urls = await ctx.bridge.fetchCustomFace(count); + const urls = await ctx.bridge.apis.profile.fetchCustomFace(count); return okResponse(urls); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -826,7 +817,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { const meta = ctx.getMessageMeta(messageId); if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message'); - const result = await ctx.bridge.getEmojiLikes(meta.targetId, meta.sequence, emojiId); + const result = await ctx.bridge.apis.interaction.getEmojiLikes(meta.targetId, meta.sequence, emojiId); return okResponse({ emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })) }); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -843,7 +834,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { const meta = ctx.getMessageMeta(messageId); if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message'); - const result = await ctx.bridge.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie); + const result = await ctx.bridge.apis.interaction.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie); return okResponse({ result: 0, errMsg: '', @@ -892,7 +883,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const data = await ctx.bridge.getGroupAtAllRemain(groupId); + const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(groupId); return okResponse(data); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -902,7 +893,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_unidirectional_friend_list', async () => { try { - const data = await ctx.bridge.getUnidirectionalFriendList(); + const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList(); return okResponse(data); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -918,7 +909,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setSelfLongNick(longNick); + await ctx.bridge.apis.profile.setSelfLongNick(longNick); return okResponse({}); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -939,7 +930,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setAvatar(file); + await ctx.bridge.apis.profile.setAvatar(file); return okResponse(); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -961,7 +952,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setInputStatus(userId, eventType); + await ctx.bridge.apis.profile.setInputStatus(userId, eventType); return okResponse({}); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -979,7 +970,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const translated = await ctx.bridge.translateEn2Zh(words); + const translated = await ctx.bridge.apis.misc.translateEn2Zh(words); return okResponse({ words: translated }); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -987,7 +978,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { }); h.registerAction('get_clientkey', async () => { - const clientKeyInfo = await ctx.bridge.forceFetchClientKey(); + const clientKeyInfo = await ctx.bridge.apis.web.forceFetchClientKey(); if (!clientKeyInfo.clientKey) { return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error'); } @@ -1003,12 +994,12 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const data = await ctx.bridge.getMiniAppArk( - String(type), - String(title), - String(desc), - String(picUrl), - String(jumpUrl) + const data = await ctx.bridge.apis.misc.getMiniAppArk( + String(type), + String(title), + String(desc), + String(picUrl), + String(jumpUrl) ); return okResponse(data); } catch (e) { @@ -1029,12 +1020,12 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - const data = await ctx.bridge.clickInlineKeyboardButton( - groupId, - botAppid, - String(buttonId), - String(callbackData), - msgSeq + const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton( + groupId, + botAppid, + String(buttonId), + String(callbackData), + msgSeq ); return okResponse(data); } catch (e) { @@ -1051,7 +1042,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.sendGroupSign(groupId); + await ctx.bridge.apis.misc.sendGroupSign(groupId); return okResponse({}); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -1146,7 +1137,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !folderId) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required'); } - await ctx.bridge.deleteGroupFileFolder(groupId, folderId); + await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId); return okResponse(); }); @@ -1174,18 +1165,18 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); } }; - h.registerAction('set_group_todo', handleGroupTodo((g, s) => ctx.bridge.setGroupTodo(g, s))); - h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.completeGroupTodo(g, s))); - h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.cancelGroupTodo(g, s))); + h.registerAction('set_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.setGroupTodo(g, BigInt(s)))); + h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.completeGroupTodo(g, BigInt(s)))); + h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.cancelGroupTodo(g, BigInt(s)))); // --- User online/ext status (napcat: nc_get_user_status) --- h.registerAction('nc_get_user_status', async (params) => { const userId = asNumber(params.user_id); if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - const status = await ctx.bridge.getStrangerStatus(userId); + const status = await ctx.bridge.apis.extras.getStrangerStatus(userId); if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status'); - return okResponse(status); + return okResponse({ ...status }); }); // --- AI voice (oidb 0x929D / 0x929B) --- @@ -1195,7 +1186,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const chatType = asNumber(params.chat_type) || 1; if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); try { - const list = await ctx.bridge.fetchAiVoiceList(groupId, chatType); + const list = await ctx.bridge.apis.extras.fetchAiVoiceList(groupId, chatType); return okResponse(list.map((cat) => ({ type: cat.category, characters: cat.voices.map((v) => ({ @@ -1218,8 +1209,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); } try { - const node = await ctx.bridge.fetchAiVoice(groupId, character, text, chatType); - const url = await ctx.bridge.fetchGroupPttUrlByNode(groupId, node); + const node = await ctx.bridge.apis.extras.fetchAiVoice(groupId, character, text, chatType); + const url = await ctx.bridge.apis.groupFile.getPttUrl(groupId, node); return okResponse(url); } catch (err) { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); @@ -1238,7 +1229,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); } try { - await ctx.bridge.fetchAiVoice(groupId, character, text, chatType); + await ctx.bridge.apis.extras.fetchAiVoice(groupId, character, text, chatType); return okResponse({ message_id: 0 }); } catch (err) { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); diff --git a/packages/core/src/onebot/actions/friend.ts b/packages/onebot/src/actions/friend.ts similarity index 95% rename from packages/core/src/onebot/actions/friend.ts rename to packages/onebot/src/actions/friend.ts index 4ea7d205..7e638c99 100644 --- a/packages/core/src/onebot/actions/friend.ts +++ b/packages/onebot/src/actions/friend.ts @@ -24,7 +24,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userId = asNumber(params.user_id); const block = asBoolean(params.block, false); if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.handleDeleteFriend(userId, block); + await ctx.bridge.apis.friend.delete(userId, block); return okResponse(); }); } diff --git a/packages/core/src/onebot/actions/group-admin.ts b/packages/onebot/src/actions/group-admin.ts similarity index 85% rename from packages/core/src/onebot/actions/group-admin.ts rename to packages/onebot/src/actions/group-admin.ts index 404b017a..23bda0e2 100644 --- a/packages/core/src/onebot/actions/group-admin.ts +++ b/packages/onebot/src/actions/group-admin.ts @@ -8,7 +8,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userId = asNumber(params.user_id); const reject = asBoolean(params.reject_add_request, false); if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.setGroupKick(groupId, userId, reject); + await ctx.bridge.apis.groupAdmin.kickMember(groupId, userId, reject); return okResponse(); }); @@ -17,7 +17,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : []; const reject = asBoolean(params.reject_add_request, false); if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required'); - await ctx.setGroupKickMembers(groupId, userIds, reject); + await ctx.bridge.apis.groupAdmin.kickMembers(groupId, userIds, reject); return okResponse(); }); @@ -26,7 +26,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userId = asNumber(params.user_id); const duration = asNumber(params.duration) || 1800; if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.setGroupBan(groupId, userId, duration); + await ctx.bridge.apis.groupAdmin.muteMember(groupId, userId, duration); return okResponse(); }); @@ -34,7 +34,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const groupId = asNumber(params.group_id); const enable = asBoolean(params.enable, true); if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.setGroupWholeBan(groupId, enable); + await ctx.bridge.apis.groupAdmin.muteAll(groupId, enable); return okResponse(); }); @@ -42,14 +42,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const groupId = asNumber(params.group_id); const addType = asNumber(params.add_type); if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required'); - await ctx.bridge.setGroupAddOption(groupId, addType); + await ctx.bridge.apis.groupAdmin.setAddOption(groupId, addType); return okResponse(); }); h.registerAction('set_group_search', async (params) => { const groupId = asNumber(params.group_id); if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.bridge.setGroupSearch(groupId); + await ctx.bridge.apis.groupAdmin.setSearch(groupId); return okResponse(); }); @@ -58,7 +58,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userId = asNumber(params.user_id); const enable = asBoolean(params.enable, true); if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.bridge.setGroupAdmin(groupId, userId, enable); + await ctx.bridge.apis.groupAdmin.setAdmin(groupId, userId, enable); return okResponse(); }); @@ -67,7 +67,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userId = asNumber(params.user_id); const card = asString(params.card); if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.bridge.setGroupCard(groupId, userId, card); + await ctx.bridge.apis.groupAdmin.setCard(groupId, userId, card); return okResponse(); }); @@ -75,14 +75,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const groupId = asNumber(params.group_id); const name = asString(params.group_name); if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.bridge.setGroupName(groupId, name); + await ctx.bridge.apis.groupAdmin.setName(groupId, name); return okResponse(); }); h.registerAction('set_group_leave', async (params) => { const groupId = asNumber(params.group_id); if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.setGroupLeave(groupId); + await ctx.bridge.apis.groupAdmin.leave(groupId); return okResponse(); }); @@ -91,7 +91,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const userId = asNumber(params.user_id); const title = asString(params.special_title); if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.bridge.setGroupSpecialTitle(groupId, userId, title); + await ctx.bridge.apis.groupAdmin.setSpecialTitle(groupId, userId, title); return okResponse(); }); @@ -113,7 +113,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); try { - await ctx.bridge.setGroupAvatar(groupId, file); + await ctx.bridge.apis.profile.setGroupAvatar(groupId, file); return okResponse(); } catch (err) { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); diff --git a/packages/core/src/onebot/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts similarity index 79% rename from packages/core/src/onebot/actions/group-album.ts rename to packages/onebot/src/actions/group-album.ts index cd7f8b5d..b7f8b1e9 100644 --- a/packages/core/src/onebot/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -1,6 +1,7 @@ import type { ApiHandler, ApiActionContext } from '../api-handler'; import { asNumber, asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; +import type { JsonValue } from '../types'; export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_group_album_list', async (params) => { @@ -8,7 +9,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); try { - const albumList = await ctx.getGroupAlbumList(groupId); + const albumList = await ctx.bridge.apis.groupAlbum.list(groupId); return okResponse(albumList); } catch (error) { const message = error instanceof Error ? error.message : 'failed to get group album list'; @@ -28,7 +29,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); try { - await ctx.uploadImageToGroupAlbum(groupId, albumId, albumName, file); + await ctx.bridge.apis.groupAlbum.upload(groupId, albumId, albumName, file); return okResponse(null); } catch (error) { const message = error instanceof Error ? error.message : 'failed to upload image to group album'; @@ -45,8 +46,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required'); try { - const mediaList = await ctx.getGroupAlbumMediaList(groupId, albumId, attachInfo); - return okResponse(mediaList); + 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'; return failedResponse(RETCODE.INTERNAL_ERROR, message); @@ -65,8 +69,12 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required'); try { - const comment = await ctx.commentGroupAlbumMedia(groupId, albumId, lloc, content); - return okResponse(comment); + 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'; return failedResponse(RETCODE.INTERNAL_ERROR, message); @@ -84,7 +92,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } try { - const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, true); + const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, true); return okResponse(res); } catch (error) { const message = error instanceof Error ? error.message : 'failed to set like on album media'; @@ -104,7 +112,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } try { - const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, false); + const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, false); return okResponse(res); } catch (error) { const message = error instanceof Error ? error.message : 'failed to cancel like on album media'; @@ -122,7 +130,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } try { - const res = await ctx.deleteGroupAlbumMedia(groupId, albumId, lloc); + const res = await ctx.bridge.apis.groupAlbum.delete(groupId, albumId, lloc); return okResponse(res); } catch (error) { const message = error instanceof Error ? error.message : 'failed to delete album media'; diff --git a/packages/core/src/onebot/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts similarity index 83% rename from packages/core/src/onebot/actions/group-file.ts rename to packages/onebot/src/actions/group-file.ts index 29581a0e..4f459099 100644 --- a/packages/core/src/onebot/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -11,8 +11,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const folderId = asString(params.folder) || asString(params.folder_id) || '/'; const uploadFile = asBoolean(params.upload_file, true); if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required'); - const fileId = await ctx.uploadGroupFile(groupId, file, name, folderId, uploadFile); - return okResponse({ file_id: fileId }); + const result = await ctx.bridge.apis.groupFile.upload(groupId, file, name, folderId, uploadFile); + return okResponse({ file_id: result.fileId }); }); h.registerAction('upload_private_file', async (params) => { @@ -21,8 +21,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const name = asString(params.name); const uploadFile = asBoolean(params.upload_file, true); if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required'); - const fileId = await ctx.uploadPrivateFile(userId, file, name, uploadFile); - return okResponse({ file_id: fileId }); + const result = await ctx.bridge.apis.groupFile.uploadPrivate(userId, file, name, uploadFile); + return okResponse({ file_id: result.fileId }); }); h.registerAction('get_group_file_url', async (params) => { @@ -32,7 +32,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !fileId) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required'); } - return okResponse({ url: await ctx.getGroupFileUrl(groupId, fileId, busId) }); + return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(groupId, fileId, busId) }); }); h.registerAction('get_group_root_files', async (params) => { @@ -58,7 +58,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !fileId) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required'); } - await ctx.bridge.deleteGroupFile(groupId, fileId); + await ctx.bridge.apis.groupFile.delete(groupId, fileId); return okResponse(); }); @@ -70,7 +70,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !fileId || !parentDirectory || !targetDirectory) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required'); } - await ctx.bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory); + await ctx.bridge.apis.groupFile.move(groupId, fileId, parentDirectory, targetDirectory); return okResponse(); }); @@ -81,7 +81,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !name) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required'); } - await ctx.createGroupFileFolder(groupId, name, parentId); + await ctx.bridge.apis.groupFile.createFolder(groupId, name, parentId); return okResponse(); }); @@ -91,7 +91,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !folderId) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required'); } - await ctx.bridge.deleteGroupFileFolder(groupId, folderId); + await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId); return okResponse(); }); @@ -102,7 +102,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId || !folderId || !newName) { return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required'); } - await ctx.bridge.renameGroupFileFolder(groupId, folderId, newName); + await ctx.bridge.apis.groupFile.renameFolder(groupId, folderId, newName); return okResponse(); }); @@ -113,6 +113,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!userId || !fileId || !fileHash) { return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required'); } - return okResponse({ url: await ctx.getPrivateFileUrl(userId, fileId, fileHash) }); + return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash) }); }); } diff --git a/packages/core/src/onebot/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts similarity index 95% rename from packages/core/src/onebot/actions/group-info.ts rename to packages/onebot/src/actions/group-info.ts index f946ff42..ae302de6 100644 --- a/packages/core/src/onebot/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -1,7 +1,7 @@ import type { ApiHandler, ApiActionContext } from '../api-handler'; import { asNumber, asBoolean, asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; -import { WebHonorType } from '@/bridge/web/group-honor'; +import { WebHonorType } from '@snowluma/bridge/web/group-honor'; export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_group_list', async (params) => { @@ -68,7 +68,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } try { - const honorInfo = await ctx.bridge.getGroupHonorInfo(groupId, typeStr as WebHonorType); + const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType); return okResponse(honorInfo); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`); diff --git a/packages/core/src/onebot/actions/info.ts b/packages/onebot/src/actions/info.ts similarity index 100% rename from packages/core/src/onebot/actions/info.ts rename to packages/onebot/src/actions/info.ts diff --git a/packages/core/src/onebot/actions/message.ts b/packages/onebot/src/actions/message.ts similarity index 100% rename from packages/core/src/onebot/actions/message.ts rename to packages/onebot/src/actions/message.ts diff --git a/packages/core/src/onebot/actions/request.ts b/packages/onebot/src/actions/request.ts similarity index 93% rename from packages/core/src/onebot/actions/request.ts rename to packages/onebot/src/actions/request.ts index cce90b82..e76bade9 100644 --- a/packages/core/src/onebot/actions/request.ts +++ b/packages/onebot/src/actions/request.ts @@ -7,7 +7,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const flag = asString(params.flag); const approve = asBoolean(params.approve, true); if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required'); - await ctx.handleFriendRequest(flag, approve); + await ctx.bridge.apis.friend.handleRequest(flag, approve); return okResponse(); }); diff --git a/packages/core/src/onebot/api-handler.ts b/packages/onebot/src/api-handler.ts similarity index 68% rename from packages/core/src/onebot/api-handler.ts rename to packages/onebot/src/api-handler.ts index 721c1c7b..60b0649e 100644 --- a/packages/core/src/onebot/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -1,9 +1,9 @@ import type { JsonObject, JsonValue, MessageMeta } from './types'; import type { ForwardPreviewMeta } from './modules/message-actions'; -import type { BridgeInterface } from '../bridge/bridge-interface'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import { RETCODE, failedResponse } from './types'; -import { createLogger, type Logger } from '../utils/logger'; -import { summarizeParams } from '../utils/log-summary'; +import { createLogger, type Logger } from '@snowluma/common/logger'; +import { summarizeParams } from '@snowluma/common/log-summary'; const moduleLog = createLogger('Bridge.Action'); @@ -17,8 +17,8 @@ import { register as registerRequest } from './actions/request'; import { register as registerExtended } from './actions/extended'; import { register as registerGroupAlbum } from './actions/group-album'; -import { WebHonorType } from '@/bridge/web/group-honor'; -import { ClientKeyInfo } from '@/bridge/bridge'; +import { WebHonorType } from '@snowluma/bridge/web/group-honor'; +import type { ClientKeyInfo } from '@snowluma/core/bridge'; export interface MessageSendResult { messageId: number; @@ -61,34 +61,29 @@ export interface ApiActionContext { getGroupMemberList: (groupId: number, noCache?: boolean) => Promise; getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise; getStrangerInfo: (userId: number) => Promise; - // Group admin (adapters: rename Bridge methods to OneBot vocabulary) - setGroupKick: (groupId: number, userId: number, rejectAdd: boolean) => Promise; - setGroupKickMembers: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise; - setGroupBan: (groupId: number, userId: number, duration: number) => Promise; - setGroupWholeBan: (groupId: number, enable: boolean) => Promise; - setGroupLeave: (groupId: number) => Promise; - // Group file (adapters: field extraction + Bridge name translation) - uploadGroupFile: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise; - uploadPrivateFile: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise; - getGroupFileUrl: (groupId: number, fileId: string, busId?: 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; - createGroupFileFolder: (groupId: number, name: string, parentId?: string) => Promise; - getPrivateFileUrl: (userId: number, fileId: string, fileHash: string) => Promise; - getGroupFileCount: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>; - // Requests (adapters: rename to OneBot vocabulary) - handleFriendRequest: (flag: string, approve: boolean) => 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 (adapters: flatten isGroup into bridge.sendPoke signature) - sendFriendPoke: (userId: number, targetId?: number) => Promise; - sendGroupPoke: (groupId: number, userId: number) => 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 with OneBot-specific default args - getProfileLike: (userId?: number, start?: number, limit?: number) => Promise; - getGroupEssence: (groupId: number, pageStart?: number, pageLimit?: number) => Promise; - // Friend deletion (adapter: rename + force-boolean) - handleDeleteFriend: (userId: number, block?: boolean) => 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; @@ -99,33 +94,18 @@ 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 }>; - // Extended NapCat-compatible - setFriendRemark: (userId: number, remark: string) => Promise; - setGroupRemark: (groupId: number, remark: string) => Promise; - setGroupAvatar: (groupId: number, source: string) => Promise; + // setMsgEmojiLike: stays because it threads messageStore meta lookup. setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise; - markGroupMsgAsRead: (groupId: number, sequence: number) => Promise; - markPrivateMsgAsRead: (userId: number, sequence: number) => Promise; - setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise; - setProfile: (nickname?: string, personalNote?: string) => Promise; - fetchCustomFace: (count?: number) => Promise; - getEmojiLikes: (groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) => Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }>; - // Web - getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => Promise; - getGroupEssenceAll: (groupId: number) => Promise; - getGroupAlbumList: (groupId: number) => Promise; - uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise; - getGroupAlbumMediaList: (groupId: number, albumId: string, attachInfo?: string) => Promise; - commentGroupAlbumMedia: (groupId: number, albumId: string, lloc: string, content: string) => Promise; - deleteGroupAlbumMedia: (groupId: number, albumId: string, lloc: string) => Promise; - likeGroupAlbumMedia: (groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean) => Promise; - sendGroupNotice: (groupId: number, content: string, options?: any) => Promise; - getGroupNotice: (groupId: number) => Promise; - deleteGroupNotice: (groupId: number, fid: string) => Promise; - getCookiesStr: (domain: string) => Promise; - getCsrfToken: () => Promise; - getCredentials: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>; - forceFetchClientKey: () => Promise; + // 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/core/src/onebot/config.ts b/packages/onebot/src/config.ts similarity index 98% rename from packages/core/src/onebot/config.ts rename to packages/onebot/src/config.ts index 5e1605df..e2c94a18 100644 --- a/packages/core/src/onebot/config.ts +++ b/packages/onebot/src/config.ts @@ -1,7 +1,7 @@ import fs from 'fs'; import path from 'path'; import { randomBytes } from 'crypto'; -import { createLogger } from '../utils/logger'; +import { createLogger } from '@snowluma/common/logger'; import type { HttpClientNetwork, HttpServerNetwork, @@ -243,9 +243,9 @@ function collectByName( function pickAutoName(kind: keyof OneBotNetworks, used: Map, counter: number): string { const prefix = kind === 'httpServers' ? 'http' : - kind === 'httpClients' ? 'httppost' : - kind === 'wsServers' ? 'ws' : - 'wsclient'; + kind === 'httpClients' ? 'httppost' : + kind === 'wsServers' ? 'ws' : + 'wsclient'; let candidate = `${prefix}-${counter}`; while (used.has(candidate)) { counter += 1; diff --git a/packages/onebot/src/env.d.ts b/packages/onebot/src/env.d.ts new file mode 100644 index 00000000..c1f1bcd1 --- /dev/null +++ b/packages/onebot/src/env.d.ts @@ -0,0 +1,8 @@ +// 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/core/src/onebot/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts similarity index 72% rename from packages/core/src/onebot/event-converter/index.ts rename to packages/onebot/src/event-converter/index.ts index 5b5b6032..adb7dbe2 100644 --- a/packages/core/src/onebot/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -1,13 +1,4 @@ -// Bridge event -> OneBot top-level event conversion. -// -// Replaces the old `EventConverter` class. The class held four -// resolver fields (image-url / media-url / message-id / media-segment -// sink) wired in lazily via setters; the new shape passes them as a -// `ConverterContext` object so each case is a pure function and the -// per-case test setup is two lines, not a class instance plus four -// setter calls. - -import type { MessageElement, QQEventVariant } from '../../bridge/events'; +import type { MessageElement, QQEventVariant } from '@snowluma/bridge/events'; import type { JsonObject } from '../types'; import { convertFriendMessage, @@ -84,26 +75,26 @@ export async function convertEvent( switch (event.kind) { // Messages. case 'friend_message': return convertFriendMessage(ctx, event); - case 'group_message': return convertGroupMessage(ctx, event); - case 'temp_message': return convertTempMessage(ctx, event); + case 'group_message': return convertGroupMessage(ctx, event); + case 'temp_message': return convertTempMessage(ctx, event); // Notices. - case 'group_member_join': return convertGroupMemberJoin(ctx, event); + case 'group_member_join': return convertGroupMemberJoin(ctx, event); case 'group_member_leave': return convertGroupMemberLeave(ctx, event); - case 'group_mute': return convertGroupMute(ctx, event); - case 'group_admin': return convertGroupAdmin(ctx, event); - case 'friend_recall': return convertFriendRecall(ctx, event); - case 'group_recall': return convertGroupRecall(ctx, event); - case 'friend_poke': return convertFriendPoke(ctx, event); - case 'group_poke': return convertGroupPoke(ctx, event); - case 'group_essence': return convertGroupEssence(ctx, event); - case 'group_file_upload': return convertGroupFileUpload(ctx, event); - case 'friend_add': return convertFriendAdd(ctx, event); + case 'group_mute': return convertGroupMute(ctx, event); + case 'group_admin': return convertGroupAdmin(ctx, event); + case 'friend_recall': return convertFriendRecall(ctx, event); + case 'group_recall': return convertGroupRecall(ctx, event); + case 'friend_poke': return convertFriendPoke(ctx, event); + case 'group_poke': return convertGroupPoke(ctx, event); + case 'group_essence': return convertGroupEssence(ctx, event); + case 'group_file_upload': return convertGroupFileUpload(ctx, event); + case 'friend_add': return convertFriendAdd(ctx, event); case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event); // Requests. - case 'friend_request': return convertFriendRequest(ctx, event); - case 'group_invite': return convertGroupInvite(ctx, event); + case 'friend_request': return convertFriendRequest(ctx, event); + case 'group_invite': return convertGroupInvite(ctx, event); default: return null; diff --git a/packages/core/src/onebot/event-converter/to-message.ts b/packages/onebot/src/event-converter/to-message.ts similarity index 92% rename from packages/core/src/onebot/event-converter/to-message.ts rename to packages/onebot/src/event-converter/to-message.ts index 57058c5f..f87353fd 100644 --- a/packages/core/src/onebot/event-converter/to-message.ts +++ b/packages/onebot/src/event-converter/to-message.ts @@ -1,11 +1,6 @@ -// Message-kind handlers: friend_message, group_message, temp_message. -// Each takes a ConverterContext (which carries selfId + the four -// resolver/sink callbacks) and the typed bridge event, and returns the -// OneBot top-level event JSON. - -import type { QQEventVariant } from '../../bridge/events'; -import type { JsonObject } from '../types'; +import type { QQEventVariant } from '@snowluma/bridge/events'; 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'; diff --git a/packages/core/src/onebot/event-converter/to-notice.ts b/packages/onebot/src/event-converter/to-notice.ts similarity index 94% rename from packages/core/src/onebot/event-converter/to-notice.ts rename to packages/onebot/src/event-converter/to-notice.ts index 484d4921..76af6b26 100644 --- a/packages/core/src/onebot/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -1,12 +1,6 @@ -// Notice-kind handlers (10 cases). These produce OneBot `notice` events -// with no message body / no element conversion — pure field projections -// from the bridge event into the OneBot wire shape. None of them call -// resolvers except the two recall handlers and group_essence, which -// need a message-id resolution. - -import type { QQEventVariant } from '../../bridge/events'; -import type { JsonObject } from '../types'; +import type { QQEventVariant } from '@snowluma/bridge/events'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id'; +import type { JsonObject } from '../types'; import type { ConverterContext } from './index'; import { applyMessageIdResolver, isSameActor } from './utils'; diff --git a/packages/core/src/onebot/event-converter/to-request.ts b/packages/onebot/src/event-converter/to-request.ts similarity index 74% rename from packages/core/src/onebot/event-converter/to-request.ts rename to packages/onebot/src/event-converter/to-request.ts index cc46bc24..9b3d0b50 100644 --- a/packages/core/src/onebot/event-converter/to-request.ts +++ b/packages/onebot/src/event-converter/to-request.ts @@ -1,9 +1,4 @@ -// Request-kind handlers (2 cases). OneBot `request` events for friend -// adds and group invites/joins — both carry the bridge-supplied `flag` -// that the caller later passes back to `set_friend_add_request` / -// `set_group_add_request`. - -import type { QQEventVariant } from '../../bridge/events'; +import type { QQEventVariant } from '@snowluma/bridge/events'; import type { JsonObject } from '../types'; import type { ConverterContext } from './index'; diff --git a/packages/core/src/onebot/event-converter/to-segment.ts b/packages/onebot/src/event-converter/to-segment.ts similarity index 92% rename from packages/core/src/onebot/event-converter/to-segment.ts rename to packages/onebot/src/event-converter/to-segment.ts index fd926fae..8e0829bb 100644 --- a/packages/core/src/onebot/event-converter/to-segment.ts +++ b/packages/onebot/src/event-converter/to-segment.ts @@ -1,9 +1,4 @@ -// Per-element converter: 13 element types -> one OneBot message segment. -// Used by message-events (friend/group/temp) for inline elements AND by -// modules/message-actions.ts for forward-message rebuilding (re-exported -// from this module via the index barrel as `elementsToOneBotSegments`). - -import type { MessageElement } from '../../bridge/events'; +import type { MessageElement } from '@snowluma/bridge/events'; import type { JsonArray, JsonObject } from '../types'; import type { ImageUrlResolver, diff --git a/packages/core/src/onebot/event-converter/utils.ts b/packages/onebot/src/event-converter/utils.ts similarity index 93% rename from packages/core/src/onebot/event-converter/utils.ts rename to packages/onebot/src/event-converter/utils.ts index fdd3731e..82523dc6 100644 --- a/packages/core/src/onebot/event-converter/utils.ts +++ b/packages/onebot/src/event-converter/utils.ts @@ -1,11 +1,5 @@ -// Pure helpers shared across the per-post_type converter modules. -// -// Nothing here touches I/O or class state; everything is a small -// function so the per-event tests can import what they need without -// dragging in resolver wiring. - -import type { JsonArray, JsonObject } from '../types'; 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 { diff --git a/packages/core/src/onebot/event-filter.ts b/packages/onebot/src/event-filter.ts similarity index 94% rename from packages/core/src/onebot/event-filter.ts rename to packages/onebot/src/event-filter.ts index e67415b7..a3d90ae6 100644 --- a/packages/core/src/onebot/event-filter.ts +++ b/packages/onebot/src/event-filter.ts @@ -1,11 +1,4 @@ import type { JsonObject, JsonValue, MessageFormat } from './types'; - -/** - * Per-adapter view of how an event should be reported. - * - * Built once from each adapter's own configuration at (re)load time so the - * per-publish dispatch loop is just a couple of object lookups. - */ export interface EventReportOptions { /** Effective `messageFormat` for this adapter. */ messageFormat: MessageFormat; diff --git a/packages/core/src/onebot/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts similarity index 87% rename from packages/core/src/onebot/event-pipeline.ts rename to packages/onebot/src/event-pipeline.ts index 1df60864..a9e04944 100644 --- a/packages/core/src/onebot/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -1,15 +1,7 @@ -// Per-kind bridge → OneBot event handlers. -// -// Replaces the legacy single-firehose `OneBotInstance.onBridgeEvent` switch. -// Every bridge event kind gets a small async handler bound to a shared -// `OneBotInstanceContext`; subscribers register on `ctx.bridge.events` so -// multiple unrelated downstream concerns (meta caching, OB11 conversion, -// dispatch) compose cleanly without one giant switch statement. - -import type { OneBotInstanceContext } from './instance-context'; +import type { QQEventVariant } from '@snowluma/bridge/events'; import { convertEvent } from './event-converter'; +import type { OneBotInstanceContext } from './instance-context'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; -import type { QQEventVariant } from '../bridge/events'; /** * Subscribe every `OneBotInstanceContext`-aware handler onto the bridge diff --git a/packages/core/src/onebot/instance-context.ts b/packages/onebot/src/instance-context.ts similarity index 55% rename from packages/core/src/onebot/instance-context.ts rename to packages/onebot/src/instance-context.ts index ad8b57c8..c6238e5c 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -1,5 +1,5 @@ -import type { WebHonorType } from '@/bridge/web/group-honor'; -import type { Bridge } from '../bridge/bridge'; +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'; @@ -35,7 +35,7 @@ import { getRecordInfo as getCachedRecordInfo, } from './modules/media-actions'; import { handleGroupAddRequest } from './modules/request-actions'; -import type { BridgeInterface } from '../bridge/bridge-interface'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; /** * Single shared context bag that flows through every OneBot instance-internal @@ -111,44 +111,19 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { 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.kickGroupMember(groupId, userId, reject), - setGroupKickMembers: (groupId, userIds, reject) => bridge.kickGroupMembers(groupId, userIds, reject), - setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration), - setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable), - setGroupLeave: (groupId) => bridge.leaveGroup(groupId), + // Group admin — actions now call `ctx.bridge.apis.groupAdmin.X(...)` + // directly; no per-method passthrough here anymore. - // Group file — fileId field extraction + defaults. - uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => { - const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true); - return result.fileId; - }, - uploadPrivateFile: async (userId, file, name, uploadFile) => { - const result = await bridge.uploadPrivateFile(userId, file, name ?? '', uploadFile ?? true); - return result.fileId; - }, - getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102), + // 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), - createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'), - getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash), - // Requests — name translation. - handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve), + // 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), - // Pokes — flatten isGroup into the bridge signature. - sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId), - sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId), - - // Essence — bake the set/unset boolean. - setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true), - deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false), - - // Profile-like / get_group_essence — OneBot-specific defaults that the - // action handlers don't supply. - getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.getProfileLike(userId, start, limit), - getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit), - // Message-store-backed history reads. getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count), getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count), @@ -161,47 +136,21 @@ 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), - handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block), - forceFetchClientKey: () => bridge.forceFetchClientKey(), - setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark), - setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark), - setGroupAvatar: (groupId, source) => bridge.setGroupAvatar(groupId, source), - getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId), - // Cross-store: looks up the meta then routes through Bridge. + // 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'); - // 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.setGroupReaction(meta.targetId, meta.sequence, emojiId, set); + await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set); }, - markGroupMsgAsRead: (groupId, sequence) => bridge.markGroupMsgAsRead(groupId, sequence), - markPrivateMsgAsRead: (userId, sequence) => bridge.markPrivateMsgAsRead(userId, sequence), - setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.setOnlineStatus(status, extStatus, batteryStatus), - setProfile: (nickname?: string, personalNote?: string) => bridge.setProfile(nickname, personalNote), - - // Web-backed actions. - getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.getGroupHonorInfo(groupId, type), - getGroupEssenceAll: (groupId) => bridge.getGroupEssenceAll(groupId), - getGroupAlbumList: (groupId) => bridge.getGroupAlbumList(groupId), - uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.uploadImageToGroupAlbum(groupId, albumId, albumName, filePath), - getGroupAlbumMediaList: (groupId, albumId, attachInfo) => bridge.getGroupAlbumMediaList(groupId, albumId, attachInfo), - commentGroupAlbumMedia: (groupId, albumId, lloc, content) => bridge.commentGroupAlbumMedia(groupId, albumId, lloc, content), - deleteGroupAlbumMedia: (groupId, albumId, lloc) => bridge.deleteGroupAlbumMedia(groupId, albumId, lloc), - likeGroupAlbumMedia: (groupId, albumId, batchId, lloc, isLike) => bridge.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, isLike), - sendGroupNotice: (groupId, content, options) => bridge.sendGroupNotice(groupId, content, options), - getGroupNotice: (groupId) => bridge.getGroupNotice(groupId), - deleteGroupNotice: (groupId, fid) => bridge.deleteGroupNotice(groupId, fid), - getCookiesStr: (domain) => bridge.getCookiesStr(domain), - getCsrfToken: () => bridge.getCsrfToken(), - getCredentials: (domain) => bridge.getCredentials(domain), - - // Extended - fetchCustomFace: (count) => bridge.fetchCustomFace(count), - getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie), // Media lookup. getImageInfo: (file) => getCachedImageInfo(mediaStore, file), diff --git a/packages/core/src/onebot/instance-rkey.ts b/packages/onebot/src/instance-rkey.ts similarity index 92% rename from packages/core/src/onebot/instance-rkey.ts rename to packages/onebot/src/instance-rkey.ts index 493eb2c2..101d6628 100644 --- a/packages/core/src/onebot/instance-rkey.ts +++ b/packages/onebot/src/instance-rkey.ts @@ -1,7 +1,7 @@ -import type { MessageElement } from '../bridge/events'; -import type { DownloadRKeyInfo } from '../bridge/bridge'; -import type { BridgeInterface } from '../bridge/bridge-interface'; -import { createLogger } from '../utils/logger'; +import type { MessageElement } from '@snowluma/bridge/events'; +import type { DownloadRKeyInfo } from '@snowluma/core/bridge'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { createLogger } from '@snowluma/common/logger'; const log = createLogger('OneBot'); @@ -28,7 +28,7 @@ export class RKeyCache { private lastRefreshAttempt = 0; warmUp(bridge: BridgeInterface, uin: string): void { - bridge.fetchDownloadRKeys().then( + bridge.apis.contacts.fetchDownloadRKeys().then( (rkeys) => { this.updateCache(rkeys); log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length); @@ -117,7 +117,7 @@ export class RKeyCache { this.lastRefreshAttempt = now; // Schedule async refresh - bridge.fetchDownloadRKeys().then( + bridge.apis.contacts.fetchDownloadRKeys().then( (rkeys) => this.updateCache(rkeys), () => { /* ignore */ }, ); diff --git a/packages/core/src/onebot/instance.ts b/packages/onebot/src/instance.ts similarity index 98% rename from packages/core/src/onebot/instance.ts rename to packages/onebot/src/instance.ts index 1d2cefcc..66831037 100644 --- a/packages/core/src/onebot/instance.ts +++ b/packages/onebot/src/instance.ts @@ -1,5 +1,5 @@ import path from 'path'; -import type { BridgeInterface } from '../bridge/bridge-interface'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import { ApiHandler } from './api-handler'; import type { ConverterContext } from './event-converter'; import { MediaIndexer } from './media-indexer'; @@ -19,8 +19,8 @@ import { HttpPostAdapter, type NetworkAdapterContext, } from './network'; -import { createLogger, type Logger } from '../utils/logger'; -import { formatGroup, formatMessageSegments, formatReply, formatUser } from '../utils/event-format'; +import { createLogger, type Logger } from '@snowluma/common/logger'; +import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/bridge/format'; const moduleLog = createLogger('Event'); diff --git a/packages/core/src/onebot/manager.ts b/packages/onebot/src/manager.ts similarity index 90% rename from packages/core/src/onebot/manager.ts rename to packages/onebot/src/manager.ts index a2a4b8d0..5f49e0cc 100644 --- a/packages/core/src/onebot/manager.ts +++ b/packages/onebot/src/manager.ts @@ -1,8 +1,8 @@ -import type { BridgeInterface } from '../bridge/bridge-interface'; -import type { BridgeManager } from '../bridge/manager'; +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'; -import { createLogger } from '../utils/logger'; const log = createLogger('OneBot'); const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1'; @@ -18,9 +18,6 @@ export class OneBotManager { bridgeManager.setSessionClosedCallback((uin) => { this.onSessionClosed(uin); }); - - // Per-kind subscriptions to `bridge.events` happen inside - // `OneBotInstance` itself; no global firehose to wire here. } getInstance(uin: string): OneBotInstance | null { @@ -92,7 +89,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise< // which used to leave identity.nickname empty — see step 1b for the // explicit fallback. try { - const friends = await bridge.fetchFriendList(); + const friends = await bridge.apis.contacts.fetchFriendList(); log.info('friends loaded: UIN=%s count=%d', uin, friends.length); for (const f of friends) { @@ -118,7 +115,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise< // back in the friend list. if (!selfResolved && selfUin > 0) { try { - const profile = await bridge.fetchUserProfile(selfUin); + const profile = await bridge.apis.contacts.fetchUserProfile(selfUin); bridge.identity.setSelfProfile(profile); bridge.identity.nickname = profile.nickname || uin; log.debug('self info via profile: UIN=%s uid=%s nickname=%s', @@ -132,7 +129,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise< // Step 2: Fetch group list let groups: { groupId: number }[] = []; try { - groups = await bridge.fetchGroupList(); + groups = await bridge.apis.contacts.fetchGroupList(); log.info('groups loaded: UIN=%s count=%d', uin, groups.length); } catch (e) { log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e)); @@ -144,7 +141,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise< let failedGroupCount = 0; for (const g of groups) { try { - const members = await bridge.fetchGroupMemberList(g.groupId); + const members = await bridge.apis.contacts.fetchGroupMemberList(g.groupId); loadedGroupCount += 1; loadedMemberCount += members.length; if (VERBOSE_WARMUP) { diff --git a/packages/core/src/onebot/media-indexer.ts b/packages/onebot/src/media-indexer.ts similarity index 82% rename from packages/core/src/onebot/media-indexer.ts rename to packages/onebot/src/media-indexer.ts index 1dbc607a..91f4c6a8 100644 --- a/packages/core/src/onebot/media-indexer.ts +++ b/packages/onebot/src/media-indexer.ts @@ -1,23 +1,15 @@ // 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 -// resolve the original `data.file` back to a URL + metadata. -// -// Used as the `mediaSegmentSink` callback in `ConverterContext`. -// -// The fan-out is uniform (always one rememberX call per segment), but -// each mediaType maps to a slightly different MediaStore record shape; -// keeping the three field maps in one place makes the divergence -// visible at a glance. -import type { MessageElement } from '../bridge/events'; -import type { JsonObject } from './types'; +import type { MessageElement } from '@snowluma/bridge/events'; import type { MediaStore } from './media-store'; +import type { JsonObject } from './types'; export type MediaType = 'image' | 'record' | 'video'; export class MediaIndexer { - constructor(private readonly mediaStore: MediaStore) {} + constructor(private readonly mediaStore: MediaStore) { } remember( mediaType: MediaType, diff --git a/packages/core/src/onebot/media-store.ts b/packages/onebot/src/media-store.ts similarity index 86% rename from packages/core/src/onebot/media-store.ts rename to packages/onebot/src/media-store.ts index 95a17093..9e6ee8ca 100644 --- a/packages/core/src/onebot/media-store.ts +++ b/packages/onebot/src/media-store.ts @@ -3,26 +3,12 @@ // 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. -// -// Earlier this lived in an in-memory `MediaCache`, which meant the lookup -// table was lost on every restart. This implementation persists everything -// alongside the message store so OneBot consumers can always resolve the -// media that produced any segment ever stored, even after the bot restarts. -// -// Schema overview (single SQLite file per UIN, e.g. `data//media.db`): -// media_entries(type, primary_key, data JSON, last_seen) -- one row per logical media item -// media_keys(type, key, primary_key) -- secondary index for every alias -// -// `rememberImage` / `rememberRecord` upsert exactly one entry row plus one -// alias row per identifier (file / fileName / fileId / url). The alias rows -// always point to the canonical entry so URL refreshes propagate to every -// alias automatically. import fs from 'fs'; +import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; import path from 'path'; -import { DatabaseSync, type StatementSync } from 'node:sqlite'; -import type { MessageElement } from '../bridge/events'; +import type { MessageElement } from '@snowluma/bridge/events'; export interface CachedImage { /** Primary `data.file` value as exposed in the OneBot segment. */ @@ -94,17 +80,17 @@ const TYPE_VIDEO = 'video'; const DEFAULT_KEEP_ENTRIES = 4096; export class MediaStore { - private readonly db: DatabaseSync; + private readonly db: DatabaseType; private readonly maxEntriesPerType: number; // Prepared statements (pay the parsing cost once at startup). - private readonly upsertEntry: StatementSync; - private readonly upsertKey: StatementSync; - private readonly findEntryByKey: StatementSync; - private readonly findEntryByPrimary: StatementSync; - private readonly evictByType: StatementSync; - private readonly purgeOrphanKeys: StatementSync; - private readonly countByType: StatementSync; + private readonly upsertEntry: Statement; + private readonly upsertKey: Statement; + private readonly findEntryByKey: Statement; + private readonly findEntryByPrimary: Statement; + private readonly evictByType: Statement; + private readonly purgeOrphanKeys: Statement; + private readonly countByType: Statement; constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) { this.maxEntriesPerType = Math.max(64, maxEntriesPerType); @@ -112,9 +98,9 @@ export class MediaStore { const dir = path.dirname(dbPath); fs.mkdirSync(dir, { recursive: true }); - this.db = new DatabaseSync(dbPath); - this.db.exec('PRAGMA journal_mode = WAL'); - this.db.exec('PRAGMA synchronous = NORMAL'); + this.db = new Database(dbPath); + this.db.pragma('journal_mode = WAL'); + this.db.pragma('synchronous = NORMAL'); this.initSchema(); this.upsertEntry = this.db.prepare( diff --git a/packages/core/src/onebot/media-url-resolver.ts b/packages/onebot/src/media-url-resolver.ts similarity index 50% rename from packages/core/src/onebot/media-url-resolver.ts rename to packages/onebot/src/media-url-resolver.ts index b30c9546..2fc0079e 100644 --- a/packages/core/src/onebot/media-url-resolver.ts +++ b/packages/onebot/src/media-url-resolver.ts @@ -1,26 +1,12 @@ -// Resolves the URL for an image / record / video / file element on its -// way out of the bridge into an OneBot segment. -// -// Two steps: -// 1. If the bridge event arrived without a `url` (the receive path -// sometimes does), fetch a fresh URL from the right Bridge API -// based on element.type + isGroup, mutating the element in-place -// so any downstream cache sees the URL too. -// 2. Apply the cached RKey (the per-UIN signed download key) the -// RKeyCache knows about — both to brand-new URLs from step 1 and -// to URLs that came in with the event already. -// -// Used as the `mediaUrlResolver` callback in `ConverterContext`. - -import type { BridgeInterface } from '../bridge/bridge-interface'; -import type { MessageElement } from '../bridge/events'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { MessageElement } from '@snowluma/bridge/events'; import type { RKeyCache } from './instance-rkey'; export class MediaUrlResolver { constructor( private readonly bridge: BridgeInterface, private readonly rkeyCache: RKeyCache, - ) {} + ) { } async resolve(element: MessageElement, isGroup: boolean, sessionId: number): Promise { if (!element.url) { @@ -40,9 +26,9 @@ export class MediaUrlResolver { private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise { if (element.type === 'file' && element.fileId) { if (isGroup) { - element.url = await this.bridge.fetchGroupFileUrl(sessionId, element.fileId); + element.url = await this.bridge.apis.groupFile.getUrl(sessionId, element.fileId); } else if (element.fileHash) { - element.url = await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash); + element.url = await this.bridge.apis.groupFile.getPrivateUrl(sessionId, element.fileId, element.fileHash); } else { element.url = ''; } @@ -52,12 +38,12 @@ export class MediaUrlResolver { if ((element.type === 'record' || element.type === 'video') && element.mediaNode) { if (isGroup) { element.url = element.type === 'record' - ? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode) - : await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode); + ? await this.bridge.apis.groupFile.getPttUrl(sessionId, element.mediaNode) + : await this.bridge.apis.groupFile.getVideoUrl(sessionId, element.mediaNode); } else { element.url = element.type === 'record' - ? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode) - : await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode); + ? await this.bridge.apis.groupFile.getPrivatePttUrl(element.mediaNode) + : await this.bridge.apis.groupFile.getPrivateVideoUrl(element.mediaNode); } } } diff --git a/packages/core/src/onebot/message-id.ts b/packages/onebot/src/message-id.ts similarity index 100% rename from packages/core/src/onebot/message-id.ts rename to packages/onebot/src/message-id.ts diff --git a/packages/core/src/onebot/message-parser.ts b/packages/onebot/src/message-parser.ts similarity index 97% rename from packages/core/src/onebot/message-parser.ts rename to packages/onebot/src/message-parser.ts index dea16d07..940d8d52 100644 --- a/packages/core/src/onebot/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -1,10 +1,6 @@ -// OneBot11 message segment parser. -// Converts OneBot message format (string with CQ codes or JSON segment arrays) -// into internal MessageElement arrays for sending. - -import type { MessageElement } from '../bridge/events'; -import type { JsonValue, JsonObject } from './types'; -import { createLogger } from '../utils/logger'; +import type { MessageElement } from '@snowluma/bridge/events'; +import { createLogger } from '@snowluma/common/logger'; +import type { JsonValue } from './types'; const log = createLogger('MsgParser'); @@ -140,12 +136,12 @@ async function segmentToElement(type: string, data: Record, opt if (options?.resolveReplySequence) { const resolved = options.resolveReplySequence(id); if (typeof resolved === 'number' && resolved > 0) { - const element: MessageElement = { - type: 'reply', + const element: MessageElement = { + type: 'reply', replySeq: resolved, replyMessageId: id // Keep the original messageId for logging }; - + // Try to get additional meta info for better reply display if (options?.resolveReplyMeta) { const meta = options.resolveReplyMeta(id); @@ -155,7 +151,7 @@ async function segmentToElement(type: string, data: Record, opt element.replyRandom = meta.random; } } - + return element; } } diff --git a/packages/core/src/onebot/message-store.ts b/packages/onebot/src/message-store.ts similarity index 64% rename from packages/core/src/onebot/message-store.ts rename to packages/onebot/src/message-store.ts index d17d4395..32f70d52 100644 --- a/packages/core/src/onebot/message-store.ts +++ b/packages/onebot/src/message-store.ts @@ -1,13 +1,31 @@ -// SQLite-backed message store using node:sqlite (DatabaseSync). -// Refactored to use a single unified `messages` table for all message types. - import fs from 'fs'; +import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; import path from 'path'; -import { DatabaseSync } from 'node:sqlite'; 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: DatabaseSync; + private readonly db: DatabaseType; + private readonly stmtStoreEvent: Statement; + private readonly stmtStoreMeta: Statement; + private readonly stmtFindEvent: Statement; + private readonly stmtFindMeta: Statement; + private readonly stmtResolveReplyGroup: Statement; + private readonly stmtResolveReplyPrivate: Statement; + private readonly stmtListEventsAnchored: Statement; + private readonly stmtListEventsLatest: Statement; constructor(dbPath: string) { const dir = path.dirname(dbPath); @@ -15,10 +33,77 @@ export class MessageStore { // Replace .json extension with .db if present const finalPath = dbPath.replace(/\.json$/, '.db'); - this.db = new DatabaseSync(finalPath); - this.db.exec('PRAGMA journal_mode = WAL'); - this.db.exec('PRAGMA synchronous = NORMAL'); + this.db = new Database(finalPath); + this.db.pragma('journal_mode = WAL'); + this.db.pragma('synchronous = NORMAL'); this.initSchema(); + + // Prepare once. Statements survive for the lifetime of the + // Database instance — `close()` finalizes them automatically. + this.stmtStoreEvent = this.db.prepare( + `INSERT INTO messages + (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data) + VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?) + ON CONFLICT(message_hash) DO UPDATE SET + is_group = excluded.is_group, + session_id = excluded.session_id, + sequence = excluded.sequence, + event_name = excluded.event_name, + timestamp = excluded.timestamp, + data = excluded.data`, + ); + + this.stmtStoreMeta = this.db.prepare( + `INSERT INTO messages + (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(message_hash) DO UPDATE SET + is_group = excluded.is_group, + session_id = excluded.session_id, + sequence = excluded.sequence, + event_name = excluded.event_name, + client_sequence = excluded.client_sequence, + random = excluded.random, + timestamp = excluded.timestamp`, + ); + + this.stmtFindEvent = this.db.prepare( + 'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL', + ); + + this.stmtFindMeta = this.db.prepare( + 'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?', + ); + + this.stmtResolveReplyGroup = this.db.prepare( + `SELECT sequence + FROM messages + WHERE is_group = 1 AND session_id = ? AND message_hash = ? + LIMIT 1`, + ); + + this.stmtResolveReplyPrivate = this.db.prepare( + `SELECT sequence + FROM messages + WHERE is_group = 0 AND message_hash = ? + LIMIT 1`, + ); + + this.stmtListEventsAnchored = this.db.prepare( + `SELECT data + FROM messages + WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ? + ORDER BY sequence DESC + LIMIT ?`, + ); + + this.stmtListEventsLatest = this.db.prepare( + `SELECT data + FROM messages + WHERE is_group = ? AND session_id = ? AND data IS NOT NULL + ORDER BY sequence DESC + LIMIT ?`, + ); } close(): void { @@ -37,35 +122,12 @@ export class MessageStore { const json = JSON.stringify(event); const timestamp = toInt(event.time); - this.db.prepare( - `INSERT INTO messages - (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data) - VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?) - ON CONFLICT(message_hash) DO UPDATE SET - is_group = excluded.is_group, - session_id = excluded.session_id, - sequence = excluded.sequence, - event_name = excluded.event_name, - timestamp = excluded.timestamp, - data = excluded.data` - ).run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json); + this.stmtStoreEvent.run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json); } storeMeta(messageId: number, meta: MessageMeta): void { if (!isValidMessageId(messageId)) return; - this.db.prepare( - `INSERT INTO messages - (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(message_hash) DO UPDATE SET - is_group = excluded.is_group, - session_id = excluded.session_id, - sequence = excluded.sequence, - event_name = excluded.event_name, - client_sequence = excluded.client_sequence, - random = excluded.random, - timestamp = excluded.timestamp` - ).run( + this.stmtStoreMeta.run( messageId, meta.isGroup ? 1 : 0, meta.targetId, @@ -79,10 +141,8 @@ export class MessageStore { findEvent(messageId: number): JsonObject | null { if (!isValidMessageId(messageId)) return null; - const row = this.db.prepare( - 'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL', - ).get(messageId) as { data: string } | undefined; - + const row = this.stmtFindEvent.get(messageId) as { data: string } | undefined; + if (!row?.data) return null; try { return JSON.parse(row.data) as JsonObject; @@ -94,9 +154,7 @@ export class MessageStore { findMeta(messageId: number): MessageMeta | null { if (!isValidMessageId(messageId)) return null; - const row = this.db.prepare( - 'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?', - ).get(messageId) as { + const row = this.stmtFindMeta.get(messageId) as { is_group: number; session_id: number; sequence: number; @@ -123,25 +181,15 @@ export class MessageStore { if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) { return null; } - + // For private messages, we cannot rely on session_id matching because: // - When receiving: session_id is the sender's UIN // - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to) // So for private messages, we only match by message_hash and is_group flag. const row = isGroup - ? this.db.prepare( - `SELECT sequence - FROM messages - WHERE is_group = 1 AND session_id = ? AND message_hash = ? - LIMIT 1` - ).get(sessionId, messageId) as { sequence: number } | undefined - : this.db.prepare( - `SELECT sequence - FROM messages - WHERE is_group = 0 AND message_hash = ? - LIMIT 1` - ).get(messageId) as { sequence: number } | undefined; - + ? this.stmtResolveReplyGroup.get(sessionId, messageId) as { sequence: number } | undefined + : this.stmtResolveReplyPrivate.get(messageId) as { sequence: number } | undefined; + if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) { return null; } @@ -161,20 +209,8 @@ export class MessageStore { const anchor = hasAnchor ? (anchorSequence as number) : 0; const rows = hasAnchor - ? this.db.prepare( - `SELECT data - FROM messages - WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ? - ORDER BY sequence DESC - LIMIT ?` - ).all(isGroup ? 1 : 0, sessionId, anchor, limit) - : this.db.prepare( - `SELECT data - FROM messages - WHERE is_group = ? AND session_id = ? AND data IS NOT NULL - ORDER BY sequence DESC - LIMIT ?` - ).all(isGroup ? 1 : 0, sessionId, limit); + ? this.stmtListEventsAnchored.all(isGroup ? 1 : 0, sessionId, anchor, limit) + : this.stmtListEventsLatest.all(isGroup ? 1 : 0, sessionId, limit); const result: JsonObject[] = []; for (const row of rows as Array<{ data: string }>) { diff --git a/packages/core/src/onebot/modules/contact-actions.ts b/packages/onebot/src/modules/contact-actions.ts similarity index 89% rename from packages/core/src/onebot/modules/contact-actions.ts rename to packages/onebot/src/modules/contact-actions.ts index f2e00ab2..805d2941 100644 --- a/packages/core/src/onebot/modules/contact-actions.ts +++ b/packages/onebot/src/modules/contact-actions.ts @@ -1,5 +1,5 @@ -import type { BridgeInterface } from '../../bridge/bridge-interface'; -import type { IdentityService } from '../../bridge/identity-service'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { IdentityService } from '@snowluma/bridge/identity-service'; import type { OneBotInstanceContext } from '../instance-context'; import type { JsonObject } from '../types'; @@ -13,7 +13,7 @@ export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nick // 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.fetchGroupMemberList(groupId); + await bridge.apis.contacts.fetchGroupMemberList(groupId); } catch { // Use cached data. } @@ -21,7 +21,7 @@ async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: numbe export async function getFriendList(bridge: BridgeInterface): Promise { try { - const friends = await bridge.fetchFriendList(); + const friends = await bridge.apis.contacts.fetchFriendList(); return friends.map(f => ({ user_id: f.uin as any, nickname: f.nickname as any, @@ -42,7 +42,7 @@ export async function getGroupList( ): Promise { try { if (noCache || bridge.identity.groups.length === 0) { - await bridge.fetchGroupList(); + await bridge.apis.contacts.fetchGroupList(); } } catch { // Use cached data. @@ -62,7 +62,7 @@ export async function getGroupInfo( ): Promise { if (noCache || !bridge.identity.findGroup(groupId)) { try { - await bridge.fetchGroupList(); + await bridge.apis.contacts.fetchGroupList(); } catch { // Use cached data. } @@ -88,7 +88,7 @@ export async function getGroupMemberList( } try { - const members = await bridge.fetchGroupMemberList(groupId); + const members = await bridge.apis.contacts.fetchGroupMemberList(groupId); return members.map(m => formatGroupMember(groupId, m)); } catch { return getCachedGroupMembers(bridge.identity, groupId); @@ -114,7 +114,7 @@ export async function getGroupFiles( groupId: number, folderId?: string, ): Promise { - const result = await bridge.fetchGroupFiles(groupId, folderId ?? '/'); + const result = await bridge.apis.groupFile.list(groupId, folderId ?? '/'); return { files: result.files.map((file) => ({ group_id: groupId as any, @@ -146,7 +146,7 @@ export async function getStrangerInfo( userId: number, ): Promise { try { - const p = await bridge.fetchUserProfile(userId); + const p = await bridge.apis.contacts.fetchUserProfile(userId); return { user_id: p.uin as any, nickname: p.nickname as any, @@ -167,7 +167,7 @@ export async function getStrangerInfo( export async function getGroupSystemMessages(bridge: BridgeInterface): Promise { try { - const reqs = await bridge.fetchGroupRequests(); + const reqs = await bridge.apis.contacts.fetchGroupRequests(); return reqs.map(r => ({ group_id: r.groupId, group_name: r.groupName, @@ -184,7 +184,7 @@ export async function getGroupSystemMessages(bridge: BridgeInterface): Promise { try { - const rkeys = await bridge.fetchDownloadRKeys(); + const rkeys = await bridge.apis.contacts.fetchDownloadRKeys(); return rkeys.map(r => ({ rkey: r.rkey, type: r.type, diff --git a/packages/core/src/onebot/modules/media-actions.ts b/packages/onebot/src/modules/media-actions.ts similarity index 82% rename from packages/core/src/onebot/modules/media-actions.ts rename to packages/onebot/src/modules/media-actions.ts index f3be88f9..2c265a0b 100644 --- a/packages/core/src/onebot/modules/media-actions.ts +++ b/packages/onebot/src/modules/media-actions.ts @@ -1,5 +1,5 @@ -import type { BridgeInterface } from '../../bridge/bridge-interface'; -import { createLogger } from '../../utils/logger'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { createLogger } from '@snowluma/common/logger'; import type { MediaStore } from '../media-store'; import type { JsonObject } from '../types'; @@ -34,8 +34,8 @@ export async function getRecordInfo( if (!url && cached.mediaNode) { try { url = cached.isGroup - ? await bridge.fetchGroupPttUrlByNode(cached.sessionId, cached.mediaNode) - : await bridge.fetchPrivatePttUrlByNode(cached.mediaNode); + ? await bridge.apis.groupFile.getPttUrl(cached.sessionId, cached.mediaNode) + : await bridge.apis.groupFile.getPrivatePttUrl(cached.mediaNode); if (url) { mediaStore.updateRecordUrl(file, url); } diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts similarity index 82% rename from packages/core/src/onebot/modules/message-actions.ts rename to packages/onebot/src/modules/message-actions.ts index c2589e79..4238e9ca 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -1,12 +1,13 @@ -import type { BridgeInterface } from '../../bridge/bridge-interface'; -import type { ForwardNodePayload, MessageElement } from '../../bridge/events'; -import { createLogger } from '../../utils/logger'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { ForwardNodePayload, MessageElement } from '@snowluma/bridge/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 { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id'; import { parseMessage } from '../message-parser'; import type { MessageStore } from '../message-store'; -import type { JsonObject, JsonValue, MessageMeta } from '../types'; +import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types'; import type { OneBotInstanceContext } from '../instance-context'; const log = createLogger('OneBot'); @@ -65,9 +66,9 @@ export async function getFriendMsgHistory( export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise { if (meta.isGroup) { - await bridge.recallGroupMessage(meta.targetId, meta.sequence); + await bridge.apis.message.recallGroup(meta.targetId, meta.sequence); } else { - await bridge.recallPrivateMessage( + await bridge.apis.message.recallPrivate( meta.targetId, meta.clientSequence, meta.sequence, @@ -85,7 +86,98 @@ export async function setEssenceMessage( ): Promise { const meta = messageStore.findMeta(messageId); if (!meta || !meta.isGroup) throw new Error('message not found or not a group message'); - await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable); + await bridge.apis.interaction.setEssence(meta.targetId, meta.sequence, meta.random, enable); +} + +/** + * Build + store a synthetic OneBot event for a just-sent message so + * `/get_msg` can find it. + * + * The QQ server doesn't always echo self-sent messages back on the + * receive channel — Lagrange and NapCat both work around this by + * writing a local copy at send time (Lagrange persists into Realm DB + * inside `SendMessageOperation`; NapCat caches in-memory via its msg + * service). Without it, callers that hit `/get_msg` with a freshly- + * returned `message_id` get "message not found" even though the recall + * path works fine (recall uses the lighter `cacheMessageMeta` already). + * + * Stored event has `post_type: 'message_sent'` so OneBot clients that + * inspect it through `/get_msg` can distinguish their own outbound + * messages from incoming ones. + */ +async function cacheSelfSentMessage( + ref: OneBotInstanceContext, + options: { + isGroup: boolean; + sessionId: number; // groupId or peer userId + messageId: number; + sequence: number; + timestamp: number; + elements: MessageElement[]; + }, +): Promise { + const { isGroup, sessionId, messageId, sequence, timestamp, elements } = options; + if (!Number.isInteger(messageId) || messageId === 0) return; + + // Defensive: tests mock `ref.messageStore` as `{ findEvent: ... } as any` + // without the full MessageStore surface. Production always has it. Bail + // quietly when the helper isn't there — the user-visible `cacheMessageMeta` + // already covers recall/delete; only `/get_msg` lookup degrades. + const storeEvent = (ref.messageStore as { storeEvent?: typeof ref.messageStore.storeEvent }).storeEvent; + if (typeof storeEvent !== 'function') return; + + try { + // We deliberately pass no URL resolvers — for a synthetic self-sent + // event the file/url fields in segments are best-effort (they're + // already what the OneBot caller passed in). Image/video URLs would + // need a real resolver to render in `/get_msg`, but the existing + // resolver is async and bound to the receive pipeline; skipping it + // means /get_msg returns the segment with the original `file` path + // and an empty `url`, which is what Lagrange does too. + const segments = await elementsToOneBotSegments(elements, isGroup, sessionId) as JsonArray; + const raw = segmentsToRawMessage(segments); + const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT; + const selfId = ref.selfId; + + const event: JsonObject = { + time: timestamp, + self_id: selfId, + post_type: 'message_sent', + message_type: isGroup ? 'group' : 'private', + sub_type: isGroup ? 'normal' : 'friend', + message_id: messageId, + message_seq: sequence, + user_id: selfId, // sender = self + message: segments, + raw_message: raw, + font: 0, + sender: { + user_id: selfId, + nickname: '', + sex: 'unknown', + age: 0, + }, + }; + if (isGroup) { + event.group_id = sessionId; + } else { + // c2c: target_id mirrors NapCat's `targetUin` field for self-sent + // events; some OneBot clients use it to disambiguate self-sent + // private messages (where user_id is self, not the peer). + event.target_id = sessionId; + } + + // Store directly via messageStore (bypassing dispatchEvent — we + // don't want to broadcast this synthetic event over the WS bridge; + // the QQ server's own echo-back is the source of truth for that). + storeEvent.call(ref.messageStore, messageId, isGroup, sessionId, sequence, eventName, event); + } catch (err) { + // Never let event-cache failures sink the send call — recall + return + // value are what callers care about; /get_msg degrading to "not found" + // is the worst case here and matches the previous behaviour. + log.warn('[OneBot] failed to cache self-sent message %d: %s', + messageId, err instanceof Error ? err.message : String(err)); + } } export async function sendPrivateMessage( @@ -138,7 +230,7 @@ export async function sendPrivateMessage( // C2C `{type:'file'}` segments can't ride on the elems[] pipeline — // c2c files live on `RichText.notOnlineFile`, parallel to elems - // (see `proto/proton/message.ts:notOnlineFile`). The element-builder + // (see `@snowluma/proto-defs/message:notOnlineFile`). The element-builder // explicitly drops them with a warn ("file send via elems[] is // group-only"), so a private message that bundled a file alongside // anything else used to either ship as "[空消息]" (only-file case, @@ -155,9 +247,9 @@ export async function sendPrivateMessage( log.warn('[OneBot] private file segment without file_id — skipped (upload first via upload_private_file)'); } - let lastReceipt: Awaited> | undefined; + let lastReceipt: Awaited> | undefined; if (nonFileElements.length > 0) { - lastReceipt = await ref.bridge.sendPrivateMessage(userId, nonFileElements); + lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements); logSentMessage(false, userId, nonFileElements); } if (fileElements.length > 0) { @@ -189,7 +281,7 @@ export async function sendPrivateMessage( fileEl.fileId, ); } - lastReceipt = await ref.bridge.sendC2cFileMessage(userId, userUid, { + lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId!, fileName, fileSize, @@ -211,6 +303,14 @@ export async function sendPrivateMessage( random: lastReceipt.random, timestamp: lastReceipt.timestamp, }); + await cacheSelfSentMessage(ref, { + isGroup: false, + sessionId: userId, + messageId, + sequence: lastReceipt.sequence, + timestamp: lastReceipt.timestamp, + elements, + }); return { messageId }; } @@ -258,9 +358,9 @@ export async function sendGroupMessage( log.warn('[OneBot] group file segment without file_id — skipped (upload first via upload_group_file)'); } - let lastReceipt: Awaited> | undefined; + let lastReceipt: Awaited> | undefined; if (nonFileElements.length > 0) { - lastReceipt = await ref.bridge.sendGroupMessage(groupId, nonFileElements); + lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements); logSentMessage(true, groupId, nonFileElements); } for (const fileEl of fileElements) { @@ -269,7 +369,7 @@ export async function sendGroupMessage( // wire. If this is the LAST element we still need a receipt so // the OneBot caller can cache the id; synthesise one from the // file_id hash + a fresh timestamp. - await ref.bridge.sendGroupFileMessage(groupId, fileEl.fileId!); + await ref.bridge.apis.groupFile.publish(groupId, fileEl.fileId!); logSentMessage(true, groupId, [fileEl]); if (!lastReceipt) { // Use a hash of the fileId as a stable pseudo-id; this gets @@ -300,6 +400,14 @@ export async function sendGroupMessage( random: lastReceipt.random, timestamp: lastReceipt.timestamp, }); + await cacheSelfSentMessage(ref, { + isGroup: true, + sessionId: groupId, + messageId, + sequence: lastReceipt.sequence, + timestamp: lastReceipt.timestamp, + elements, + }); return { messageId }; } @@ -322,9 +430,9 @@ export async function sendGroupForwardMessage( // namespace — otherwise the ARK card's res_id won't be resolvable // when the recipient taps to expand. const nodes = await parseForwardNodes(ref, messages, { groupId }); - const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId); + const forwardId = await ref.bridge.apis.forward.upload(nodes, groupId); const previewElement = buildForwardPreviewElement(forwardId, nodes, true, meta); - const receipt = await ref.bridge.sendGroupMessage(groupId, [previewElement]); + const receipt = await ref.bridge.apis.message.sendGroup(groupId, [previewElement]); const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT); ref.cacheMessageMeta(messageId, { @@ -336,6 +444,14 @@ export async function sendGroupForwardMessage( random: receipt.random, timestamp: receipt.timestamp, }); + await cacheSelfSentMessage(ref, { + isGroup: true, + sessionId: groupId, + messageId, + sequence: receipt.sequence, + timestamp: receipt.timestamp, + elements: [previewElement], + }); return { messageId, forwardId }; } @@ -350,9 +466,9 @@ export async function sendPrivateForwardMessage( // userId is plumbed through so inner image/record/video can be uploaded // under the recipient's scene (otherwise the OIDB private-image upload // has no target uid and the element builder bails). - const forwardId = await ref.bridge.uploadForwardNodes(nodes, undefined, userId); + const forwardId = await ref.bridge.apis.forward.upload(nodes, undefined, userId); const previewElement = buildForwardPreviewElement(forwardId, nodes, false, meta); - const receipt = await ref.bridge.sendPrivateMessage(userId, [previewElement]); + const receipt = await ref.bridge.apis.message.sendPrivate(userId, [previewElement]); const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT); ref.cacheMessageMeta(messageId, { @@ -364,6 +480,14 @@ export async function sendPrivateForwardMessage( random: receipt.random, timestamp: receipt.timestamp, }); + await cacheSelfSentMessage(ref, { + isGroup: false, + sessionId: userId, + messageId, + sequence: receipt.sequence, + timestamp: receipt.timestamp, + elements: [previewElement], + }); return { messageId, forwardId }; } @@ -376,7 +500,7 @@ export async function uploadForwardMessage( const nodes = await parseForwardNodes(ref, messages, { groupId }); // groupId controls the resId namespace (group vs private). Without it, // a resId minted here is unusable when later sent into a group. - const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId); + const forwardId = await ref.bridge.apis.forward.upload(nodes, groupId); return { forwardId }; } @@ -411,7 +535,7 @@ export async function forwardSingleMessage( let receipt; let messageIdOut: number; if (target.groupId) { - receipt = await ref.bridge.sendGroupMessage(target.groupId, elements); + receipt = await ref.bridge.apis.message.sendGroup(target.groupId, elements); messageIdOut = hashMessageIdInt32(receipt.sequence, target.groupId, GROUP_MESSAGE_EVENT); ref.cacheMessageMeta(messageIdOut, { isGroup: true, @@ -422,8 +546,16 @@ export async function forwardSingleMessage( random: receipt.random, timestamp: receipt.timestamp, }); + await cacheSelfSentMessage(ref, { + isGroup: true, + sessionId: target.groupId, + messageId: messageIdOut, + sequence: receipt.sequence, + timestamp: receipt.timestamp, + elements, + }); } else { - receipt = await ref.bridge.sendPrivateMessage(target.userId!, elements); + receipt = await ref.bridge.apis.message.sendPrivate(target.userId!, elements); messageIdOut = hashMessageIdInt32(receipt.sequence, target.userId!, PRIVATE_MESSAGE_EVENT); ref.cacheMessageMeta(messageIdOut, { isGroup: false, @@ -434,6 +566,14 @@ export async function forwardSingleMessage( random: receipt.random, timestamp: receipt.timestamp, }); + await cacheSelfSentMessage(ref, { + isGroup: false, + sessionId: target.userId!, + messageId: messageIdOut, + sequence: receipt.sequence, + timestamp: receipt.timestamp, + elements, + }); } return { messageId: messageIdOut }; @@ -530,7 +670,7 @@ export async function getForwardMessage( ref: OneBotInstanceContext, resId: string, ): Promise { - const nodes = await ref.bridge.fetchForwardNodes(resId); + const nodes = await ref.bridge.apis.forward.fetch(resId); const results: JsonObject[] = []; for (const node of nodes) { const isGroup = node.messageType === 'group' || (node.groupId !== undefined && node.groupId > 0); diff --git a/packages/core/src/onebot/modules/request-actions.ts b/packages/onebot/src/modules/request-actions.ts similarity index 85% rename from packages/core/src/onebot/modules/request-actions.ts rename to packages/onebot/src/modules/request-actions.ts index 9dcdb8b9..5d15c8c9 100644 --- a/packages/core/src/onebot/modules/request-actions.ts +++ b/packages/onebot/src/modules/request-actions.ts @@ -1,4 +1,4 @@ -import type { BridgeInterface } from '../../bridge/bridge-interface'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; export async function handleGroupAddRequest( bridge: BridgeInterface, @@ -15,7 +15,7 @@ export async function handleGroupAddRequest( if (!groupId) throw new Error('invalid group_id in flag'); if (!targetUid) throw new Error('invalid request target in flag'); - const requests = await bridge.fetchGroupRequests(); + const requests = await bridge.apis.contacts.fetchGroupRequests(); const matching = requests.find((r) => { if (r.groupId !== groupId) return false; if (requestType === 'add') return r.targetUid === targetUid; @@ -27,7 +27,7 @@ export async function handleGroupAddRequest( throw new Error('matching group request not found'); } - await bridge.setGroupAddRequest( + await bridge.apis.groupAdmin.setAddRequest( groupId, matching.sequence, matching.eventType, diff --git a/packages/core/src/onebot/network/adapter.ts b/packages/onebot/src/network/adapter.ts similarity index 81% rename from packages/core/src/onebot/network/adapter.ts rename to packages/onebot/src/network/adapter.ts index d502d451..7e194d53 100644 --- a/packages/core/src/onebot/network/adapter.ts +++ b/packages/onebot/src/network/adapter.ts @@ -1,15 +1,6 @@ -// Base abstractions for OneBot network adapters. -// -// Modeled on NapCat's `IOB11NetworkAdapter` so each entry under -// `config.networks.{httpServers,httpClients,wsServers,wsClients}` becomes -// exactly one adapter instance, identified by `name`. The previous design -// rolled multiple servers/clients into a single transport class; the -// per-entry split makes hot-reload, lifecycle, and event isolation much -// simpler to reason about. - import type { ApiHandler } from '../api-handler'; -import type { JsonObject, NetworkBase } from '../types'; import type { DispatchPayload } from '../event-filter'; +import type { JsonObject, NetworkBase } from '../types'; export interface NetworkAdapterContext { /** Self UIN as string — written into outbound headers. */ diff --git a/packages/core/src/onebot/network/http-post-adapter.ts b/packages/onebot/src/network/http-post-adapter.ts similarity index 94% rename from packages/core/src/onebot/network/http-post-adapter.ts rename to packages/onebot/src/network/http-post-adapter.ts index 15ec6ff1..9f47844f 100644 --- a/packages/core/src/onebot/network/http-post-adapter.ts +++ b/packages/onebot/src/network/http-post-adapter.ts @@ -1,16 +1,11 @@ -// Outbound HTTP webhook adapter — one instance per `httpClients[]` entry. -// -// Forwards every event to the configured URL via HTTP POST and interprets -// any JSON response body as a OneBot v11 quick-operation. - -import type { HttpClientNetwork, JsonObject } from '../types'; +import { createLogger, type Logger } from '@snowluma/common/logger'; import { pickDispatchJson, resolveReportOptions, type DispatchPayload, type EventReportOptions, } from '../event-filter'; -import { createLogger, type Logger } from '../../utils/logger'; +import type { HttpClientNetwork, JsonObject } from '../types'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; import { executeQuickOperation } from './quick-operation'; diff --git a/packages/core/src/onebot/network/http-server-adapter.ts b/packages/onebot/src/network/http-server-adapter.ts similarity index 96% rename from packages/core/src/onebot/network/http-server-adapter.ts rename to packages/onebot/src/network/http-server-adapter.ts index 8291b24d..565a07b1 100644 --- a/packages/core/src/onebot/network/http-server-adapter.ts +++ b/packages/onebot/src/network/http-server-adapter.ts @@ -1,18 +1,12 @@ -// Inbound HTTP API server — one instance per `httpServers[]` entry. -// -// Pure request/response: incoming POST/GET maps to `ApiHandler.handle`, -// the response body is JSON-serialized back. `onEvent` is a deliberate -// no-op since this transport never pushes events. - import { createServer, type IncomingMessage, type Server, type ServerResponse, } from 'http'; -import type { HttpServerNetwork, JsonObject, JsonValue } from '../types'; +import { createLogger, type Logger } from '@snowluma/common/logger'; import type { DispatchPayload } from '../event-filter'; -import { createLogger, type Logger } from '../../utils/logger'; +import type { HttpServerNetwork, JsonObject, JsonValue } from '../types'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; import { isAuthorized, normalizePath } from './utils'; @@ -263,4 +257,4 @@ function writeJson(res: ServerResponse, statusCode: number, data: unknown): void res.statusCode = statusCode; res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.end(JSON.stringify(data)); -} \ No newline at end of file +} diff --git a/packages/core/src/onebot/network/index.ts b/packages/onebot/src/network/index.ts similarity index 89% rename from packages/core/src/onebot/network/index.ts rename to packages/onebot/src/network/index.ts index ccd5b2a3..0e5aa631 100644 --- a/packages/core/src/onebot/network/index.ts +++ b/packages/onebot/src/network/index.ts @@ -1,9 +1,8 @@ -// Public surface for the OneBot network package. - export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; -export { OneBotNetworkManager } from './network-manager'; -export { WsServerAdapter } from './ws-server-adapter'; -export { WsClientAdapter } from './ws-client-adapter'; -export { HttpServerAdapter } from './http-server-adapter'; export { HttpPostAdapter } from './http-post-adapter'; +export { HttpServerAdapter } from './http-server-adapter'; +export { OneBotNetworkManager } from './network-manager'; export { executeQuickOperation } from './quick-operation'; +export { WsClientAdapter } from './ws-client-adapter'; +export { WsServerAdapter } from './ws-server-adapter'; + diff --git a/packages/core/src/onebot/network/network-manager.ts b/packages/onebot/src/network/network-manager.ts similarity index 90% rename from packages/core/src/onebot/network/network-manager.ts rename to packages/onebot/src/network/network-manager.ts index b1e5a621..5100d86b 100644 --- a/packages/core/src/onebot/network/network-manager.ts +++ b/packages/onebot/src/network/network-manager.ts @@ -1,13 +1,7 @@ -// OneBot network manager. -// -// Mirrors NapCat's `OB11NetworkManager`: holds a `Map`, fans -// events out to every active adapter in parallel, and provides primitives -// the OneBot instance uses to register, hot-reload, and tear adapters down. - -import type { JsonObject, NetworkBase } from '../types'; +import { createLogger } from '@snowluma/common/logger'; import { buildDispatchPayload } from '../event-filter'; +import type { JsonObject, NetworkBase } from '../types'; import { IOneBotNetworkAdapter } from './adapter'; -import { createLogger } from '../../utils/logger'; const log = createLogger('OneBot.Network'); diff --git a/packages/core/src/onebot/network/quick-operation.ts b/packages/onebot/src/network/quick-operation.ts similarity index 89% rename from packages/core/src/onebot/network/quick-operation.ts rename to packages/onebot/src/network/quick-operation.ts index 272ce9f9..27446a3b 100644 --- a/packages/core/src/onebot/network/quick-operation.ts +++ b/packages/onebot/src/network/quick-operation.ts @@ -1,10 +1,3 @@ -// OneBot v11 hidden API: `.handle_quick_operation`. -// -// When an HTTP POST event report receives a JSON body in response, that body -// is interpreted as a "quick operation" — short-cuts to common follow-up -// API calls (reply, recall, ban, kick, approve/reject). Spec: -// https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md - import type { ApiHandler } from '../api-handler'; import type { JsonObject, JsonValue } from '../types'; diff --git a/packages/core/src/onebot/network/utils.ts b/packages/onebot/src/network/utils.ts similarity index 97% rename from packages/core/src/onebot/network/utils.ts rename to packages/onebot/src/network/utils.ts index 5e229ec3..197c53c8 100644 --- a/packages/core/src/onebot/network/utils.ts +++ b/packages/onebot/src/network/utils.ts @@ -1,7 +1,5 @@ -// Helpers shared between OneBot network adapters. - -import type { IncomingMessage } from 'http'; 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 { diff --git a/packages/core/src/onebot/network/ws-client-adapter.ts b/packages/onebot/src/network/ws-client-adapter.ts similarity index 93% rename from packages/core/src/onebot/network/ws-client-adapter.ts rename to packages/onebot/src/network/ws-client-adapter.ts index c38120e0..5b0b11ff 100644 --- a/packages/core/src/onebot/network/ws-client-adapter.ts +++ b/packages/onebot/src/network/ws-client-adapter.ts @@ -1,11 +1,5 @@ -// Reverse (client) WebSocket adapter — one instance per `wsClients[]` entry. -// -// Connects out to a remote OneBot endpoint, manages reconnects, forwards -// pushed events on `onEvent`, and dispatches incoming API messages to the -// shared ApiHandler. - import { WebSocket } from '@snowluma/websocket'; -import type { WsClientNetwork, WsRole, JsonObject } from '../types'; +import { createLogger, type Logger } from '@snowluma/common/logger'; import { pickDispatchJson, resolveReportOptions, @@ -13,7 +7,7 @@ import { type DispatchPayload, type EventReportOptions, } from '../event-filter'; -import { createLogger, type Logger } from '../../utils/logger'; +import type { JsonObject, WsClientNetwork, WsRole } from '../types'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; import { rawDataToString, safeClose, safeSend } from './utils'; diff --git a/packages/core/src/onebot/network/ws-server-adapter.ts b/packages/onebot/src/network/ws-server-adapter.ts similarity index 91% rename from packages/core/src/onebot/network/ws-server-adapter.ts rename to packages/onebot/src/network/ws-server-adapter.ts index d4686bb0..6368fa99 100644 --- a/packages/core/src/onebot/network/ws-server-adapter.ts +++ b/packages/onebot/src/network/ws-server-adapter.ts @@ -1,12 +1,6 @@ -// Forward (server) WebSocket adapter — one instance per `wsServers[]` entry. -// -// Each adapter owns its own `WebSocketServer`, accepts inbound forward -// connections (api / event / universal roles), and pushes events to all live -// event-receiving sockets when `onEvent` fires. - import { WebSocket, WebSocketServer } from '@snowluma/websocket'; import type { IncomingMessage } from 'http'; -import type { WsRole, WsServerNetwork, JsonObject } from '../types'; +import { createLogger, type Logger } from '@snowluma/common/logger'; import { pickDispatchJson, resolveReportOptions, @@ -14,9 +8,9 @@ import { type DispatchPayload, type EventReportOptions, } from '../event-filter'; -import { createLogger, type Logger } from '../../utils/logger'; +import type { JsonObject, WsRole, WsServerNetwork } from '../types'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; -import { isAuthorized, parseRequestPath, rawDataToString, safeClose, safeSend, normalizePath } from './utils'; +import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils'; const moduleLog = createLogger('OneBot.WS-Server'); diff --git a/packages/core/src/onebot/types.ts b/packages/onebot/src/types.ts similarity index 85% rename from packages/core/src/onebot/types.ts rename to packages/onebot/src/types.ts index 1523d367..adf3bfca 100644 --- a/packages/core/src/onebot/types.ts +++ b/packages/onebot/src/types.ts @@ -1,9 +1,9 @@ -export type JsonPrimitive = string | number | boolean | null; -export type JsonValue = JsonPrimitive | JsonObject | JsonArray; -export interface JsonObject { - [key: string]: JsonValue; -} -export type JsonArray = JsonValue[]; +// Plain JSON types now live in @snowluma/common/json so @snowluma/bridge +// (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'; export interface ApiResponse { status: 'ok' | 'failed'; diff --git a/packages/core/tests/api-handler-logging.test.ts b/packages/onebot/tests/api-handler-logging.test.ts similarity index 96% rename from packages/core/tests/api-handler-logging.test.ts rename to packages/onebot/tests/api-handler-logging.test.ts index 6e3ef718..72d3339a 100644 --- a/packages/core/tests/api-handler-logging.test.ts +++ b/packages/onebot/tests/api-handler-logging.test.ts @@ -5,9 +5,9 @@ // from blowing the line width. import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { ApiHandler } from '../src/onebot/api-handler'; -import { subscribeLogs, type LogEntry } from '../src/utils/logger'; -import { summarizeParams } from '../src/utils/log-summary'; +import { ApiHandler } from '../src/api-handler'; +import { subscribeLogs, type LogEntry } from '@snowluma/common/logger'; +import { summarizeParams } from '@snowluma/common/log-summary'; // Minimal context — we never reach the real action handlers; we // register our own via registerAction. diff --git a/packages/core/tests/config.test.ts b/packages/onebot/tests/config.test.ts similarity index 99% rename from packages/core/tests/config.test.ts rename to packages/onebot/tests/config.test.ts index 6a667f50..5bd9128c 100644 --- a/packages/core/tests/config.test.ts +++ b/packages/onebot/tests/config.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import fs from 'fs'; import os from 'os'; import path from 'path'; -import { loadOneBotConfig, makeDefaultOneBotConfig, saveOneBotConfig } from '../src/onebot/config'; +import { loadOneBotConfig, makeDefaultOneBotConfig, saveOneBotConfig } from '../src/config'; const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/; diff --git a/packages/core/tests/onebot/contact-actions.test.ts b/packages/onebot/tests/contact-actions.test.ts similarity index 86% rename from packages/core/tests/onebot/contact-actions.test.ts rename to packages/onebot/tests/contact-actions.test.ts index ea44dec9..a6f17597 100644 --- a/packages/core/tests/onebot/contact-actions.test.ts +++ b/packages/onebot/tests/contact-actions.test.ts @@ -7,7 +7,7 @@ import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, -} from '../../src/bridge/qq-info'; +} from '@snowluma/bridge/qq-info'; import { getFriendList, getGroupInfo, @@ -16,8 +16,8 @@ import { getGroupMemberList, getLoginInfo, getStrangerInfo, -} from '../../src/onebot/modules/contact-actions'; -import type { OneBotInstanceContext } from '../../src/onebot/instance-context'; +} from '../src/modules/contact-actions'; +import type { OneBotInstanceContext } from '../src/instance-context'; /** * A typed BridgeInterface where every property is undefined by default; @@ -25,8 +25,28 @@ import type { OneBotInstanceContext } from '../../src/onebot/instance-context'; * fail loudly if they exercise a code path the fake hasn't been told * about. Tests just spread the methods they care about. */ -function fakeBridge(overrides: Partial = {}): BridgeInterface { - return new Proxy(overrides as BridgeInterface, { +// `apisAutoPromote` lets tests written before #6 (which stubbed flat +// methods like `fetchFriendList: vi.fn()` on bridge directly) keep +// working without restructuring — the helper rewrites flat stubs into +// the new `apis..method` shape automatically. New code can also +// pass `apis: { contacts: { … } }` explicitly; the two merge. +const APIS_ROUTING: Record = { + fetchFriendList: 'contacts', fetchGroupList: 'contacts', + fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts', + fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts', +}; + +function fakeBridge(overrides: Record = {}): BridgeInterface { + const apisSynth: Record> = {}; + for (const [k, v] of Object.entries(overrides)) { + const area = APIS_ROUTING[k]; + if (area) { + if (!apisSynth[area]) apisSynth[area] = {}; + apisSynth[area][k] = v; + } + } + const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } }; + return new Proxy(merged as BridgeInterface, { get(target, prop) { if (prop in target) return (target as any)[prop]; throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`); @@ -99,7 +119,7 @@ describe('onebot/contact-actions / getFriendList', () => { }); const out = await getFriendList(bridge); expect(out).toEqual([{ user_id: 22222, nickname: 'alice', remark: 'best-friend' }]); - expect(bridge.fetchFriendList).toHaveBeenCalledOnce(); + expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalledOnce(); }); it('falls back to identity.friends on fetch failure', async () => { @@ -117,7 +137,7 @@ describe('onebot/contact-actions / getGroupList', () => { it('triggers fetch when the in-memory roster is empty', async () => { const fetched = [makeGroup(100, 'Group A')]; // `groups` starts empty; the fetch callback flips it to mimic - // bridge.fetchGroupList writing back through identity.rememberGroups. + // bridge.apis.contacts.fetchGroupList writing back through identity.rememberGroups. let groups: QQGroupInfo[] = []; const bridge = fakeBridge({ fetchGroupList: vi.fn(async () => { groups = fetched; return fetched; }), @@ -126,7 +146,7 @@ describe('onebot/contact-actions / getGroupList', () => { }), }); const out = await getGroupList(bridge); - expect(bridge.fetchGroupList).toHaveBeenCalledOnce(); + expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce(); expect(out).toEqual([{ group_id: 100, group_name: 'Group A', member_count: 0, max_member_count: 500, @@ -140,7 +160,7 @@ describe('onebot/contact-actions / getGroupList', () => { identity: fakeIdentity({ groups: cached }), }); await getGroupList(bridge); - expect(bridge.fetchGroupList).not.toHaveBeenCalled(); + expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled(); }); it('forces fetch when noCache=true even with a populated cache', async () => { @@ -150,7 +170,7 @@ describe('onebot/contact-actions / getGroupList', () => { identity: fakeIdentity({ groups: cached }), }); await getGroupList(bridge, true); - expect(bridge.fetchGroupList).toHaveBeenCalledOnce(); + expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce(); }); it('serves the stale cache when the fetch path throws', async () => { @@ -174,7 +194,7 @@ describe('onebot/contact-actions / getGroupInfo', () => { }); const out = await getGroupInfo(bridge, 500); expect(out).toMatchObject({ group_id: 500, group_name: 'Group E' }); - expect(bridge.fetchGroupList).not.toHaveBeenCalled(); + expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled(); }); it('triggers fetch when the group is unknown to the cache', async () => { @@ -236,7 +256,6 @@ describe('onebot/contact-actions / getGroupMemberList', () => { describe('onebot/contact-actions / getGroupMemberInfo', () => { it('returns the cached member when present and noCache is false', async () => { const member = makeMember(44, 'dave', 'D'); - const cached = makeGroup(1000, '', [member]); const bridge = fakeBridge({ fetchGroupMemberList: vi.fn(async () => []), identity: fakeIdentity({ @@ -246,7 +265,7 @@ describe('onebot/contact-actions / getGroupMemberInfo', () => { }); const out = await getGroupMemberInfo(bridge, 1000, 44); expect(out).toMatchObject({ user_id: 44, nickname: 'dave', card: 'D' }); - expect(bridge.fetchGroupMemberList).not.toHaveBeenCalled(); + expect(bridge.apis.contacts.fetchGroupMemberList).not.toHaveBeenCalled(); }); it('triggers fetch when member is unknown and re-queries the cache', async () => { diff --git a/packages/core/tests/event-converter.test.ts b/packages/onebot/tests/event-converter.test.ts similarity index 99% rename from packages/core/tests/event-converter.test.ts rename to packages/onebot/tests/event-converter.test.ts index 1887d067..57a6f55f 100644 --- a/packages/core/tests/event-converter.test.ts +++ b/packages/onebot/tests/event-converter.test.ts @@ -3,20 +3,20 @@ import { convertEvent, elementsToOneBotSegments, type ConverterContext, -} from '../src/onebot/event-converter'; +} from '../src/event-converter'; import { buildDispatchPayload, pickDispatchJson, resolveReportOptions, shapeEventForAdapter, -} from '../src/onebot/event-filter'; +} from '../src/event-filter'; import type { FriendMessage, GroupMessage, MessageElement, QQEventVariant, TempMessage, -} from '../src/bridge/events'; +} from '@snowluma/bridge/events'; const SELF_ID = 10001; const PEER_UIN = 22222; diff --git a/packages/core/tests/event-pipeline.test.ts b/packages/onebot/tests/event-pipeline.test.ts similarity index 91% rename from packages/core/tests/event-pipeline.test.ts rename to packages/onebot/tests/event-pipeline.test.ts index 04794b2d..b4f09bec 100644 --- a/packages/core/tests/event-pipeline.test.ts +++ b/packages/onebot/tests/event-pipeline.test.ts @@ -1,25 +1,25 @@ import { describe, expect, it, vi } from 'vitest'; -import { BridgeEventBus } from '../src/bridge/event-bus'; +import { BridgeEventBus } from '@snowluma/bridge/event-bus'; // Wrap convertEvent in a vi.fn that delegates to the real impl by // default, so one test can override it to return null without making // the others lose the real conversion behavior. -vi.mock('../src/onebot/event-converter', async () => { - const actual = await vi.importActual('../src/onebot/event-converter'); +vi.mock('../src/event-converter', async () => { + const actual = await vi.importActual('../src/event-converter'); return { ...actual, convertEvent: vi.fn(actual.convertEvent) }; }); -import { convertEvent, type ConverterContext } from '../src/onebot/event-converter'; -import { registerEventPipeline } from '../src/onebot/event-pipeline'; -import type { OneBotInstanceContext } from '../src/onebot/instance-context'; +import { convertEvent, type ConverterContext } from '../src/event-converter'; +import { registerEventPipeline } from '../src/event-pipeline'; +import type { OneBotInstanceContext } from '../src/instance-context'; import type { FriendMessage, GroupMessage, GroupMemberJoin, TempMessage, QQEventVariant, -} from '../src/bridge/events'; -import type { JsonObject, MessageMeta } from '../src/onebot/types'; +} from '@snowluma/bridge/events'; +import type { JsonObject, MessageMeta } from '../src/types'; const SELF_UIN = '10001'; const SELF_ID = 10001; diff --git a/packages/core/tests/onebot/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts similarity index 88% rename from packages/core/tests/onebot/extended-actions.test.ts rename to packages/onebot/tests/extended-actions.test.ts index 95ddbb8e..13441786 100644 --- a/packages/core/tests/onebot/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -5,10 +5,10 @@ // param coercion, retcode shape) is part of what's under test. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { ApiHandler, type ApiActionContext } from '../../src/onebot/api-handler'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; -import type { GroupRequestInfo } from '../../src/bridge/qq-info'; -import type { MessageMeta } from '../../src/onebot/types'; +import type { GroupRequestInfo } from '@snowluma/bridge/qq-info'; +import type { MessageMeta } from '../src/types'; function fakeMeta(overrides: Partial = {}): MessageMeta { return { @@ -28,8 +28,61 @@ function fakeMeta(overrides: Partial = {}): MessageMeta { * pre-stubbed for the test. Same pattern as contact-actions.test.ts — * keeps tests honest about which surface they actually need. */ -function fakeBridge(overrides: Partial = {}): BridgeInterface { - return new Proxy(overrides as BridgeInterface, { +// Maps flat method names → [area, newMethodName] on the ApiHub under +// the #6 refactor. Auto-promotion lets tests written against the +// pre-refactor flat surface (`fetchGroupRequests: vi.fn()`) keep +// working without per-test restructure, even when the new method name +// drops the redundant `Group`/`File` prefix. +const APIS_ROUTING: Record = { + fetchFriendList: ['contacts', 'fetchFriendList'], + fetchGroupList: ['contacts', 'fetchGroupList'], + fetchGroupMemberList: ['contacts', 'fetchGroupMemberList'], + fetchUserProfile: ['contacts', 'fetchUserProfile'], + fetchGroupRequests: ['contacts', 'fetchGroupRequests'], + fetchDownloadRKeys: ['contacts', 'fetchDownloadRKeys'], + // GroupFileApi: methods drop `Group`/`File`/`Folder` suffix where + // the area name already says it. + deleteGroupFileFolder: ['groupFile', 'deleteFolder'], + fetchGroupPttUrlByNode: ['groupFile', 'getPttUrl'], + // InteractionApi: methods drop the redundant `Group` prefix. + sendLike: ['interaction', 'sendLike'], + setGroupReaction: ['interaction', 'setReaction'], + // ProfileApi: a few methods rename (getProfileLike → getLike). + setOnlineStatus: ['profile', 'setOnlineStatus'], + setDiyOnlineStatus: ['profile', 'setDiyOnlineStatus'], + setProfile: ['profile', 'setProfile'], + setSelfLongNick: ['profile', 'setSelfLongNick'], + setInputStatus: ['profile', 'setInputStatus'], + setAvatar: ['profile', 'setAvatar'], + setGroupAvatar: ['profile', 'setGroupAvatar'], + fetchCustomFace: ['profile', 'fetchCustomFace'], + getProfileLike: ['profile', 'getLike'], + getUnidirectionalFriendList: ['profile', 'getUnidirectionalFriendList'], + // FriendApi: handleRequest/delete/setRemark. + setFriendRemark: ['friend', 'setRemark'], + deleteFriend: ['friend', 'delete'], + setFriendAddRequest: ['friend', 'handleRequest'], + // ExtrasApi: group todo / stranger status / AI voice. + setGroupTodo: ['extras', 'setGroupTodo'], + completeGroupTodo: ['extras', 'completeGroupTodo'], + cancelGroupTodo: ['extras', 'cancelGroupTodo'], + getStrangerStatus: ['extras', 'getStrangerStatus'], + fetchAiVoiceList: ['extras', 'fetchAiVoiceList'], + fetchAiVoice: ['extras', 'fetchAiVoice'], +}; + +function fakeBridge(overrides: Record = {}): BridgeInterface { + const apisSynth: Record> = {}; + for (const [k, v] of Object.entries(overrides)) { + const route = APIS_ROUTING[k]; + if (route) { + const [area, newName] = route; + if (!apisSynth[area]) apisSynth[area] = {}; + apisSynth[area][newName] = v; + } + } + const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } }; + return new Proxy(merged as BridgeInterface, { get(target, prop) { if (prop in target) return (target as any)[prop]; throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`); diff --git a/packages/core/tests/onebot/forward-nested.test.ts b/packages/onebot/tests/forward-nested.test.ts similarity index 91% rename from packages/core/tests/onebot/forward-nested.test.ts rename to packages/onebot/tests/forward-nested.test.ts index 39863dd5..d47cf015 100644 --- a/packages/core/tests/onebot/forward-nested.test.ts +++ b/packages/onebot/tests/forward-nested.test.ts @@ -15,11 +15,11 @@ import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; -import type { OneBotInstanceContext } from '../../src/onebot/instance-context'; +import type { OneBotInstanceContext } from '../src/instance-context'; import { sendGroupForwardMessage, sendPrivateForwardMessage, -} from '../../src/onebot/modules/message-actions'; +} from '../src/modules/message-actions'; function fakeBridge(overrides: Partial = {}): BridgeInterface { return new Proxy(overrides as BridgeInterface, { @@ -53,7 +53,7 @@ describe('forward — nested {type:"node"} content', () => { messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, })); - const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any); + const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any); const ctx = makeCtx(bridge); const messages = [{ @@ -105,7 +105,7 @@ describe('forward — nested {type:"node"} content', () => { messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, })); - const bridge = fakeBridge({ uploadForwardNodes, sendPrivateMessage } as any); + const bridge = fakeBridge({ apis: { message: { sendPrivate: sendPrivateMessage }, forward: { upload: uploadForwardNodes } } } as any); const ctx = makeCtx(bridge); const messages = [{ @@ -143,7 +143,7 @@ describe('forward — nested {type:"node"} content', () => { const sendGroupMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, })); - const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any); + const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any); const ctx = makeCtx(bridge); function wrap(content: any, depth: number): any { @@ -167,7 +167,7 @@ describe('forward — nested {type:"node"} content', () => { const sendGroupMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, })); - const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any); + const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any); const ctx = makeCtx(bridge); const messages = [ @@ -195,7 +195,7 @@ describe('forward — nested {type:"node"} content', () => { const sendGroupMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, })); - const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any); + const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any); const ctx = makeCtx(bridge); const messages = [{ diff --git a/packages/core/tests/group-msg-emoji-like.test.ts b/packages/onebot/tests/group-msg-emoji-like.test.ts similarity index 90% rename from packages/core/tests/group-msg-emoji-like.test.ts rename to packages/onebot/tests/group-msg-emoji-like.test.ts index a986ac1d..e925ea1a 100644 --- a/packages/core/tests/group-msg-emoji-like.test.ts +++ b/packages/onebot/tests/group-msg-emoji-like.test.ts @@ -6,16 +6,16 @@ // - formatEvent prints something readable in the [Event] log import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { protoEncode } from '../src/protobuf/decode'; -import { GroupReactNotifySchema } from '../src/bridge/proto/notify'; -import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc'; -import type { MsgPushContext } from '../src/bridge/msg-push/context'; -import { IdentityService } from '../src/bridge/identity-service'; -import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '../src/bridge/events'; -import { convertGroupMsgEmojiLike } from '../src/onebot/event-converter/to-notice'; -import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/onebot/message-id'; -import { formatEvent } from '../src/utils/event-format'; -import { subscribeLogs, type LogEntry } from '../src/utils/logger'; +import { protobuf_encode } from '@snowluma/proton'; +import type { GroupReactNotify } from '@snowluma/proto-defs/notify'; +import { decodeEvent0x2DC } from '@snowluma/bridge/msg-push/decoders/event-0x2dc'; +import type { MsgPushContext } from '@snowluma/bridge/msg-push/context'; +import { IdentityService } from '@snowluma/bridge/identity-service'; +import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '@snowluma/bridge/events'; +import { convertGroupMsgEmojiLike } from '../src/event-converter/to-notice'; +import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/message-id'; +import { formatEvent } from '@snowluma/bridge/format'; +import { subscribeLogs, type LogEntry } from '@snowluma/common/logger'; const SELF_UIN = '10001'; const GROUP_ID = 123456789; @@ -28,7 +28,7 @@ function makeIdentity(): IdentityService { * a 7-byte magic prefix followed by an encoded GroupReactNotify. */ function buildReactContent(notify: Record): Uint8Array { const prefix = new Uint8Array([0, 0, 0, 0, 0, 0, 0]); - const body = protoEncode(notify as never, GroupReactNotifySchema); + const body = protobuf_encode(notify as GroupReactNotify); const out = new Uint8Array(prefix.length + body.length); out.set(prefix, 0); out.set(body, prefix.length); diff --git a/packages/core/tests/http-server-content-type.test.ts b/packages/onebot/tests/http-server-content-type.test.ts similarity index 96% rename from packages/core/tests/http-server-content-type.test.ts rename to packages/onebot/tests/http-server-content-type.test.ts index 71d7ea26..49207745 100644 --- a/packages/core/tests/http-server-content-type.test.ts +++ b/packages/onebot/tests/http-server-content-type.test.ts @@ -4,9 +4,9 @@ import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest'; import http from 'http'; -import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter'; -import type { NetworkAdapterContext } from '../src/onebot/network/adapter'; -import type { HttpServerNetwork } from '../src/onebot/types'; +import { HttpServerAdapter } from '../src/network/http-server-adapter'; +import type { NetworkAdapterContext } from '../src/network/adapter'; +import type { HttpServerNetwork } from '../src/types'; // ─── Helpers ─── diff --git a/packages/core/tests/http-server-hot-reload.test.ts b/packages/onebot/tests/http-server-hot-reload.test.ts similarity index 97% rename from packages/core/tests/http-server-hot-reload.test.ts rename to packages/onebot/tests/http-server-hot-reload.test.ts index 9509541b..beb6acfe 100644 --- a/packages/core/tests/http-server-hot-reload.test.ts +++ b/packages/onebot/tests/http-server-hot-reload.test.ts @@ -9,9 +9,9 @@ import { describe, expect, it, vi, afterEach } from 'vitest'; import http from 'http'; import type { AddressInfo } from 'net'; -import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter'; -import { NetworkReloadType, type NetworkAdapterContext } from '../src/onebot/network/adapter'; -import type { HttpServerNetwork } from '../src/onebot/types'; +import { HttpServerAdapter } from '../src/network/http-server-adapter'; +import { NetworkReloadType, type NetworkAdapterContext } from '../src/network/adapter'; +import type { HttpServerNetwork } from '../src/types'; function fakeCtx(): NetworkAdapterContext { return { diff --git a/packages/core/tests/media-indexer.test.ts b/packages/onebot/tests/media-indexer.test.ts similarity index 97% rename from packages/core/tests/media-indexer.test.ts rename to packages/onebot/tests/media-indexer.test.ts index 7a9a0a61..1498c565 100644 --- a/packages/core/tests/media-indexer.test.ts +++ b/packages/onebot/tests/media-indexer.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi } from 'vitest'; -import { MediaIndexer } from '../src/onebot/media-indexer'; -import type { MessageElement } from '../src/bridge/events'; +import { MediaIndexer } from '../src/media-indexer'; +import type { MessageElement } from '@snowluma/bridge/events'; function makeMediaStore() { return { diff --git a/packages/core/tests/media-store.test.ts b/packages/onebot/tests/media-store.test.ts similarity index 98% rename from packages/core/tests/media-store.test.ts rename to packages/onebot/tests/media-store.test.ts index 05fc8750..29ce7794 100644 --- a/packages/core/tests/media-store.test.ts +++ b/packages/onebot/tests/media-store.test.ts @@ -1,11 +1,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import fs from 'fs'; import path from 'path'; -import { MediaStore } from '../src/onebot/media-store'; -import { convertEvent, type ConverterContext } from '../src/onebot/event-converter'; -import type { GroupMessage, FriendMessage, MessageElement } from '../src/bridge/events'; +import { MediaStore } from '../src/media-store'; +import { convertEvent, type ConverterContext } from '../src/event-converter'; +import type { GroupMessage, FriendMessage, MessageElement } from '@snowluma/bridge/events'; -const SELF_UIN = '10001'; const SELF_ID = 10001; const PEER_UIN = 22222; const GROUP_ID = 99999; diff --git a/packages/core/tests/media-url-resolver.test.ts b/packages/onebot/tests/media-url-resolver.test.ts similarity index 73% rename from packages/core/tests/media-url-resolver.test.ts rename to packages/onebot/tests/media-url-resolver.test.ts index 1e167f82..8c24da19 100644 --- a/packages/core/tests/media-url-resolver.test.ts +++ b/packages/onebot/tests/media-url-resolver.test.ts @@ -1,19 +1,28 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { MediaUrlResolver } from '../src/onebot/media-url-resolver'; -import type { MessageElement } from '../src/bridge/events'; +import { MediaUrlResolver } from '../src/media-url-resolver'; +import type { MessageElement } from '@snowluma/bridge/events'; // Minimal stand-ins for the two collaborators. Each test wires whatever // subset of Bridge methods the element type exercises. - +// +// MediaUrlResolver now reaches `bridge.apis.groupFile.{getUrl, +// getPrivateUrl, getPttUrl, getPrivatePttUrl, getVideoUrl, +// getPrivateVideoUrl}` per the #6 Api-on-ctx refactor. The helper here +// builds an `apis.groupFile` stub directly so tests can keep asserting +// "which file/url helper got called" without going through the +// `mockBridge` shared fixture. function makeBridge(overrides: Record> = {}) { return { - fetchGroupFileUrl: vi.fn(async () => 'http://group/file'), - fetchPrivateFileUrl: vi.fn(async () => 'http://private/file'), - fetchGroupPttUrlByNode: vi.fn(async () => 'http://group/ptt'), - fetchPrivatePttUrlByNode: vi.fn(async () => 'http://private/ptt'), - fetchGroupVideoUrlByNode: vi.fn(async () => 'http://group/video'), - fetchPrivateVideoUrlByNode: vi.fn(async () => 'http://private/video'), - ...overrides, + apis: { + groupFile: { + getUrl: overrides.getUrl ?? vi.fn(async () => 'http://group/file'), + getPrivateUrl: overrides.getPrivateUrl ?? vi.fn(async () => 'http://private/file'), + getPttUrl: overrides.getPttUrl ?? vi.fn(async () => 'http://group/ptt'), + getPrivatePttUrl: overrides.getPrivatePttUrl ?? vi.fn(async () => 'http://private/ptt'), + getVideoUrl: overrides.getVideoUrl ?? vi.fn(async () => 'http://group/video'), + getPrivateVideoUrl: overrides.getPrivateVideoUrl ?? vi.fn(async () => 'http://private/video'), + }, + }, }; } @@ -34,7 +43,7 @@ describe('MediaUrlResolver — file element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'file', fileId: 'fid-x' }; const out = await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupFileUrl).toHaveBeenCalledWith(12345, 'fid-x'); + expect(bridge.apis.groupFile.getUrl).toHaveBeenCalledWith(12345, 'fid-x'); expect(element.url).toBe('http://group/file'); expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce(); expect(out).toBe('http://group/file'); @@ -44,7 +53,7 @@ describe('MediaUrlResolver — file element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'file', fileId: 'fid-x', fileHash: 'hash-y' }; await resolver.resolve(element, false, 67890); - expect(bridge.fetchPrivateFileUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y'); + expect(bridge.apis.groupFile.getPrivateUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y'); expect(element.url).toBe('http://private/file'); }); @@ -52,7 +61,7 @@ describe('MediaUrlResolver — file element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'file', fileId: 'fid-x' }; await resolver.resolve(element, false, 67890); - expect(bridge.fetchPrivateFileUrl).not.toHaveBeenCalled(); + expect(bridge.apis.groupFile.getPrivateUrl).not.toHaveBeenCalled(); expect(element.url).toBe(''); }); }); @@ -66,7 +75,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE }; await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupPttUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE); + expect(bridge.apis.groupFile.getPttUrl).toHaveBeenCalledWith(12345, MEDIA_NODE); expect(element.url).toBe('http://group/ptt'); }); @@ -74,7 +83,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE }; await resolver.resolve(element, false, 67890); - expect(bridge.fetchPrivatePttUrlByNode).toHaveBeenCalledWith(MEDIA_NODE); + expect(bridge.apis.groupFile.getPrivatePttUrl).toHaveBeenCalledWith(MEDIA_NODE); expect(element.url).toBe('http://private/ptt'); }); @@ -82,7 +91,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE }; await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupVideoUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE); + expect(bridge.apis.groupFile.getVideoUrl).toHaveBeenCalledWith(12345, MEDIA_NODE); expect(element.url).toBe('http://group/video'); }); @@ -90,7 +99,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE }; await resolver.resolve(element, false, 67890); - expect(bridge.fetchPrivateVideoUrlByNode).toHaveBeenCalledWith(MEDIA_NODE); + expect(bridge.apis.groupFile.getPrivateVideoUrl).toHaveBeenCalledWith(MEDIA_NODE); expect(element.url).toBe('http://private/video'); }); @@ -98,7 +107,7 @@ describe('MediaUrlResolver — record / video element', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'record' }; await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupPttUrlByNode).not.toHaveBeenCalled(); + expect(bridge.apis.groupFile.getPttUrl).not.toHaveBeenCalled(); expect(element.url).toBeUndefined(); }); }); @@ -110,13 +119,13 @@ describe('MediaUrlResolver — short-circuits and resilience', () => { const resolver = new MediaUrlResolver(bridge as any, rkey as any); const element: MessageElement = { type: 'file', fileId: 'fid', url: 'already-set' }; await resolver.resolve(element, true, 12345); - expect(bridge.fetchGroupFileUrl).not.toHaveBeenCalled(); + expect(bridge.apis.groupFile.getUrl).not.toHaveBeenCalled(); expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce(); }); it('bridge throws: swallowed, rkey still applied', async () => { const bridge = makeBridge({ - fetchGroupFileUrl: vi.fn(async () => { throw new Error('network down'); }), + getUrl: vi.fn(async () => { throw new Error('network down'); }), }); const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'rkey-fallback') }); const resolver = new MediaUrlResolver(bridge as any, rkey as any); diff --git a/packages/core/tests/message-id.test.ts b/packages/onebot/tests/message-id.test.ts similarity index 97% rename from packages/core/tests/message-id.test.ts rename to packages/onebot/tests/message-id.test.ts index 77997a25..a098c7b9 100644 --- a/packages/core/tests/message-id.test.ts +++ b/packages/onebot/tests/message-id.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id'; +import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/message-id'; describe('hashMessageIdInt32', () => { it('returns consistent hash for same inputs', () => { diff --git a/packages/core/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts similarity index 96% rename from packages/core/tests/message-parser.test.ts rename to packages/onebot/tests/message-parser.test.ts index debc405b..6bcd8e45 100644 --- a/packages/core/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -2,12 +2,12 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; import { describe, it, expect, vi } from 'vitest'; -import { parseMessage } from '../src/onebot/message-parser'; -import { buildSendElems } from '../src/bridge/element-builder'; -import { MentionExtraSendSchema } from '../src/bridge/proto/action'; -import { makeOidbBaseSchema } from '../src/bridge/proto/oidb'; -import { NTV2UploadRichMediaRespSchema } from '../src/bridge/proto/highway'; -import { protoDecode, protoEncode } from '../src/protobuf/decode'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { parseMessage } from '../src/message-parser'; +import { buildSendElems } from '@snowluma/bridge/element-builder'; +import type { MentionExtraSend } from '@snowluma/proto-defs/action'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway'; describe('parseMessage', () => { describe('plain text', () => { @@ -188,7 +188,7 @@ describe('parseMessage', () => { const protoElems = await buildSendElems(elements); const reserve = protoElems[0].text?.pbReserve; expect(reserve).toBeInstanceOf(Uint8Array); - const extra = protoDecode(reserve as Uint8Array, MentionExtraSendSchema); + const extra = protobuf_decode(reserve as Uint8Array); expect(extra).toMatchObject({ type: 2, uin: 123456, @@ -232,8 +232,7 @@ describe('parseMessage', () => { const videoPath = path.join(os.tmpdir(), `snowluma-video-test-${process.pid}-${Date.now()}.mp4`); fs.writeFileSync(videoPath, Buffer.from([0, 1, 2, 3])); - const respSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema); - const responseData = protoEncode({ + const responseData = protobuf_encode>({ command: 0x11EA, subCommand: 100, errorCode: 0, @@ -255,7 +254,7 @@ describe('parseMessage', () => { }, errorMsg: '', reserved: 1, - }, respSchema); + }); const bridge = { identity: { uin: '10000' }, diff --git a/packages/core/tests/message-store.test.ts b/packages/onebot/tests/message-store.test.ts similarity index 98% rename from packages/core/tests/message-store.test.ts rename to packages/onebot/tests/message-store.test.ts index fc5ea787..a3527d84 100644 --- a/packages/core/tests/message-store.test.ts +++ b/packages/onebot/tests/message-store.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { MessageStore } from '../src/onebot/message-store'; -import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id'; +import { MessageStore } from '../src/message-store'; +import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/message-id'; import fs from 'fs'; import path from 'path'; diff --git a/packages/core/tests/network-manager.test.ts b/packages/onebot/tests/network-manager.test.ts similarity index 95% rename from packages/core/tests/network-manager.test.ts rename to packages/onebot/tests/network-manager.test.ts index 401a8582..82b2e372 100644 --- a/packages/core/tests/network-manager.test.ts +++ b/packages/onebot/tests/network-manager.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { IOneBotNetworkAdapter, NetworkReloadType, OneBotNetworkManager } from '../src/onebot/network'; -import type { NetworkAdapterContext } from '../src/onebot/network'; -import type { JsonObject, NetworkBase } from '../src/onebot/types'; -import type { DispatchPayload } from '../src/onebot/event-filter'; +import { IOneBotNetworkAdapter, NetworkReloadType, OneBotNetworkManager } from '../src/network'; +import type { NetworkAdapterContext } from '../src/network'; +import type { JsonObject, NetworkBase } from '../src/types'; +import type { DispatchPayload } from '../src/event-filter'; interface FakeNetworkConfig extends NetworkBase { // Allows tests to influence behavior via config: diff --git a/packages/core/tests/onebot/request-actions.test.ts b/packages/onebot/tests/request-actions.test.ts similarity index 52% rename from packages/core/tests/onebot/request-actions.test.ts rename to packages/onebot/tests/request-actions.test.ts index 6e51dcf5..2dbcaa7b 100644 --- a/packages/core/tests/onebot/request-actions.test.ts +++ b/packages/onebot/tests/request-actions.test.ts @@ -1,10 +1,26 @@ import { describe, expect, it, vi } from 'vitest'; -import { handleGroupAddRequest } from '../../src/onebot/modules/request-actions'; +import { handleGroupAddRequest } from '../src/modules/request-actions'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; -import type { GroupRequestInfo } from '../../src/bridge/qq-info'; +import type { GroupRequestInfo } from '@snowluma/bridge/qq-info'; -function fakeBridge(overrides: Partial = {}): BridgeInterface { - return new Proxy(overrides as BridgeInterface, { +// See `contact-actions.test.ts` for the auto-promotion rationale. +const APIS_ROUTING: Record = { + fetchFriendList: 'contacts', fetchGroupList: 'contacts', + fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts', + fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts', +}; + +function fakeBridge(overrides: Record = {}): BridgeInterface { + const apisSynth: Record> = {}; + for (const [k, v] of Object.entries(overrides)) { + const area = APIS_ROUTING[k]; + if (area) { + if (!apisSynth[area]) apisSynth[area] = {}; + apisSynth[area][k] = v; + } + } + const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } }; + return new Proxy(merged as BridgeInterface, { get(target, prop) { if (prop in target) return (target as any)[prop]; throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`); @@ -36,32 +52,32 @@ function fakeRequest(overrides: Partial = {}): GroupRequestInf describe('onebot/modules/request-actions / handleGroupAddRequest', () => { it('matches add requests by groupId and targetUid', async () => { - const setGroupAddRequest = vi.fn(async () => {}); + const setAddRequest = vi.fn(async () => {}); const bridge = fakeBridge({ fetchGroupRequests: vi.fn(async () => [ fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, eventType: 7, filtered: false }), ]), - setGroupAddRequest: setGroupAddRequest as any, + apis: { groupAdmin: { setAddRequest } } as any, }); await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok'); - expect(setGroupAddRequest).toHaveBeenCalledOnce(); - expect(setGroupAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false); + expect(setAddRequest).toHaveBeenCalledOnce(); + expect(setAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false); }); it('matches invite requests by groupId and invitorUid', async () => { - const setGroupAddRequest = vi.fn(async () => {}); + const setAddRequest = vi.fn(async () => {}); const bridge = fakeBridge({ fetchGroupRequests: vi.fn(async () => [ fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }), ]), - setGroupAddRequest: setGroupAddRequest as any, + apis: { groupAdmin: { setAddRequest } } as any, }); await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no'); - expect(setGroupAddRequest).toHaveBeenCalledOnce(); - expect(setGroupAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false); + expect(setAddRequest).toHaveBeenCalledOnce(); + expect(setAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false); }); }); diff --git a/packages/core/tests/onebot/send-group-file.test.ts b/packages/onebot/tests/send-group-file.test.ts similarity index 78% rename from packages/core/tests/onebot/send-group-file.test.ts rename to packages/onebot/tests/send-group-file.test.ts index 3625c938..62038289 100644 --- a/packages/core/tests/onebot/send-group-file.test.ts +++ b/packages/onebot/tests/send-group-file.test.ts @@ -11,14 +11,14 @@ // // Fix: split file segments off at the OneBot layer (same pattern as // the c2c-file split for private messages) and dispatch through -// `bridge.sendGroupFileMessage`, which calls dedicated OIDB +// `bridge.apis.groupFile.publish`, which calls dedicated OIDB // `OidbSvcTrpcTcp.0x6d9_4` — Lagrange.Core V2's // `GroupSendFileService.cs`. import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; -import type { OneBotInstanceContext } from '../../src/onebot/instance-context'; -import { sendGroupMessage } from '../../src/onebot/modules/message-actions'; +import type { OneBotInstanceContext } from '../src/instance-context'; +import { sendGroupMessage } from '../src/modules/message-actions'; function fakeBridge(overrides: Partial = {}): BridgeInterface { return new Proxy(overrides as BridgeInterface, { @@ -45,7 +45,7 @@ const goodReceipt = { }; describe('send_group_msg with {type:"file"} segment', () => { - it('file-only message routes through sendGroupFileMessage (not sendGroupMessage_bridge)', async () => { + it('file-only message routes through apis.groupFile.publish (not apis.message.sendGroup)', async () => { // Pure-file case — the elems[] path used to ship a transElem(24) // and got result=79. The dedicated OIDB-0x6d9_4 route must take // over for group file publishing. @@ -53,10 +53,12 @@ describe('send_group_msg with {type:"file"} segment', () => { // Declare params on the fn so `mock.calls[0]` infers a tuple of // [groupId, fileId] instead of `[]` (which makes the destructuring // a tsc error under noUncheckedIndexedAccess). - const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined); + const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined); const bridge = fakeBridge({ - sendGroupMessage: sendGroupMessage_bridge, - sendGroupFileMessage, + apis: { + message: { sendGroup: sendGroupMessage_bridge }, + groupFile: { publish }, + } as any, resolveUserUid: vi.fn(), } as any); const ctx = makeCtx(bridge); @@ -65,20 +67,22 @@ describe('send_group_msg with {type:"file"} segment', () => { type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 }, }] as any, false); - expect(sendGroupFileMessage).toHaveBeenCalledOnce(); + expect(publish).toHaveBeenCalledOnce(); expect(sendGroupMessage_bridge).not.toHaveBeenCalled(); - const [groupId, fileId] = sendGroupFileMessage.mock.calls[0]!; + const [groupId, fileId] = publish.mock.calls[0]!; expect(groupId).toBe(12345); expect(fileId).toBe('gfid-abc'); }); it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => { const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt); - const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined); + const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined); const bridge = fakeBridge({ - sendGroupMessage: sendGroupMessage_bridge, - sendGroupFileMessage, + apis: { + message: { sendGroup: sendGroupMessage_bridge }, + groupFile: { publish }, + } as any, resolveUserUid: vi.fn(async () => 'u_peer'), } as any); const ctx = makeCtx(bridge); @@ -89,13 +93,13 @@ describe('send_group_msg with {type:"file"} segment', () => { ] as any, false); expect(sendGroupMessage_bridge).toHaveBeenCalledOnce(); - expect(sendGroupFileMessage).toHaveBeenCalledOnce(); + expect(publish).toHaveBeenCalledOnce(); const [textGid, textElements] = sendGroupMessage_bridge.mock.calls[0]!; expect(textGid).toBe(12345); expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]); - const [fileGid, fileFileId] = sendGroupFileMessage.mock.calls[0]!; + const [fileGid, fileFileId] = publish.mock.calls[0]!; expect(fileGid).toBe(12345); expect(fileFileId).toBe('gfid-xyz'); }); @@ -104,10 +108,12 @@ describe('send_group_msg with {type:"file"} segment', () => { // Same upload-by-reference contract as the c2c file path — // missing file_id means there's nothing to publish. const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt); - const sendGroupFileMessage = vi.fn(); + const publish = vi.fn(); const bridge = fakeBridge({ - sendGroupMessage: sendGroupMessage_bridge, - sendGroupFileMessage, + apis: { + message: { sendGroup: sendGroupMessage_bridge }, + groupFile: { publish }, + } as any, resolveUserUid: vi.fn(), } as any); const ctx = makeCtx(bridge); @@ -118,6 +124,6 @@ describe('send_group_msg with {type:"file"} segment', () => { ] as any, false); expect(sendGroupMessage_bridge).toHaveBeenCalledOnce(); - expect(sendGroupFileMessage).not.toHaveBeenCalled(); + expect(publish).not.toHaveBeenCalled(); }); }); diff --git a/packages/core/tests/onebot/send-private-c2c-file.test.ts b/packages/onebot/tests/send-private-c2c-file.test.ts similarity index 92% rename from packages/core/tests/onebot/send-private-c2c-file.test.ts rename to packages/onebot/tests/send-private-c2c-file.test.ts index 3b626cfd..fe821cef 100644 --- a/packages/core/tests/onebot/send-private-c2c-file.test.ts +++ b/packages/onebot/tests/send-private-c2c-file.test.ts @@ -16,8 +16,8 @@ import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; -import type { OneBotInstanceContext } from '../../src/onebot/instance-context'; -import { sendPrivateMessage } from '../../src/onebot/modules/message-actions'; +import type { OneBotInstanceContext } from '../src/instance-context'; +import { sendPrivateMessage } from '../src/modules/message-actions'; function fakeBridge(overrides: Partial = {}): BridgeInterface { return new Proxy(overrides as BridgeInterface, { @@ -52,8 +52,7 @@ describe('send_private_msg with {type:"file"} segment', () => { const resolveUserUid = vi.fn(async () => 'u_peer'); const recallUploadedFile = vi.fn(() => undefined); const bridge = fakeBridge({ - sendPrivateMessage: sendPrivateMessage_bridge, - sendC2cFileMessage, + apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any, resolveUserUid, recallUploadedFile, } as any); @@ -98,8 +97,7 @@ describe('send_private_msg with {type:"file"} segment', () => { rememberedAt: 0, } : undefined); const bridge = fakeBridge({ - sendPrivateMessage: vi.fn(), - sendC2cFileMessage, + apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage } } as any, resolveUserUid: vi.fn(async () => 'u_peer'), recallUploadedFile, } as any); @@ -137,8 +135,7 @@ describe('send_private_msg with {type:"file"} segment', () => { rememberedAt: 0, })); const bridge = fakeBridge({ - sendPrivateMessage: vi.fn(), - sendC2cFileMessage, + apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage } } as any, resolveUserUid: vi.fn(async () => 'u_peer'), recallUploadedFile, } as any); @@ -162,8 +159,7 @@ describe('send_private_msg with {type:"file"} segment', () => { const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt); const resolveUserUid = vi.fn(async () => 'u_peer'); const bridge = fakeBridge({ - sendPrivateMessage: sendPrivateMessage_bridge, - sendC2cFileMessage, + apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any, resolveUserUid, recallUploadedFile: vi.fn(() => undefined), } as any); @@ -196,8 +192,7 @@ describe('send_private_msg with {type:"file"} segment', () => { const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt); const sendC2cFileMessage = vi.fn(); const bridge = fakeBridge({ - sendPrivateMessage: sendPrivateMessage_bridge, - sendC2cFileMessage, + apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any, resolveUserUid: vi.fn(), recallUploadedFile: vi.fn(() => undefined), } as any); @@ -220,8 +215,7 @@ describe('send_private_msg with {type:"file"} segment', () => { // an empty uid. const sendC2cFileMessage = vi.fn(); const bridge = fakeBridge({ - sendPrivateMessage: vi.fn(), - sendC2cFileMessage, + apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage } } as any, resolveUserUid: vi.fn(async () => ''), // intentional empty recallUploadedFile: vi.fn(() => undefined), } as any); diff --git a/packages/onebot/tsconfig.json b/packages/onebot/tsconfig.json new file mode 100644 index 00000000..4cd329d7 --- /dev/null +++ b/packages/onebot/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"], + "noEmit": true + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/packages/onebot/vitest.config.ts b/packages/onebot/vitest.config.ts new file mode 100644 index 00000000..88fbd8e3 --- /dev/null +++ b/packages/onebot/vitest.config.ts @@ -0,0 +1,39 @@ +// Vitest config — runs the OneBot tests against the workspace TS +// source directly (no build step). The 20 tests here were previously +// inside `packages/core/tests/` and ran via `@snowluma/core`'s vitest +// invocation; they moved over wholesale in the Phase 3 split. +import protobufVitePlugin from '@snowluma/proton/vite'; +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + // `@snowluma/proton` provides the bare-specifier resolver that turns + // `import type { OidbBase } from '@snowluma/proto-defs/oidb'` into + // a zero-runtime encoder/decoder at the call site. The same plugin + // is loaded by `@snowluma/core`'s vite config — keep it here so the + // OneBot tests resolve identically. + plugins: [protobufVitePlugin()], + test: { + include: ['tests/**/*.test.ts'], + // Per-RoadMap-#5 bench files live in `bench/*.bench.ts`. Use the + // vitest `--mode bench` (via `pnpm bench`) to pick them up; default + // `test` runs leave them inert. + benchmark: { + include: ['bench/**/*.bench.ts'], + }, + environment: 'node', + // Suppress the logger's file transport during tests so the suite + // doesn't litter cwd with logs/snowluma-*.log files. Tests that + // explicitly cover file output set their own SNOWLUMA_LOG_FILE='1' + // + SNOWLUMA_LOG_DIR=. + // + // Run at debug level so tests asserting on debug-level log entries + // (e.g. action dispatch entry lines) actually see them via the + // ring buffer / subscribers, which sit behind the console-level + // gate. Mirrors the equivalent env setup in @snowluma/core's + // vitest.config.ts. + env: { + SNOWLUMA_LOG_FILE: '0', + SNOWLUMA_LOG_LEVEL: 'debug' + } + }, +}); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json new file mode 100644 index 00000000..40457854 --- /dev/null +++ b/packages/proto-defs/package.json @@ -0,0 +1,73 @@ +{ + "name": "@snowluma/proto-defs", + "version": "1.9.1", + "private": true, + "type": "module", + "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./action": { + "types": "./src/action.ts", + "default": "./src/action.ts" + }, + "./element": { + "types": "./src/element.ts", + "default": "./src/element.ts" + }, + "./highway": { + "types": "./src/highway.ts", + "default": "./src/highway.ts" + }, + "./longmsg": { + "types": "./src/longmsg.ts", + "default": "./src/longmsg.ts" + }, + "./message": { + "types": "./src/message.ts", + "default": "./src/message.ts" + }, + "./notify": { + "types": "./src/notify.ts", + "default": "./src/notify.ts" + }, + "./oidb": { + "types": "./src/oidb.ts", + "default": "./src/oidb.ts" + }, + "./oidb-action": { + "types": "./src/oidb-action.ts", + "default": "./src/oidb-action.ts" + }, + "./oidb-actions/base": { + "types": "./src/oidb-actions/base.ts", + "default": "./src/oidb-actions/base.ts" + }, + "./oidb-actions/group-album": { + "types": "./src/oidb-actions/group-album.ts", + "default": "./src/oidb-actions/group-album.ts" + }, + "./oidb-actions/group-file": { + "types": "./src/oidb-actions/group-file.ts", + "default": "./src/oidb-actions/group-file.ts" + }, + "./oidb-actions/media": { + "types": "./src/oidb-actions/media.ts", + "default": "./src/oidb-actions/media.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@snowluma/proton": "workspace:*" + }, + "devDependencies": { + "@types/node": "^24.12.2", + "typescript": "catalog:" + } +} diff --git a/packages/proto-defs/src/action.ts b/packages/proto-defs/src/action.ts new file mode 100644 index 00000000..fbd94d9e --- /dev/null +++ b/packages/proto-defs/src/action.ts @@ -0,0 +1,91 @@ +import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton'; +import type { Elem } from './element'; + +// Routing +export interface RoutingC2C { + uin?: pb<1, uint_32>; + uid?: pb<2, string>; +} + +export interface RoutingGroup { + groupCode?: pb<1, uint_64>; +} + +// 服务器限制 C2C 文件消息必须使用 Trans0x211 路由头(RoutingHead 字段 15) +// 若误用常规 RoutingC2C 会被服务器拒绝。 +// 仅在包含 FileEntity 时触发,且 CcCmd 固定为 4。 + +export interface RoutingTrans0x211 { + toUin?: pb<1, uint_64>; + ccCmd?: pb<2, uint_32>; + uid?: pb<8, string>; +} + +export interface RoutingHead { + c2c?: pb<1, RoutingC2C>; + grp?: pb<2, RoutingGroup>; + trans0x211?: pb<15, RoutingTrans0x211>; +} + +// Content Head for send +export interface SendContentHead { + type?: pb<1, uint_32>; + subType?: pb<2, uint_32>; + c2cCmd?: pb<3, uint_32>; +} + +// Message Control +export interface MessageControl { + msgFlag?: pb<1, int_32>; +} + +// RichText (for send — only elems) +export interface SendRichText { + elems?: pb_repeated<2, Elem>; +} + +// MessageBody (for send) +export interface SendMessageBody { + richText?: pb<1, SendRichText>; + // C2C 离线文件元数据(NotOnlineFile)必须序列化后塞入此字段 + // 服务器不会读取 richText.notOnlineFile。 + msgContent?: pb<2, bytes>; +} + +// SendMessageRequest +export interface SendMessageRequest { + routingHead?: pb<1, RoutingHead>; + contentHead?: pb<2, SendContentHead>; + messageBody?: pb<3, SendMessageBody>; + clientSequence?: pb<4, uint_32>; + random?: pb<5, uint_32>; + syncCookie?: pb<6, bytes>; + via?: pb<8, uint_32>; + dataStatist?: pb<9, uint_32>; + ctrl?: pb<12, MessageControl>; + multiSendSeq?: pb<14, uint_32>; +} + +// SendMessageResponse +export interface SendMessageResponse { + result?: pb<1, int_32>; + errMsg?: pb<2, string>; + timestamp1?: pb<3, uint_32>; + field10?: pb<10, uint_32>; + groupSequence?: pb<11, uint_32>; + timestamp2?: pb<12, uint_32>; + privateSequence?: pb<14, uint_32>; +} + +// MentionExtra (for building @mention text element) +export interface MentionExtraSend { + type?: pb<3, int_32>; + uin?: pb<4, uint_32>; + field5?: pb<5, int_32>; + uid?: pb<9, string>; +} + +// MarkdownData +export interface MarkdownData { + content?: pb<1, string>; +} diff --git a/packages/core/src/bridge/proto/proton/element.ts b/packages/proto-defs/src/element.ts similarity index 82% rename from packages/core/src/bridge/proto/proton/element.ts rename to packages/proto-defs/src/element.ts index 304cd08e..07512392 100644 --- a/packages/core/src/bridge/proto/proton/element.ts +++ b/packages/proto-defs/src/element.ts @@ -1,13 +1,6 @@ -// Proton (compile-time) form of bridge/proto/element.ts. -// -// One-to-one mirror of every schema in element.ts. The legacy `*Schema` -// constants stay in place for back-compat; both forms produce wire-equivalent -// output (modulo the proto3 default-value omission — see README). - import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; -// ── Nested / helper schemas ───────────────────────────────────────── - +// Nested / helper schemas export interface CustomFacePbReserve { subType?: pb<1, int_32>; summary?: pb<9, string>; @@ -33,8 +26,7 @@ export interface NotOnlineImagePbReserve { md5Str?: pb<31, string>; } -// ── Core element schemas ──────────────────────────────────────────── - +// Core element schemas export interface TextElem { str?: pb<1, string>; link?: pb<2, string>; @@ -238,7 +230,7 @@ export interface GeneralFlags { longTextResId?: pb<7, string>; } -// ── Elem (union of all element types) ─────────────────────────────── +// Elem (union of all element types) export interface Elem { text?: pb<1, TextElem>; @@ -258,7 +250,7 @@ export interface Elem { commonElem?: pb<53, CommonElem>; } -// ── Extra decode types (for CommonElem.pbElem sub-messages) ───────── +// Extra decode types (for CommonElem.pbElem sub-messages) export interface MentionExtra { type?: pb<3, int_32>; @@ -284,7 +276,7 @@ export interface QSmallFaceExtra { preview2?: pb<3, string>; } -// ── NTQQ MsgInfo types (CommonElem service_type 48) ───────────────── +// NTQQ MsgInfo types (CommonElem service_type 48) export interface FileType { type?: pb<1, uint_32>; @@ -391,24 +383,15 @@ export interface MsgInfo { extBizInfo?: pb<2, ExtBizInfo>; } -// ── GroupFileExtra (TransElem type=24) ────────────────────────────── -// -// Sourced from NapCat's `GroupFileExtraInfo` (component.ts:146-155) -// cross-checked against acidify's `GroupFileExtra.Inner.Info` -// (proto/message/extra/GroupFileExtra.kt). Field numbers had been -// shifted by one in the previous schema (fileSha at 5, ext at 6, -// fileMd5 at 7) which caused the server to reject group-file chat -// posts with `result=79` — the server saw fileSha bytes where it -// expected a uint32 placeholder (field 5) and silently dropped the -// rest. Field 5 is a uint32 placeholder both refs label `field5`; -// fileSha is at 6, extInfoString at 7, fileMd5 at 8. - +// 群文件附加信息 (TransElem type=24) +// 旧版 Schema 字段 5-7 错位曾导致服务器返回 result=79 并拒收消息。 +// 字段 5 为 uint32 占位符。 export interface GroupFileInfo { busId?: pb<1, uint_32>; fileId?: pb<2, string>; fileSize?: pb<3, uint_64>; fileName?: pb<4, string>; - field5?: pb<5, uint_32>; + field5?: pb<5, uint_32>; // 关键:必须是 uint32 占位符,错位会导致 SHA 字节流污染此字段 fileSha?: pb<6, bytes>; extInfoString?: pb<7, string>; fileMd5?: pb<8, bytes>; @@ -418,24 +401,18 @@ export interface GroupFileExtraInner { info?: pb<2, GroupFileInfo>; } -// Outer wrapper carries three additional fields the server expects: -// field1 (uint32, NapCat hardcodes to 6 — "magic op tag"), fileName -// (string mirror of the inner info.fileName), display (optional UI -// preview string, NapCat leaves empty but writes the slot). Without -// these the server still recognized the message in older builds but -// rejects it in the current rollout. +// 新版服务器强校验外层结构。缺少 field1 (Magic Tag)、fileName 或 display 槽位,消息将被直接拒绝。 export interface GroupFileExtra { - field1?: pb<1, uint_32>; - fileName?: pb<2, string>; - display?: pb<3, string>; + field1?: pb<1, uint_32>; // NapCat 硬编码固定为 6 (Magic Op Tag) + fileName?: pb<2, string>; // 镜像同步内部的 info.fileName + display?: pb<3, string>; // UI 预览槽位,可留空但必须声明 inner?: pb<7, GroupFileExtraInner>; } -// ── Preserve (for message receipt info) ───────────────────────────── - +// 消息回执保留信息 export interface Preserve { messageId?: pb<3, uint_64>; senderUid?: pb<6, string>; receiverUid?: pb<7, string>; clientSequence?: pb<8, uint_32>; -} +} \ No newline at end of file diff --git a/packages/core/src/bridge/proto/proton/highway.ts b/packages/proto-defs/src/highway.ts similarity index 85% rename from packages/core/src/bridge/proto/proton/highway.ts rename to packages/proto-defs/src/highway.ts index eef6ee84..d6e39377 100644 --- a/packages/core/src/bridge/proto/proton/highway.ts +++ b/packages/proto-defs/src/highway.ts @@ -1,6 +1,3 @@ -// Proton (compile-time) form of bridge/proto/highway.ts. -// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. - import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; import type { IndexNode, @@ -11,7 +8,7 @@ import type { PttExtBizInfo, } from './element'; -// ── DataHighwayHead ───────────────────────────────────────────────── +// DataHighwayHead export interface DataHighwayHead { version?: pb<1, uint_32>; @@ -57,7 +54,7 @@ export interface RespDataHighwayHead { errorCode?: pb<3, uint_32>; } -// ── Highway extend (NTV2RichMediaHighwayExt) ──────────────────────── +// Highway extend (NTV2RichMediaHighwayExt) export interface HighwayDomain { isEnable?: pb<1, bool>; @@ -93,7 +90,7 @@ export interface NTV2RichMediaHighwayExt { hash?: pb<11, HighwayHash>; } -// ── File upload extend (group/private file highway) ───────────────── +// File upload extend (group/private file highway) export interface FileUploadUrl { unknown?: pb<1, int_32>; @@ -153,7 +150,7 @@ export interface FileUploadExt { unknown200?: pb<200, int_32>; } -// ── Encodable MsgInfo (for embedding in message element) ──────────── +// Encodable MsgInfo (for embedding in message element) export interface EncodableMediaExtBizInfo { pic?: pb<1, PicExtBizInfo>; @@ -167,7 +164,7 @@ export interface EncodableMediaMsgInfo { extBizInfo?: pb<2, EncodableMediaExtBizInfo>; } -// ── HttpConn.0x6ff_501 (highway session) ──────────────────────────── +// HttpConn.0x6ff_501 (highway session) export interface HttpConn { field1?: pb<1, int_32>; @@ -208,7 +205,7 @@ export interface HttpConn0x6FF501Response { httpConn?: pb<0x501, HttpConnResponse>; } -// ── NTV2 Upload Request (for OIDB 0x11C4/0x11C5) ──────────────────── +// NTV2 Upload Request (for OIDB 0x11C4/0x11C5) export interface NTV2FileType { type?: pb<1, uint_32>; @@ -234,10 +231,8 @@ export interface NTV2UploadInfo { subFileType?: pb<2, uint_32>; } -// The NTV2 upload request + response carry the same ExtBizInfo shape that -// element-side incoming-message decoding uses. See bridge/proto/highway.ts -// for the rationale (the video fromScene/toScene drop was responsible for -// c2c result=79 rejections on send_private_msg [{type:'video'}]). +// NTV2 上传请求/响应扩展信息(与消息解码结构共用,参考 bridge/proto/highway.ts) +// 必须包含 video.fromScene 和 toScene 字段,否则私聊发送视频时会被服务器返回 result=79 拒绝。 export interface NTV2ExtBizInfo { pic?: pb<1, PicExtBizInfo>; video?: pb<2, VideoExtBizInfo>; @@ -293,8 +288,7 @@ export interface NTV2UploadRichMediaReq { upload?: pb<2, NTV2UploadReq>; } -// ── NTV2 Upload Response ──────────────────────────────────────────── - +// NTV2 Upload Response export interface NTV2IPv4 { outIp?: pb<1, uint_32>; outPort?: pb<2, uint_32>; diff --git a/packages/proto-defs/src/index.ts b/packages/proto-defs/src/index.ts new file mode 100644 index 00000000..614f5e73 --- /dev/null +++ b/packages/proto-defs/src/index.ts @@ -0,0 +1,34 @@ +// SnowLuma wire-protobuf type definitions. +// +// This barrel exists so `@snowluma/proto-defs` can be resolved by a +// plain `import {} from '@snowluma/proto-defs'` (consumers that don't +// know which sub-namespace they want, or just want to see what's +// available). The package itself is otherwise consumed via the +// per-file subpath exports declared in package.json — that's the +// recommended import shape because it mirrors the legacy +// `bridge/proto/proton/` paths 1:1 and avoids name collisions. +// +// ─── Collision note ─── +// +// `highway.ts` and `oidb-actions/media.ts` each define their own +// `NTV2*` types (NTV2CommonHead, NTV2ClientMeta, NTV2C2CUserInfo, +// NTV2FileInfo, NTV2FileType, NTV2GroupInfo). The two definitions +// are NOT compatible — they describe different wire shapes for +// different protocol surfaces and happen to share the same name in +// the upstream Lagrange schema. `export *` silently drops one side +// when names collide, so a consumer that grabs an `NTV2CommonHead` +// off the barrel might end up with the wrong one. Prefer the subpath +// imports below for any NTV2-named type. + +export type * from './action.js'; +export type * from './element.js'; +// NOTE: `highway.ts` intentionally NOT re-exported here — see note above. +export type * from './longmsg.js'; +export type * from './message.js'; +export type * from './notify.js'; +export type * from './oidb.js'; +export type * from './oidb-action.js'; +export type * from './oidb-actions/base.js'; +export type * from './oidb-actions/group-album.js'; +export type * from './oidb-actions/group-file.js'; +// NOTE: `oidb-actions/media.ts` intentionally NOT re-exported — see note above. diff --git a/packages/core/src/bridge/proto/proton/longmsg.ts b/packages/proto-defs/src/longmsg.ts similarity index 77% rename from packages/core/src/bridge/proto/proton/longmsg.ts rename to packages/proto-defs/src/longmsg.ts index ef634a96..040d622b 100644 --- a/packages/core/src/bridge/proto/proton/longmsg.ts +++ b/packages/proto-defs/src/longmsg.ts @@ -1,10 +1,3 @@ -// Proton (compile-time) form of the long-message schemas. -// -// One-to-one mirror of `bridge/proto/longmsg.ts`. All 12 schemas are now -// migrated — the three (`LongMsgContent` / `LongMsgAction` / `LongMsgResult`) -// that reach into `PushMsgBody` resolve via the proton-form `message.ts` -// migration alongside this file. - import type { pb, pb_repeated, uint_32, bool, bytes } from '@snowluma/proton'; import type { PushMsgBody } from './message'; @@ -61,8 +54,7 @@ export interface RecvLongMsgResp { settings?: pb<15, LongMsgSettings>; } -// ── Schemas that reach into PushMsgBody (via message.ts) ──────────── - +// Schemas that reach into PushMsgBody export interface LongMsgContent { msgBody?: pb_repeated<1, PushMsgBody>; } diff --git a/packages/proto-defs/src/message.ts b/packages/proto-defs/src/message.ts new file mode 100644 index 00000000..26a8c5a6 --- /dev/null +++ b/packages/proto-defs/src/message.ts @@ -0,0 +1,98 @@ +import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton'; +import type { Elem } from './element'; + +// ResponseHead.Grp +export interface ResponseGrp { + groupUin?: pb<1, uint_32>; + memberName?: pb<2, string>; + groupName?: pb<4, string>; +} + +export interface ResponseForward { + friendName?: pb<6, string>; +} + +// ResponseHead +export interface ResponseHead { + fromUin?: pb<1, uint_32>; + fromUid?: pb<2, string>; + type?: pb<3, uint_32>; + sigMap?: pb<4, uint_32>; + toUin?: pb<5, uint_32>; + toUid?: pb<6, string>; + forward?: pb<7, ResponseForward>; + grp?: pb<8, ResponseGrp>; +} + +// ContentHead +export interface ContentHead { + msgType?: pb<1, uint_32>; + subType?: pb<2, uint_32>; + divSeq?: pb<3, uint_32>; + msgId?: pb<4, uint_32>; + sequence?: pb<5, uint_32>; + timestamp?: pb<6, uint_32>; + field7?: pb<7, uint_64>; + newId?: pb<12, uint_64>; +} + +// Ptt (voice) +export interface Ptt { + fileType?: pb<1, uint_32>; + fileId?: pb<2, uint_64>; + fileUuid?: pb<3, bytes>; + fileMd5?: pb<4, bytes>; + fileName?: pb<5, string>; + fileSize?: pb<6, uint_32>; + groupFileKey?: pb<10, string>; + fileKey?: pb<14, bytes>; + time?: pb<19, uint_32>; + format?: pb<29, uint_32>; +} + +// C2C 离线文件结构 +// 1. 发送端必填:字段 9/50/55(subcmd=1, dangerEvel=0, expireTime=当前时间+7天)。 +// 2. 接收端只读:核心标识槽位(Uuid/Md5/Name/Size/Hash)。 +export interface NotOnlineFile { + fileType?: pb<1, uint_32>; + fileUuid?: pb<3, string>; + fileMd5?: pb<4, bytes>; + fileName?: pb<5, string>; + fileSize?: pb<6, uint_64>; + subcmd?: pb<9, uint_32>; // 发送必填:固定为 1 + dangerEvel?: pb<50, uint_32>; // 发送必填:固定为 0 + expireTime?: pb<55, uint_32>; // 发送必填:过期时间戳(now + 7 days) + fileHash?: pb<57, string>; +} + +// RichText +export interface RichText { + elems?: pb_repeated<2, Elem>; + notOnlineFile?: pb<3, NotOnlineFile>; + ptt?: pb<4, Ptt>; +} + +// MessageBody +export interface MessageBody { + richText?: pb<1, RichText>; + msgContent?: pb<2, bytes>; +} + +// C2C 文件附加信息 +// 统一使用与线上数据对齐的 NotOnlineFile 结构,修复收发双向的解析问题。 +export interface FileExtra { + file?: pb<1, NotOnlineFile>; +} + +// PushMsgBody +export interface PushMsgBody { + responseHead?: pb<1, ResponseHead>; + contentHead?: pb<2, ContentHead>; + body?: pb<3, MessageBody>; +} + +// PushMsg (top-level) +export interface PushMsg { + message?: pb<1, PushMsgBody>; + status?: pb<3, int_32>; +} diff --git a/packages/core/src/bridge/proto/proton/notify.ts b/packages/proto-defs/src/notify.ts similarity index 84% rename from packages/core/src/bridge/proto/proton/notify.ts rename to packages/proto-defs/src/notify.ts index 4a916290..68903cb2 100644 --- a/packages/core/src/bridge/proto/proton/notify.ts +++ b/packages/proto-defs/src/notify.ts @@ -1,6 +1,3 @@ -// Proton (compile-time) form of bridge/proto/notify.ts. -// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. - import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; export interface OperatorField1 { @@ -122,18 +119,12 @@ export interface FriendRecall { reserved?: pb<5, bytes>; } -// ── NewFriend (0x210 subType 179 + 226) ─────────────────────────── -// -// Mutual-accept friend notice. Fires when: -// - bot sent a friend request and the other side accepted (179), or -// - the other side sent a request and bot accepted it (226). -// Both subTypes share this wire shape; field semantics follow -// `LagrangeDev/LagrangeGo` client/packets/pb/message/notify.proto. - +// 新好友通知 (0x210 子类型 179 / 226) +// 触发场景:双向同意好友申请(179:对方同意 Bot;226:Bot 同意对方)。 export interface NewFriendInfo { uid?: pb<1, string>; field2?: pb<2, uint_32>; - time?: pb<3, uint_32>; // fixed32 on wire; uint_32 decoded value is the unix epoch + time?: pb<3, uint_32>; // Unix 时间戳 (Wire 层为 fixed32) message?: pb<4, string>; nickName?: pb<5, string>; field6?: pb<6, uint_32>; @@ -146,16 +137,12 @@ export interface NewFriend { info?: pb<2, NewFriendInfo>; } -// ── SelfJoinInGroup (PkgType 85) ────────────────────────────────── -// -// Fired when the bot itself was admitted into a group — typically the -// completion of an admin-approved join request or an accepted invite. -// Ported from `lagrange-python/pb/status/group.py:170 PBSelfJoinInGroup`. - +// Bot 自身进群通知 (PkgType 85) +// 触发场景:Bot 成功加入群聊(管理员通过申请 或 接受邀请进群)。 export interface SelfJoinInGroup { groupUin?: pb<1, uint_64>; field2?: pb<2, uint_32>; - operatorUid?: pb<3, string>; + operatorUid?: pb<3, string>; // 操作人 UID (如批准申请的管理员) field4?: pb<4, uint_32>; field6?: pb<6, uint_32>; field7?: pb<7, string>; @@ -245,8 +232,7 @@ export interface NotifyMessageBody { field39?: pb<39, uint_32>; } -// ─── Event0x2DC subType=16: GroupMsgEmojiLike ──────────────────────── - +// Event0x2DC subType=16: GroupMsgEmojiLike export interface GroupReactionDataInnerDataTarget { seq?: pb<1, uint_64>; } diff --git a/packages/proto-defs/src/oidb-action.ts b/packages/proto-defs/src/oidb-action.ts new file mode 100644 index 00000000..9bbedd68 --- /dev/null +++ b/packages/proto-defs/src/oidb-action.ts @@ -0,0 +1 @@ +export type * from './oidb-actions'; diff --git a/packages/proto-defs/src/oidb-actions/base.ts b/packages/proto-defs/src/oidb-actions/base.ts new file mode 100644 index 00000000..820da07b --- /dev/null +++ b/packages/proto-defs/src/oidb-actions/base.ts @@ -0,0 +1,588 @@ +import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; + +// Re-exported from the legacy oidb-action module while large protocol groups +// are split into focused files. + +export interface OidbMuteMemberBody { + targetUid?: pb<1, string>; + duration?: pb<2, uint_32>; +} +export interface OidbMuteMember { + groupUin?: pb<1, uint_32>; + type?: pb<2, uint_32>; + body?: pb<3, OidbMuteMemberBody>; +} +export interface OidbMuteAllState { + state?: pb<17, uint_32>; +} +export interface OidbMuteAll { + groupUin?: pb<1, uint_32>; + muteState?: pb<2, OidbMuteAllState>; +} +export interface Oidb0x89a_0AddOptionSettings { + addType?: pb<16, uint_32>; +} +export interface Oidb0x89a_0AddOption { + groupUin?: pb<1, uint_64>; + settings?: pb<2, Oidb0x89a_0AddOptionSettings>; + field12?: pb<12, uint_32>; +} +export interface Oidb0x89a_0Search { + groupUin?: pb<1, uint_64>; + settings?: pb<2, bytes>; + field12?: pb<12, uint_32>; +} +export interface OidbKickMember { + groupUin?: pb<1, uint_32>; + targetUid?: pb<3, string>; + rejectAddRequest?: pb<4, bool>; + reason?: pb<5, string>; +} +export interface OidbLeaveGroup { + groupUin?: pb<1, uint_32>; +} +export interface OidbFriendRequestAction { + accept?: pb<1, uint_32>; + targetUid?: pb<2, string>; +} +export interface OidbDeleteFriendField2Field3 { + field1?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; +} +export interface OidbDeleteFriendField2 { + field1?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, OidbDeleteFriendField2Field3>; +} +export interface OidbDeleteFriendField1 { + targetUid?: pb<1, string>; + field2?: pb<2, OidbDeleteFriendField2>; + block?: pb<3, bool>; + field4?: pb<4, bool>; +} +export interface OidbDeleteFriend { + field1?: pb<1, OidbDeleteFriendField1>; +} +export interface OidbGroupRequestBody { + sequence?: pb<1, uint_64>; + eventType?: pb<2, uint_32>; + groupUin?: pb<3, uint_32>; + message?: pb<4, string>; +} +export interface OidbGroupRequestAction { + accept?: pb<1, uint_32>; + body?: pb<2, OidbGroupRequestBody>; +} +export interface OidbPoke { + uin?: pb<1, uint_32>; + groupUin?: pb<2, uint_32>; + friendUin?: pb<5, uint_32>; + ext?: pb<6, uint_32>; +} +export interface OidbEssence { + groupUin?: pb<1, uint_32>; + sequence?: pb<2, uint_32>; + random?: pb<3, uint_32>; +} +export interface OidbSetAdmin { + groupUin?: pb<1, uint_32>; + uid?: pb<2, string>; + isAdmin?: pb<3, bool>; +} +export interface OidbRenameMemberBody { + targetUid?: pb<1, string>; + targetName?: pb<2, string>; +} +export interface OidbRenameMember { + groupUin?: pb<1, uint_32>; + body?: pb<2, OidbRenameMemberBody>; +} +export interface OidbRenameGroupBody { + targetName?: pb<1, string>; +} +export interface OidbRenameGroup { + groupUin?: pb<1, uint_32>; + body?: pb<2, OidbRenameGroupBody>; +} +export interface OidbSpecialTitleBody { + targetUid?: pb<1, string>; + specialTitle?: pb<5, string>; + expireTime?: pb<6, int_32>; +} +export interface OidbSpecialTitle { + groupUin?: pb<1, uint_32>; + body?: pb<2, OidbSpecialTitleBody>; +} +export interface OidbLike { + targetUin?: pb<1, uint_32>; + count?: pb<2, uint_32>; +} +export interface OidbGroupRequestList { + count?: pb<1, uint_32>; + field2?: pb<2, uint_32>; +} +export interface OidbUserInfoKey { + key?: pb<1, uint_32>; +} +export interface OidbUserInfoRequest { + uin?: pb<1, uint_32>; + keys?: pb_repeated<3, OidbUserInfoKey>; +} +export interface OidbTwoNumber { + number1?: pb<1, uint_32>; + number2?: pb<2, uint_32>; +} +export interface OidbByteProperty { + code?: pb<1, uint_32>; + value?: pb<2, bytes>; +} +export interface OidbUserInfoProperty { + numberProperties?: pb_repeated<1, OidbTwoNumber>; + bytesProperties?: pb_repeated<2, OidbByteProperty>; +} +export interface OidbUserInfoResponseBody { + uid?: pb<1, string>; + properties?: pb<2, OidbUserInfoProperty>; + uin?: pb<3, uint_32>; +} +export interface OidbUserInfoResponse { + body?: pb<1, OidbUserInfoResponseBody>; +} +export interface AvatarInfo { + url?: pb<5, string>; +} +export interface OidbFriendListNumber { + numbers?: pb_repeated<1, uint_32>; +} +export interface OidbFriendListBodyItem { + type?: pb<1, uint_32>; + number?: pb<2, OidbFriendListNumber>; +} +export interface OidbFriendListNextUin { + uin?: pb<1, uint_32>; +} +export interface OidbFriendListRequest { + friendCount?: pb<2, uint_32>; + field4?: pb<4, uint_32>; + nextUin?: pb<5, OidbFriendListNextUin>; + field6?: pb<6, uint_32>; + field7?: pb<7, uint_32>; + body?: pb_repeated<10001, OidbFriendListBodyItem>; + field10002?: pb_repeated<10002, uint_32>; + field10003?: pb<10003, uint_32>; +} +export interface OidbGroupListConfig1 { + groupOwner?: pb<1, bool>; + field2?: pb<2, bool>; + memberMax?: pb<3, bool>; + memberCount?: pb<4, bool>; + groupName?: pb<5, bool>; + field8?: pb<8, bool>; + field9?: pb<9, bool>; + field10?: pb<10, bool>; + field11?: pb<11, bool>; + field12?: pb<12, bool>; + field13?: pb<13, bool>; + field14?: pb<14, bool>; + field15?: pb<15, bool>; + field16?: pb<16, bool>; + field17?: pb<17, bool>; + field18?: pb<18, bool>; + question?: pb<19, bool>; + field20?: pb<20, bool>; + field22?: pb<22, bool>; + field23?: pb<23, bool>; + field24?: pb<24, bool>; + field25?: pb<25, bool>; + field26?: pb<26, bool>; + field27?: pb<27, bool>; + field28?: pb<28, bool>; + field29?: pb<29, bool>; + field30?: pb<30, bool>; + field31?: pb<31, bool>; + field32?: pb<32, bool>; + field5001?: pb<5001, bool>; + field5002?: pb<5002, bool>; + field5003?: pb<5003, bool>; +} +export interface OidbGroupListConfig2 { + field1?: pb<1, bool>; + field2?: pb<2, bool>; + field3?: pb<3, bool>; + field4?: pb<4, bool>; + field5?: pb<5, bool>; + field6?: pb<6, bool>; + field7?: pb<7, bool>; + field8?: pb<8, bool>; +} +export interface OidbGroupListConfig3 { + field5?: pb<5, bool>; + field6?: pb<6, bool>; +} +export interface OidbGroupListConfig { + config1?: pb<1, OidbGroupListConfig1>; + config2?: pb<2, OidbGroupListConfig2>; + config3?: pb<3, OidbGroupListConfig3>; +} +export interface OidbGroupListRequest { + config?: pb<1, OidbGroupListConfig>; +} +export interface OidbGroupMemberListBody { + memberName?: pb<10, bool>; + memberCard?: pb<11, bool>; + level?: pb<12, bool>; + field13?: pb<13, bool>; + field16?: pb<16, bool>; + specialTitle?: pb<17, bool>; + field18?: pb<18, bool>; + field20?: pb<20, bool>; + field21?: pb<21, bool>; + joinTimestamp?: pb<100, bool>; + lastMsgTimestamp?: pb<101, bool>; + shutUpTimestamp?: pb<102, bool>; + field103?: pb<103, bool>; + field104?: pb<104, bool>; + field105?: pb<105, bool>; + field106?: pb<106, bool>; + permission?: pb<107, bool>; + field200?: pb<200, bool>; + field201?: pb<201, bool>; +} +export interface OidbGroupMemberListRequest { + groupUin?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; + body?: pb<4, OidbGroupMemberListBody>; + token?: pb<15, string>; +} +export interface GroupRecallInfo { + sequence?: pb<1, uint_32>; + random?: pb<2, uint_32>; + field3?: pb<3, uint_32>; +} +export interface GroupRecallSettings { + field1?: pb<1, uint_32>; +} +export interface GroupRecallRequest { + type?: pb<1, uint_32>; + groupUin?: pb<2, uint_32>; + info?: pb<3, GroupRecallInfo>; + settings?: pb<4, GroupRecallSettings>; +} +export interface C2CRecallInfo { + clientSequence?: pb<1, uint_32>; + random?: pb<2, uint_32>; + messageId?: pb<3, uint_64>; + timestamp?: pb<4, uint_32>; + field5?: pb<5, uint_32>; + messageSequence?: pb<6, uint_32>; +} +export interface C2CRecallSettings { + field1?: pb<1, bool>; + field2?: pb<2, bool>; +} +export interface C2CRecallRequest { + type?: pb<1, uint_32>; + targetUid?: pb<3, string>; + info?: pb<4, C2CRecallInfo>; + settings?: pb<5, C2CRecallSettings>; + field6?: pb<6, bool>; +} +// Field numbers are 2..7 — NOT 1..4. The 0x9082 request body is nested +// inside the OIDB envelope's `body` (which itself uses fields 1-5,11,12), +// so the inner offsets start at 2 to match Lagrange.Core V2's +// `OidbSvcTrpcTcp0x9082` definition. Sending `type` at field 4 instead of +// 5 makes the server read `EmojiType` as zero and reject with +// "ReqBody.EmojiType: value must be greater than 0". +// +// Field6/Field7 are unused booleans that Lagrange serialises as `false`; +// the server tolerates them missing, but we emit them to stay byte- +// identical with Lagrange in case the validator gets stricter. +export interface OidbGroupReaction { + groupUin?: pb<2, uint_32>; + sequence?: pb<3, uint_32>; + code?: pb<4, string>; + type?: pb<5, uint_32>; + field6?: pb<6, bool>; + field7?: pb<7, bool>; +} +export interface GroupReadedReportItem { + groupUin?: pb<1, uint_64>; + lastReadSeq?: pb<2, uint_64>; +} +export interface C2CReadedReportItem { + uid?: pb<2, string>; + lastReadTime?: pb<3, uint_64>; + lastReadSeq?: pb<4, uint_64>; +} +export interface SsoReadedReportReq { + groupList?: pb_repeated<1, GroupReadedReportItem>; + c2cList?: pb_repeated<2, C2CReadedReportItem>; +} +export interface OidbClientKeyReq {} +export interface OidbClientKeyResp { + keyIndex?: pb<2, uint_32>; + clientKey?: pb<3, string>; + expireTime?: pb<4, uint_32>; +} +export interface OidbGetPskeyReq { + domainList?: pb_repeated<1, string>; +} +export interface OidbPskeyItem { + domain?: pb<1, string>; + pskey?: pb<2, string>; + expireTime?: pb<3, uint_64>; +} +export interface OidbGetPskeyResp { + pskeyItems?: pb_repeated<1, OidbPskeyItem>; +} +export interface SetStatusCustomExt { + faceId?: pb<1, uint_32>; + text?: pb<2, string>; + faceType?: pb<3, uint_32>; +} +export interface SetStatusReq { + status?: pb<1, int_32>; + extStatus?: pb<2, int_32>; + batteryStatus?: pb<3, int_32>; + customExt?: pb<4, SetStatusCustomExt>; +} +export interface SetStatusResp { + errCode?: pb<1, int_32>; + errMsg?: pb<2, string>; +} +export interface OidbProfileStringItem { + fieldId?: pb<1, uint_32>; + value?: pb<2, string>; +} +export interface OidbProfileIntItem { + fieldId?: pb<1, uint_32>; + value?: pb<2, uint_64>; +} +export interface OidbSetProfile { + uin?: pb<1, uint_64>; + stringProfiles?: pb_repeated<2, OidbProfileStringItem>; + intProfiles?: pb_repeated<3, OidbProfileIntItem>; +} +export interface Oidb0x7edInteraction { + totalCount?: pb<1, uint_32>; + newCount?: pb<2, uint_32>; + todayCount?: pb<3, uint_32>; + lastTime?: pb<4, uint_64>; +} +export interface Oidb0x7edUserLikeInfo { + uid?: pb<1, string>; + time?: pb<2, uint_64>; + favoriteInfo?: pb<3, Oidb0x7edInteraction>; + voteInfo?: pb<4, Oidb0x7edInteraction>; +} +export interface Oidb0x7edReq { + targetUid?: pb<1, string>; + basic?: pb<2, uint_32>; + vote?: pb<3, uint_32>; + favorite?: pb<4, uint_32>; + start?: pb<12, uint_32>; + limit?: pb<103, uint_32>; +} +export interface Oidb0x7edResp { + userLikeInfos?: pb_repeated<1, Oidb0x7edUserLikeInfo>; +} +export interface Oidb0x8a7Req { + basic1?: pb<1, uint_32>; + basic2?: pb<2, uint_32>; + basic3?: pb<3, uint_32>; + uin?: pb<4, uint_64>; + groupId?: pb<5, uint_64>; + type?: pb<12, uint_32>; +} +export interface Oidb0x8a7Resp { + uinRemain?: pb<2, uint_32>; + groupRemain?: pb<3, uint_32>; + msg?: pb<4, string>; + canAtAll?: pb<6, bool>; +} +export interface Oidb0xe17Req { + jsonBody?: pb<3, string>; +} +export interface Oidb0xe17Resp { + jsonBody?: pb<4, string>; +} +export interface Oidb0x112aProfileInfo { + tag?: pb<1, uint_32>; + value?: pb<2, string>; +} +export interface Oidb0x112aReq { + uin?: pb<1, uint_64>; + profile?: pb<2, Oidb0x112aProfileInfo>; +} +export interface Oidb0x112aResp {} +export interface Oidb0xcd4ReqBody { + uid?: pb<1, string>; + chatType?: pb<2, uint_32>; + eventType?: pb<3, uint_32>; +} +export interface Oidb0xcd4Req { + reqBody?: pb<1, Oidb0xcd4ReqBody>; +} +export interface Oidb0xcd4Resp {} +export interface Oidb0x990TranslateReq { + srcLang?: pb<1, string>; + dstLang?: pb<2, string>; + words?: pb_repeated<3, string>; +} +export interface Oidb0x990Req { + translateReq?: pb<2, Oidb0x990TranslateReq>; + tag10?: pb<10, uint_32>; + tag12?: pb<12, uint_32>; +} +export interface Oidb0x990TranslateResp { + errorCode?: pb<1, uint_32>; + errorMsg?: pb<2, string>; + srcLang?: pb<3, string>; + dstLang?: pb<4, string>; + srcWords?: pb_repeated<5, string>; + dstWords?: pb_repeated<6, string>; +} +export interface Oidb0x990Resp { + translateResp?: pb<2, Oidb0x990TranslateResp>; +} +export interface MiniAppShareReqBody { + appid?: pb<2, string>; + title?: pb<3, string>; + desc?: pb<4, string>; + picUrl?: pb<9, string>; + jumpUrl?: pb<11, string>; + iconUrl?: pb<12, string>; +} +export interface MiniAppShareReq { + sdkVersion?: pb<2, string>; + body?: pb<4, MiniAppShareReqBody>; +} +export interface MiniAppShareRespBody { + jsonStr?: pb<2, string>; +} +export interface MiniAppShareResp { + status?: pb<2, uint_32>; + msg?: pb<3, string>; + body?: pb<4, MiniAppShareRespBody>; +} +export interface Oidb0x112eReq { + botAppid?: pb<3, uint_64>; + msgSeq?: pb<4, uint_64>; + buttonId?: pb<5, string>; + callbackData?: pb<6, string>; + unknown7?: pb<7, uint_32>; + groupId?: pb<8, uint_64>; + unknown9?: pb<9, uint_32>; +} +export interface Oidb0x112eResp { + result?: pb<3, uint_32>; + promptText?: pb<4, string>; + errMsg?: pb<5, string>; +} +export interface Oidb0xeb7SignInInfo { + uin?: pb<1, string>; + groupId?: pb<2, string>; + version?: pb<3, string>; +} +export interface Oidb0xeb7Req { + signInInfo?: pb<2, Oidb0xeb7SignInInfo>; +} +export interface Oidb0xeb7Resp {} +export interface FaceroamOpReqInner { + field1?: pb<1, uint_32>; + osVersion?: pb<2, string>; + qqVersion?: pb<3, string>; +} +export interface FaceroamOpReq { + inner?: pb<1, FaceroamOpReqInner>; + uin?: pb<2, uint_64>; + field3?: pb<3, uint_32>; + field6?: pb<6, uint_32>; +} +export interface FaceroamOpRespItem { + faceIds?: pb_repeated<1, string>; + category?: pb<3, string>; + totalCount?: pb<4, uint_32>; +} +export interface FaceroamOpResp { + retCode?: pb<1, uint_32>; + message?: pb<2, string>; + field3?: pb<3, uint_32>; + item?: pb<4, FaceroamOpRespItem>; +} +export interface Oidb0x9083Req { + groupId?: pb<2, uint_64>; + sequence?: pb<3, uint_32>; + emojiType?: pb<4, uint_32>; + emojiId?: pb<5, string>; + cookie?: pb<6, bytes>; + field7?: pb<7, uint_32>; + count?: pb<8, uint_32>; + field12?: pb<12, uint_32>; +} +export interface Oidb0x9083RespUserInfo { + uin?: pb<1, uint_64>; + field3?: pb<3, uint_32>; +} +export interface Oidb0x9083RespInner { + userInfo?: pb<1, Oidb0x9083RespUserInfo>; + field4?: pb<4, uint_32>; +} +export interface Oidb0x9083Resp { + inner?: pb<4, Oidb0x9083RespInner>; + cookie?: pb<5, bytes>; +} +export interface Oidb0x8a0Req { + groupId?: pb<1, uint_64>; + targetUids?: pb_repeated<3, string>; + rejectAddRequest?: pb<4, uint_32>; + kickReason?: pb<5, bytes>; + field12?: pb<12, uint_32>; +} +export interface Oidb0x8a0Resp {} +export interface Oidb0xf16Inner { + groupId?: pb<1, uint_64>; + remark?: pb<3, string>; +} +export interface Oidb0xf16Req { + inner?: pb<1, Oidb0xf16Inner>; + field12?: pb<12, uint_32>; +} +export interface Oidb0xf16Resp {} +export interface OidbGroupTodo { + groupUin?: pb<1, uint_32>; + msgSeq?: pb<2, uint_64>; +} +export interface OidbStrangerStatusKey { + key?: pb<1, uint_32>; +} +export interface OidbStrangerStatusReq { + uin?: pb<1, uint_32>; + key?: pb_repeated<3, OidbStrangerStatusKey>; +} +export interface OidbSetFriendRemark { + targetUid?: pb<1, string>; + remark?: pb<2, string>; +} +export interface OidbStrangerStatusRespStatus { + key?: pb<1, uint_32>; + value?: pb<2, uint_64>; +} +export interface OidbStrangerStatusRespData { + status?: pb<2, OidbStrangerStatusRespStatus>; +} +export interface OidbStrangerStatusResp { + data?: pb<1, OidbStrangerStatusRespData>; +} +export interface GroupAvatarExtraField3 { + field1?: pb<1, uint_32>; +} +export interface GroupAvatarExtra { + type?: pb<1, uint_32>; + groupUin?: pb<2, uint_32>; + field3?: pb<3, GroupAvatarExtraField3>; + field5?: pb<5, uint_32>; + field6?: pb<6, uint_32>; +} \ No newline at end of file diff --git a/packages/proto-defs/src/oidb-actions/group-album.ts b/packages/proto-defs/src/oidb-actions/group-album.ts new file mode 100644 index 00000000..4692e529 --- /dev/null +++ b/packages/proto-defs/src/oidb-actions/group-album.ts @@ -0,0 +1,216 @@ +import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; + +export interface ExtMapEntry { + key?: pb<1, string>; + value?: pb<2, string>; +} +export interface ReqInfo { + groupId?: pb<1, string>; + albumId?: pb<2, string>; + field3?: pb<3, int_32>; + attachInfo?: pb<4, string>; + field5?: pb<5, string>; +} +export interface GetMediaListRequest { + field1?: pb<1, int_32>; + field2?: pb<2, bytes>; + field3?: pb<3, bytes>; + reqInfo?: pb<4, ReqInfo>; + traceId?: pb<5, string>; + extMap?: pb_repeated<10, ExtMapEntry>; +} +export interface UrlInfo { + url?: pb<1, string>; + width?: pb<2, uint_32>; + height?: pb<3, uint_32>; +} +export interface PhotoUrl { + spec?: pb<1, uint_32>; + url?: pb<2, UrlInfo>; +} +export interface ImageInfo { + name?: pb<1, string>; + sloc?: pb<2, string>; + lloc?: pb<3, string>; + photoUrls?: pb_repeated<4, PhotoUrl>; + defaultUrl?: pb<5, UrlInfo>; + isGif?: pb<6, bool>; + hasRaw?: pb<7, bool>; +} +export interface MediaInfo { + type?: pb<1, uint_32>; + image?: pb<2, ImageInfo>; + uploader?: pb<6, string>; + batchId?: pb<7, uint_64>; + uploadTime?: pb<8, uint_64>; +} +export interface GetMediaListAlbumInfo { + albumId?: pb<1, string>; + owner?: pb<2, string>; + name?: pb<3, string>; +} +export interface GetMediaListRspData { + albumInfo?: pb<1, GetMediaListAlbumInfo>; + mediaList?: pb_repeated<3, MediaInfo>; + prevAttachInfo?: pb<4, string>; + nextAttachInfo?: pb<5, string>; +} +export interface GetMediaListResponse { + field1?: pb<1, int_32>; + field2?: pb<2, bytes>; + field3?: pb<3, bytes>; + data?: pb<4, GetMediaListRspData>; +} +export interface CommentContentItem { + type?: pb<1, uint_32>; + content?: pb<2, string>; +} +export interface CommentUser { + uin?: pb<13, string>; +} +export interface CommentReqContentMeta { + field1?: pb<1, uint_32>; + field2?: pb<2, string>; + field3?: pb<3, string>; + field4?: pb<4, string>; + field5?: pb<5, uint_32>; + field6?: pb<6, string>; +} +export interface CommentReqContent { + field2?: pb<2, CommentUser>; + field3?: pb<3, CommentReqContentMeta>; + clientKey?: pb<7, string>; +} +export interface CommentReqPhotoMeta { + field1?: pb<1, uint_32>; + field2?: pb<2, string>; + lloc?: pb<3, string>; + field4?: pb<4, string>; + field6?: pb<6, string>; + field7?: pb<7, uint_32>; + field8?: pb<8, uint_32>; + field9?: pb<9, uint_32>; + field14?: pb<14, uint_32>; + field15?: pb<15, uint_32>; + field17?: pb<17, uint_32>; +} +export interface CommentReqPhotoWrap { + field2?: pb<2, CommentReqPhotoMeta>; +} +export interface CommentReqPhotoInfo { + field1?: pb<1, CommentReqPhotoWrap>; + albumId?: pb<3, string>; + field5?: pb<5, uint_32>; +} +export interface CommentReqBodyHeader { + field3?: pb<3, uint_32>; + field4?: pb<4, string>; +} +export interface CommentReqBodyUserWrap { + field1?: pb<1, CommentUser>; +} +export interface CommentReqBody { + field1?: pb<1, CommentReqBodyHeader>; + field2?: pb<2, CommentReqBodyUserWrap>; + field5?: pb<5, CommentReqPhotoInfo>; +} +export interface DoQunCommentRequestBody { + groupId?: pb<2, string>; + field3?: pb<3, uint_32>; + reqBody?: pb<4, CommentReqBody>; + field5?: pb<5, CommentReqContent>; +} +export interface DoQunCommentRequest { + field1?: pb<1, int_32>; + field2?: pb<2, bytes>; + field3?: pb<3, bytes>; + body?: pb<4, DoQunCommentRequestBody>; + traceId?: pb<5, string>; + extMap?: pb_repeated<10, ExtMapEntry>; +} +export interface CommentRespUser { + uin?: pb<13, string>; +} +export interface CommentRespContent { + type?: pb<1, uint_32>; + content?: pb<2, string>; +} +export interface CommentRespData { + id?: pb<1, string>; + user?: pb<2, CommentRespUser>; + content?: pb_repeated<3, CommentRespContent>; + time?: pb<4, uint_64>; + clientKey?: pb<7, string>; +} +export interface DoQunCommentResponseComment { + data?: pb<2, CommentRespData>; +} +export interface DoQunCommentResponse { + field1?: pb<1, int_32>; + comment?: pb<4, DoQunCommentResponseComment>; +} +export interface DoQunLikeReqLikeInfo { + id?: pb<1, string>; + status?: pb<3, uint_32>; +} +export interface DoQunLikeReqCellCommon { + time?: pb<3, uint_64>; + feedId?: pb<4, string>; +} +export interface DoQunLikeReqCellUser { + uin?: pb<13, string>; +} +export interface DoQunLikeReqCellUserInfo { + user?: pb<1, DoQunLikeReqCellUser>; +} +export interface DoQunLikeReqCellQunInfo { + qunId?: pb<1, string>; +} +export interface DoQunLikeReqCellMedia { + albumId?: pb<3, string>; + batchId?: pb<5, uint_64>; +} +export interface DoQunLikeReqFeedPublish { + cellCommon?: pb<1, DoQunLikeReqCellCommon>; + cellUserInfo?: pb<2, DoQunLikeReqCellUserInfo>; + cellMedia?: pb<5, DoQunLikeReqCellMedia>; + cellQunInfo?: pb<12, DoQunLikeReqCellQunInfo>; +} +export interface DoQunLikeReqBody { + type?: pb<2, uint_32>; + like?: pb<3, DoQunLikeReqLikeInfo>; + publish?: pb<4, DoQunLikeReqFeedPublish>; + clientKey?: pb<5, string>; +} +export interface DoQunLikeRequest { + field1?: pb<1, int_32>; + field2?: pb<2, string>; + field3?: pb<3, string>; + body?: pb<4, DoQunLikeReqBody>; + extMap?: pb_repeated<10, ExtMapEntry>; +} +export interface DoQunLikeRespBody { + like?: pb<2, DoQunLikeReqLikeInfo>; +} +export interface DoQunLikeResponse { + field1?: pb<1, int_32>; + body?: pb<4, DoQunLikeRespBody>; +} +export interface DeleteMediasReqBody { + groupId?: pb<1, string>; + albumId?: pb<2, string>; + lloc?: pb<3, string>; +} +export interface DeleteMediasRequest { + field1?: pb<1, int_32>; + field2?: pb<2, string>; + field3?: pb<3, string>; + body?: pb<4, DeleteMediasReqBody>; + traceId?: pb<5, string>; + extMap?: pb_repeated<10, ExtMapEntry>; +} +export interface DeleteMediasResponse { + field1?: pb<1, int_32>; + field2?: pb<2, int_32>; + field3?: pb<3, string>; +} \ No newline at end of file diff --git a/packages/proto-defs/src/oidb-actions/group-file.ts b/packages/proto-defs/src/oidb-actions/group-file.ts new file mode 100644 index 00000000..40ed92d4 --- /dev/null +++ b/packages/proto-defs/src/oidb-actions/group-file.ts @@ -0,0 +1,185 @@ +import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; + +export interface OidbGroupFileListReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + targetDirectory?: pb<3, string>; + fileCount?: pb<5, uint_32>; + sortBy?: pb<9, uint_32>; + startIndex?: pb<13, uint_32>; + field17?: pb<17, uint_32>; + field18?: pb<18, uint_32>; +} +export interface OidbGroupFileViewReq { + list?: pb<2, OidbGroupFileListReq>; +} +export interface OidbGroupFileListFolderResp { + folderId?: pb<1, string>; + parentDirectoryId?: pb<2, string>; + folderName?: pb<3, string>; + createTime?: pb<4, uint_32>; + modifiedTime?: pb<5, uint_32>; + creatorUin?: pb<6, uint_32>; + creatorName?: pb<7, string>; + totalFileCount?: pb<8, uint_32>; +} +export interface OidbGroupFileListFileResp { + fileId?: pb<1, string>; + fileName?: pb<2, string>; + fileSize?: pb<3, uint_64>; + busId?: pb<4, uint_32>; + uploadedTime?: pb<6, uint_32>; + expireTime?: pb<7, uint_32>; + modifiedTime?: pb<8, uint_32>; + downloadedTimes?: pb<9, uint_32>; + uploaderName?: pb<14, string>; + uploaderUin?: pb<15, uint_32>; + parentDirectory?: pb<16, string>; +} +export interface OidbGroupFileListItemResp { + type?: pb<1, uint_32>; + folderInfo?: pb<2, OidbGroupFileListFolderResp>; + fileInfo?: pb<3, OidbGroupFileListFileResp>; +} +export interface OidbGroupFileListResp { + retCode?: pb<1, uint_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; + isEnd?: pb<4, bool>; + items?: pb_repeated<5, OidbGroupFileListItemResp>; +} +export interface OidbGroupFileViewResp { + list?: pb<2, OidbGroupFileListResp>; +} +export interface OidbGroupFileUploadReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + busId?: pb<3, uint_32>; + entrance?: pb<4, uint_32>; + targetDirectory?: pb<5, string>; + fileName?: pb<6, string>; + localDirectory?: pb<7, string>; + fileSize?: pb<8, uint_64>; + fileSha1?: pb<9, bytes>; + fileSha3?: pb<10, bytes>; + fileMd5?: pb<11, bytes>; + field15?: pb<15, bool>; +} +export interface OidbGroupFileDownloadReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + busId?: pb<3, uint_32>; + fileId?: pb<4, string>; +} +export interface OidbGroupFileDeleteReq { + groupUin?: pb<1, uint_32>; + busId?: pb<3, uint_32>; + fileId?: pb<5, string>; +} +export interface OidbGroupFileMoveReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + busId?: pb<3, uint_32>; + fileId?: pb<4, string>; + parentDirectory?: pb<5, string>; + targetDirectory?: pb<6, string>; +} +export interface OidbGroupFileReq { + file?: pb<1, OidbGroupFileUploadReq>; + download?: pb<3, OidbGroupFileDownloadReq>; + delete?: pb<4, OidbGroupFileDeleteReq>; + move?: pb<6, OidbGroupFileMoveReq>; +} +export interface OidbGroupFileUploadResp { + retCode?: pb<1, int_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; + uploadIp?: pb<4, string>; + serverDns?: pb<5, string>; + busId?: pb<6, int_32>; + fileId?: pb<7, string>; + checkKey?: pb<8, bytes>; + fileKey?: pb<9, bytes>; + boolFileExist?: pb<10, bool>; + uploadPort?: pb<14, uint_32>; +} +export interface OidbGroupFileDownloadResp { + retCode?: pb<1, uint_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; + downloadIp?: pb<4, string>; + downloadDns?: pb<5, string>; + downloadUrl?: pb<6, bytes>; + saveFileName?: pb<11, string>; +} +export interface OidbGroupFileRetResp { + retCode?: pb<1, uint_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; +} +export interface OidbGroupFileResp { + upload?: pb<1, OidbGroupFileUploadResp>; + download?: pb<3, OidbGroupFileDownloadResp>; + delete?: pb<4, OidbGroupFileRetResp>; + move?: pb<6, OidbGroupFileRetResp>; +} +export interface OidbGroupSendFileInfo { + busiType?: pb<1, uint_32>; + fileId?: pb<2, string>; + field3?: pb<3, uint_32>; + field4?: pb<4, string>; + field5?: pb<5, bool>; +} +export interface OidbGroupSendFileBody { + groupUin?: pb<1, uint_32>; + type?: pb<2, uint_32>; + info?: pb<3, OidbGroupSendFileInfo>; +} +export interface OidbGroupSendFileReq { + body?: pb<5, OidbGroupSendFileBody>; +} +export interface OidbGroupFileCreateFolderReq { + groupUin?: pb<1, uint_32>; + rootDirectory?: pb<3, string>; + folderName?: pb<4, string>; +} +export interface OidbGroupFileDeleteFolderReq { + groupUin?: pb<1, uint_32>; + folderId?: pb<3, string>; +} +export interface OidbGroupFileRenameFolderReq { + groupUin?: pb<1, uint_32>; + folderId?: pb<3, string>; + newFolderName?: pb<4, string>; +} +export interface OidbGroupFileFolderReq { + create?: pb<1, OidbGroupFileCreateFolderReq>; + delete?: pb<2, OidbGroupFileDeleteFolderReq>; + rename?: pb<3, OidbGroupFileRenameFolderReq>; +} +export interface OidbGroupFileFolderRetResp { + retcode?: pb<1, uint_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; +} +export interface OidbGroupFileFolderResp { + create?: pb<1, OidbGroupFileFolderRetResp>; + delete?: pb<2, OidbGroupFileFolderRetResp>; + rename?: pb<3, OidbGroupFileFolderRetResp>; +} +export interface OidbGroupFileCountReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + busId?: pb<3, uint_32>; +} +export interface OidbGroupFileCountResp { + fileCount?: pb<1, uint_32>; + maxCount?: pb<2, uint_32>; + isEnd?: pb<3, bool>; +} +export interface OidbGroupFileCountViewReq { + count?: pb<3, OidbGroupFileCountReq>; +} +export interface OidbGroupFileCountViewResp { + count?: pb<3, OidbGroupFileCountResp>; +} \ No newline at end of file diff --git a/packages/proto-defs/src/oidb-actions/index.ts b/packages/proto-defs/src/oidb-actions/index.ts new file mode 100644 index 00000000..bafcf158 --- /dev/null +++ b/packages/proto-defs/src/oidb-actions/index.ts @@ -0,0 +1,4 @@ +export type * from './base'; +export type * from './group-file'; +export type * from './media'; +export type * from './group-album'; \ No newline at end of file diff --git a/packages/proto-defs/src/oidb-actions/media.ts b/packages/proto-defs/src/oidb-actions/media.ts new file mode 100644 index 00000000..8509e52c --- /dev/null +++ b/packages/proto-defs/src/oidb-actions/media.ts @@ -0,0 +1,242 @@ +import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; + +export interface OidbPrivateFileDownloadReqBody { + receiverUid?: pb<10, string>; + fileUuid?: pb<20, string>; + type?: pb<30, uint_32>; + fileHash?: pb<60, string>; + t2?: pb<601, uint_32>; +} +export interface OidbPrivateFileDownloadReq { + subCommand?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + body?: pb<14, OidbPrivateFileDownloadReqBody>; + field101?: pb<101, uint_32>; + field102?: pb<102, uint_32>; + field200?: pb<200, uint_32>; + field99999?: pb<99999, bytes>; +} +export interface OidbPrivateFileDownloadRespResult { + server?: pb<20, string>; + port?: pb<40, uint_32>; + url?: pb<50, string>; +} +export interface OidbPrivateFileDownloadRespBody { + state?: pb<20, string>; + result?: pb<30, OidbPrivateFileDownloadRespResult>; +} +export interface OidbPrivateFileDownloadResp { + body?: pb<14, OidbPrivateFileDownloadRespBody>; +} +export interface OidbPrivateFileUploadReqBody { + senderUid?: pb<10, string>; + receiverUid?: pb<20, string>; + fileSize?: pb<30, uint_32>; + fileName?: pb<40, string>; + md510MCheckSum?: pb<50, bytes>; + sha1CheckSum?: pb<60, bytes>; + localPath?: pb<70, string>; + md5CheckSum?: pb<110, bytes>; + sha3CheckSum?: pb<120, bytes>; +} +export interface OidbPrivateFileUploadReq { + command?: pb<1, uint_32>; + seq?: pb<2, int_32>; + upload?: pb<19, OidbPrivateFileUploadReqBody>; + businessId?: pb<101, int_32>; + clientType?: pb<102, int_32>; + flagSupportMediaPlatform?: pb<200, int_32>; +} +export interface IPv4 { + outIP?: pb<1, int_32>; + outPort?: pb<2, int_32>; + inIP?: pb<3, int_32>; + inPort?: pb<4, int_32>; + iPType?: pb<5, int_32>; +} +export interface OidbPrivateFileUploadRespBody { + retCode?: pb<10, int_32>; + retMsg?: pb<20, string>; + uploadIp?: pb<60, string>; + uploadDomain?: pb<70, string>; + uploadPort?: pb<80, uint_32>; + uuid?: pb<90, string>; + uploadKey?: pb<100, bytes>; + boolFileExist?: pb<110, bool>; + uploadIpList?: pb_repeated<130, string>; + uploadHttpsPort?: pb<140, int_32>; + uploadHttpsDomain?: pb<150, string>; + uploadDns?: pb<160, string>; + uploadLanip?: pb<170, string>; + fileAddon?: pb<200, string>; + rtpMediaPlatformUploadAddress?: pb_repeated<210, IPv4>; + mediaPlatformUploadKey?: pb<220, bytes>; +} +export interface OidbPrivateFileUploadResp { + upload?: pb<19, OidbPrivateFileUploadRespBody>; +} +export interface NTV2CommonHead { + requestId?: pb<1, uint_32>; + command?: pb<2, uint_32>; +} +export interface NTV2C2CUserInfo { + accountType?: pb<1, uint_32>; + targetUid?: pb<2, string>; +} +export interface NTV2GroupInfo { + groupUin?: pb<1, uint_32>; +} +export interface NTV2SceneInfo { + requestType?: pb<101, uint_32>; + businessType?: pb<102, uint_32>; + sceneType?: pb<200, uint_32>; + c2c?: pb<201, NTV2C2CUserInfo>; + group?: pb<202, NTV2GroupInfo>; +} +export interface NTV2ClientMeta { + agentType?: pb<1, uint_32>; +} +export interface NTV2ReqHead { + common?: pb<1, NTV2CommonHead>; + scene?: pb<2, NTV2SceneInfo>; + client?: pb<3, NTV2ClientMeta>; +} +export interface NTV2DownloadRKeyReq { + types?: pb_repeated<1, uint_32>; +} +export interface NTV2FileType { + type?: pb<1, uint_32>; + picFormat?: pb<2, uint_32>; + videoFormat?: pb<3, uint_32>; + voiceFormat?: pb<4, uint_32>; +} +export interface NTV2FileInfo { + fileSize?: pb<1, uint_32>; + fileHash?: pb<2, string>; + fileSha1?: pb<3, string>; + fileName?: pb<4, string>; + type?: pb<5, NTV2FileType>; + width?: pb<6, uint_32>; + height?: pb<7, uint_32>; + time?: pb<8, uint_32>; + original?: pb<9, uint_32>; +} +export interface NTV2IndexNode { + info?: pb<1, NTV2FileInfo>; + fileUuid?: pb<2, string>; + storeId?: pb<3, uint_32>; + uploadTime?: pb<4, uint_32>; + ttl?: pb<5, uint_32>; + subType?: pb<6, uint_32>; +} +export interface NTV2VideoDownloadExt { + busiType?: pb<1, uint_32>; + sceneType?: pb<2, uint_32>; + subBusiType?: pb<3, uint_32>; +} +export interface NTV2DownloadExt { + video?: pb<2, NTV2VideoDownloadExt>; +} +export interface NTV2DownloadReq { + node?: pb<1, NTV2IndexNode>; + download?: pb<2, NTV2DownloadExt>; +} +export interface NTV2RichMediaReq { + reqHead?: pb<1, NTV2ReqHead>; + download?: pb<3, NTV2DownloadReq>; + downloadRkey?: pb<4, NTV2DownloadRKeyReq>; +} +export interface NTV2RespHead { + common?: pb<1, NTV2CommonHead>; + retCode?: pb<2, uint_32>; + message?: pb<3, string>; +} +export interface NTV2RKeyInfo { + rkey?: pb<1, string>; + rkeyTtlSec?: pb<2, uint_64>; + storeId?: pb<3, uint_32>; + rkeyCreateTime?: pb<4, uint_32>; + type?: pb<5, uint_32>; +} +export interface NTV2DownloadRKeyResp { + rkeys?: pb_repeated<1, NTV2RKeyInfo>; +} +export interface NTV2MediaDownloadInfo { + domain?: pb<1, string>; + urlPath?: pb<2, string>; + httpsPort?: pb<3, uint_32>; +} +export interface NTV2MediaDownloadResp { + rKeyParam?: pb<1, string>; + rKeyTtlSecond?: pb<2, uint_32>; + info?: pb<3, NTV2MediaDownloadInfo>; + rKeyCreateTime?: pb<4, uint_32>; +} +export interface NTV2RichMediaResp { + respHead?: pb<1, NTV2RespHead>; + download?: pb<3, NTV2MediaDownloadResp>; + downloadRkey?: pb<4, NTV2DownloadRKeyResp>; +} +export interface OidbAiVoiceListReq { + groupUin?: pb<1, uint_32>; + chatType?: pb<2, uint_32>; +} +export interface OidbAiVoiceListEntry { + voiceId?: pb<1, string>; + voiceDisplayName?: pb<2, string>; + voiceExampleUrl?: pb<3, string>; +} +export interface OidbAiVoiceListCategory { + category?: pb<1, string>; + voices?: pb_repeated<2, OidbAiVoiceListEntry>; +} +export interface OidbAiVoiceListResp { + content?: pb_repeated<1, OidbAiVoiceListCategory>; +} +export interface OidbAiVoiceSession { + sessionId?: pb<1, uint_32>; +} +export interface OidbAiVoiceReq { + groupUin?: pb<1, uint_32>; + voiceId?: pb<2, string>; + text?: pb<3, string>; + chatType?: pb<4, uint_32>; + session?: pb<5, OidbAiVoiceSession>; +} +export interface OidbAiVoiceFileType { + type?: pb<1, uint_32>; + picFormat?: pb<2, uint_32>; + videoFormat?: pb<3, uint_32>; + voiceFormat?: pb<4, uint_32>; +} +export interface OidbAiVoiceFileInfo { + fileSize?: pb<1, uint_32>; + fileHash?: pb<2, string>; + fileSha1?: pb<3, string>; + fileName?: pb<4, string>; + type?: pb<5, OidbAiVoiceFileType>; + width?: pb<6, uint_32>; + height?: pb<7, uint_32>; + time?: pb<8, uint_32>; + original?: pb<9, uint_32>; +} +export interface OidbAiVoiceIndexNode { + info?: pb<1, OidbAiVoiceFileInfo>; + fileUuid?: pb<2, string>; + storeId?: pb<3, uint_32>; + uploadTime?: pb<4, uint_32>; + ttl?: pb<5, uint_32>; + subType?: pb<6, uint_32>; +} +export interface OidbAiVoiceMsgInfoBody { + index?: pb<1, OidbAiVoiceIndexNode>; +} +export interface OidbAiVoiceMsgInfo { + msgInfoBody?: pb_repeated<1, OidbAiVoiceMsgInfoBody>; +} +export interface OidbAiVoiceResp { + statusCode?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; + msgInfo?: pb<4, OidbAiVoiceMsgInfo>; +} \ No newline at end of file diff --git a/packages/core/src/bridge/proto/proton/oidb.ts b/packages/proto-defs/src/oidb.ts similarity index 72% rename from packages/core/src/bridge/proto/proton/oidb.ts rename to packages/proto-defs/src/oidb.ts index 43fc14a6..9747a903 100644 --- a/packages/core/src/bridge/proto/proton/oidb.ts +++ b/packages/proto-defs/src/oidb.ts @@ -1,19 +1,5 @@ -// Proton (compile-time) form of bridge/proto/oidb.ts. -// -// The legacy file exports a `makeOidbBaseSchema(body)` factory that builds the -// OidbSvcTrpcTcpBase envelope at runtime; here that wrapper is expressed -// once as the generic `OidbBase` interface. Every existing -// `makeOidbBaseSchema(InnerSchema)` call site becomes `OidbBase` -// at the type level, and the proton plugin monomorphizes the codec -// per-instantiation at build time. -// -// `OidbBaseMeta` is the envelope-only view used by fire-and-check calls -// that want to peek at the error code without decoding the body. - import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton'; -// ── OidbSvcTrpcTcpBase wrapper ────────────────────────────────────── - export interface OidbProperty { key?: pb<1, string>; value?: pb<2, bytes>; @@ -29,11 +15,6 @@ export interface OidbBase { reserved?: pb<12, int_32>; } -/** - * Envelope-only view used by fire-and-check calls — proto3 wire format - * silently skips unknown fields, so decoding any OidbBase message with - * this shape returns just the metadata and ignores the inner body. - */ export interface OidbBaseMeta { command?: pb<1, uint_32>; subCommand?: pb<2, uint_32>; @@ -42,8 +23,7 @@ export interface OidbBaseMeta { reserved?: pb<12, int_32>; } -// ── Friend list (0xFD4_1) ─────────────────────────────────────────── - +// Oidb.0xFD4_1 Friend list export interface OidbFriendProperty { code?: pb<1, uint_32>; value?: pb<2, string>; @@ -78,8 +58,7 @@ export interface OidbSvcTrpcTcp0xFD4_1Response { groups?: pb_repeated<102, OidbFriendProperty>; } -// ── Group list (0xFE5_2) ──────────────────────────────────────────── - +// Oidb.0xFE5_2 Group list export interface OidbSvcTrpcTcp0xFE5_2Member { uid?: pb<2, string>; } @@ -109,8 +88,7 @@ export interface OidbSvcTrpcTcp0xFE5_2Response { groups?: pb_repeated<2, OidbSvcTrpcTcp0xFE5_2Group>; } -// ── Group member list (0xFE7_3) ───────────────────────────────────── - +// Oidb.0xFE7_3 Group member list export interface OidbSvcTrpcTcp0xFE7_3Uin { uid?: pb<2, string>; uin?: pb<4, uint_32>; @@ -146,8 +124,7 @@ export interface OidbSvcTrpcTcp0xFE7_3Response { token?: pb<15, string>; } -// ── Group request (0x10C0) ────────────────────────────────────────── - +// OIDB.0x10C0 Group Request export interface OidbSvcTrpcTcp0x10C0ResponseUser { uid?: pb<1, string>; name?: pb<2, string>; diff --git a/packages/proto-defs/tsconfig.json b/packages/proto-defs/tsconfig.json new file mode 100644 index 00000000..4cd329d7 --- /dev/null +++ b/packages/proto-defs/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"], + "noEmit": true + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/packages/proton/package.json b/packages/proton/package.json index 9ad2d5b9..18e2e6db 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/proton", - "version": "1.9.0", + "version": "1.9.1", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/proton/src/ast/analyzer.ts b/packages/proton/src/ast/analyzer.ts index 4041b0a7..2e9abf5b 100644 --- a/packages/proton/src/ast/analyzer.ts +++ b/packages/proton/src/ast/analyzer.ts @@ -268,8 +268,6 @@ export function selectUsedRegistry( ): UsedRegistryResult { const roots = new Set(); const resolved: ResolvedCallSiteRecord[] = []; - const resolveImportedTypeName = createImportedTypeNameResolver(sourceFile); - for (const cs of callSites) { const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile); const typeName = typeNodeToMangledName(cs.firstTypeArg, typeSf, createImportedTypeNameResolver(typeSf)); diff --git a/packages/proton/src/ast/collector.ts b/packages/proton/src/ast/collector.ts index f05deda6..6955b308 100644 --- a/packages/proton/src/ast/collector.ts +++ b/packages/proton/src/ast/collector.ts @@ -1,14 +1,14 @@ import ts from 'typescript'; import { - WireType, - PB_MARKER, PB_REPEATED_MARKER, - type ProtobufField, type ProtobufMessage, - type GenericProtobufTemplate, type GenericFieldTemplate, + WireType, + PB_MARKER, PB_REPEATED_MARKER, + type ProtobufField, type ProtobufMessage, + type GenericProtobufTemplate, type GenericFieldTemplate, } from './types.js'; import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js'; function identityImportedTypeName(name: string): string { - return name; + return name; } /** @@ -19,147 +19,147 @@ function identityImportedTypeName(name: string): string { * type; nested generic instantiations on its fields would otherwise be missed.) */ export function* collectConcreteFieldGenericTypeArgs( - node: ts.InterfaceDeclaration, - resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, + node: ts.InterfaceDeclaration, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, ): IterableIterator { - if (node.typeParameters?.length) return; - for (const m of node.members) { - if (!ts.isPropertySignature(m) || !m.type) continue; - const parsed = parsePbTypeRef(m, resolveImportedTypeName); - if (!parsed) continue; - const ta = parsed.typeArgNode; - if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) { - yield ta; - } + if (node.typeParameters?.length) return; + for (const m of node.members) { + if (!ts.isPropertySignature(m) || !m.type) continue; + const parsed = parsePbTypeRef(m, resolveImportedTypeName); + if (!parsed) continue; + const ta = parsed.typeArgNode; + if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) { + yield ta; } + } } /** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */ export function collectInterface( - node: ts.InterfaceDeclaration, - sf: ts.SourceFile, - resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, + node: ts.InterfaceDeclaration, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, ): ProtobufMessage | null { - const fields: ProtobufField[] = []; - for (const m of node.members) { - if (!ts.isPropertySignature(m) || !m.type) continue; - const f = extractField(m, sf, resolveImportedTypeName); - if (f) fields.push(f); - } - // Register interfaces that are EXPLICITLY empty (`interface X {}`) as - // zero-field proto messages — proto3 wire format allows them and - // downstream code routinely uses them for "this OIDB call has no - // meaningful response body" placeholders. Interfaces that have - // members but no pb-marked fields are NOT proto messages — they - // belong to regular TS types and must stay unregistered to avoid - // polluting the registry. - if (fields.length === 0 && node.members.length > 0) return null; - return { name: node.name.text, fields }; + const fields: ProtobufField[] = []; + for (const m of node.members) { + if (!ts.isPropertySignature(m) || !m.type) continue; + const f = extractField(m, sf, resolveImportedTypeName); + if (f) fields.push(f); + } + // Register interfaces that are EXPLICITLY empty (`interface X {}`) as + // zero-field proto messages — proto3 wire format allows them and + // downstream code routinely uses them for "this OIDB call has no + // meaningful response body" placeholders. Interfaces that have + // members but no pb-marked fields are NOT proto messages — they + // belong to regular TS types and must stay unregistered to avoid + // polluting the registry. + if (fields.length === 0 && node.members.length > 0) return null; + return { name: node.name.text, fields }; } /** Collect a generic interface template. */ export function collectGenericInterface( - node: ts.InterfaceDeclaration, - sf: ts.SourceFile, - resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, + node: ts.InterfaceDeclaration, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, ): GenericProtobufTemplate | null { - const typeParams = node.typeParameters!.map(p => p.name.text); - const tpSet = new Set(typeParams); - const fields: GenericFieldTemplate[] = []; - for (const m of node.members) { - if (!ts.isPropertySignature(m) || !m.type) continue; - const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName); - if (f) fields.push(f); - } - return fields.length ? { name: node.name.text, typeParams, fields } : null; + const typeParams = node.typeParameters!.map(p => p.name.text); + const tpSet = new Set(typeParams); + const fields: GenericFieldTemplate[] = []; + for (const m of node.members) { + if (!ts.isPropertySignature(m) || !m.type) continue; + const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName); + if (f) fields.push(f); + } + return fields.length ? { name: node.name.text, typeParams, fields } : null; } // ── helpers ─────────────────────────────────────────────────────────── function parsePbTypeRef( - member: ts.PropertySignature, - resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, + member: ts.PropertySignature, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, ): { marker: string; fieldNumber: number; typeArgNode: ts.TypeNode } | null { - const t = member.type!; - if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null; - // Resolve the marker name through aliased imports so `import { pb as P }` - // / `import { pb_repeated as PR }` still match the marker constants. - const marker = resolveImportedTypeName(t.typeName.text); - if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null; - const ta = t.typeArguments; - if (!ta || ta.length !== 2) return null; - const fnNode = ta[0]; - if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null; - return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] }; + const t = member.type!; + if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null; + // Resolve the marker name through aliased imports so `import { pb as P }` + // / `import { pb_repeated as PR }` still match the marker constants. + const marker = resolveImportedTypeName(t.typeName.text); + if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null; + const ta = t.typeArguments; + if (!ta || ta.length !== 2) return null; + const fnNode = ta[0]; + if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null; + return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] }; } function resolveTypeName( - node: ts.TypeNode, - sf: ts.SourceFile, - resolveImportedTypeName: ImportedTypeNameResolver, + node: ts.TypeNode, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver, ): string | null { - if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) { - // Generic instantiations (e.g. `Wrapper`) must resolve to the - // mangled name produced by monomorphization so wire-type resolution can - // find the message in the registry. Without this the field would carry - // the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`. - if (node.typeArguments && node.typeArguments.length > 0) { - return typeNodeToMangledName(node, sf, resolveImportedTypeName); - } - return resolveImportedTypeName(node.typeName.text); + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) { + // Generic instantiations (e.g. `Wrapper`) must resolve to the + // mangled name produced by monomorphization so wire-type resolution can + // find the message in the registry. Without this the field would carry + // the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`. + if (node.typeArguments && node.typeArguments.length > 0) { + return typeNodeToMangledName(node, sf, resolveImportedTypeName); } - if (isKeywordTypeNode(node)) return node.getText(sf); - return null; + return resolveImportedTypeName(node.typeName.text); + } + if (isKeywordTypeNode(node)) return node.getText(sf); + return null; } function extractField( - member: ts.PropertySignature, - sf: ts.SourceFile, - resolveImportedTypeName: ImportedTypeNameResolver, + member: ts.PropertySignature, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver, ): ProtobufField | null { - const parsed = parsePbTypeRef(member, resolveImportedTypeName); - if (!parsed) return null; - const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName); - if (!typeName || !ts.isIdentifier(member.name)) return null; - return { - name: (member.name as ts.Identifier).text, - fieldNumber: parsed.fieldNumber, - typeName, - wireType: WireType.Varint, // placeholder - isMessage: false, // placeholder - isOptional: member.questionToken != null, - isRepeated: parsed.marker === PB_REPEATED_MARKER, - }; + const parsed = parsePbTypeRef(member, resolveImportedTypeName); + if (!parsed) return null; + const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName); + if (!typeName || !ts.isIdentifier(member.name)) return null; + return { + name: (member.name as ts.Identifier).text, + fieldNumber: parsed.fieldNumber, + typeName, + wireType: WireType.Varint, // placeholder + isMessage: false, // placeholder + isOptional: member.questionToken != null, + isRepeated: parsed.marker === PB_REPEATED_MARKER, + }; } function extractGenericField( - member: ts.PropertySignature, - sf: ts.SourceFile, - tpSet: Set, - resolveImportedTypeName: ImportedTypeNameResolver, + member: ts.PropertySignature, + sf: ts.SourceFile, + tpSet: Set, + resolveImportedTypeName: ImportedTypeNameResolver, ): GenericFieldTemplate | null { - const parsed = parsePbTypeRef(member, resolveImportedTypeName); - if (!parsed) return null; - const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName); - if (!raw || !ts.isIdentifier(member.name)) return null; - const result: GenericFieldTemplate = { - name: (member.name as ts.Identifier).text, - fieldNumber: parsed.fieldNumber, - rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw), - isTypeParam: tpSet.has(raw), - isOptional: member.questionToken != null, - isRepeated: parsed.marker === PB_REPEATED_MARKER, - }; + const parsed = parsePbTypeRef(member, resolveImportedTypeName); + if (!parsed) return null; + const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName); + if (!raw || !ts.isIdentifier(member.name)) return null; + const result: GenericFieldTemplate = { + name: (member.name as ts.Identifier).text, + fieldNumber: parsed.fieldNumber, + rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw), + isTypeParam: tpSet.has(raw), + isOptional: member.questionToken != null, + isRepeated: parsed.marker === PB_REPEATED_MARKER, + }; // If the field's type-arg is itself a generic instantiation (`Wrapper`, // where U is a type param of the enclosing template), capture the original // source text so monomorphization can substitute U and re-instantiate the // inner generic. Without this the field's `rawTypeName` would stay at the // unsubstituted `'Wrapper__U'` form and the substituted instantiation // would never reach the registry. - const ta = parsed.typeArgNode; - if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) { - result.genericTypeArgText = ta.getText(sf); - result.genericTypeArgSourceFilePath = sf.fileName; - } - return result; + const ta = parsed.typeArgNode; + if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) { + result.genericTypeArgText = ta.getText(sf); + result.genericTypeArgSourceFilePath = sf.fileName; + } + return result; } diff --git a/packages/proton/src/ast/import-resolver.ts b/packages/proton/src/ast/import-resolver.ts index 0d1a4f6a..c8c4509c 100644 --- a/packages/proton/src/ast/import-resolver.ts +++ b/packages/proton/src/ast/import-resolver.ts @@ -19,6 +19,7 @@ export interface ParsedFileEntry { concrete: ProtobufMessage[]; templates: Map; importedTypeSources: Map; + exportAllTypeSources: Map; resolveImportedTypeName: ImportedTypeNameResolver; exportedWrappers: Map; } @@ -36,65 +37,134 @@ interface ImportClause { } function getCallableName(expr: ts.Expression): string | null { - if (ts.isIdentifier(expr)) return expr.text; - if (ts.isPropertyAccessExpression(expr)) return expr.name.text; - return null; + if (ts.isIdentifier(expr)) return expr.text; + if (ts.isPropertyAccessExpression(expr)) return expr.name.text; + return null; } /** Extract all named imports from the source file (both type and value imports). */ function extractImports(sf: ts.SourceFile): ImportClause[] { - const result: ImportClause[] = []; - for (const stmt of sf.statements) { - if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; - const spec = stmt.moduleSpecifier; - if (!ts.isStringLiteral(spec)) continue; - const specifier = spec.text; + const result: ImportClause[] = []; + for (const stmt of sf.statements) { + if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; + const spec = stmt.moduleSpecifier; + if (!ts.isStringLiteral(spec)) continue; + const specifier = spec.text; - const clause = stmt.importClause; - if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { - for (const el of clause.namedBindings.elements) { - result.push({ - importedName: (el.propertyName ?? el.name).text, - localName: el.name.text, - specifier, - }); - } - } + const clause = stmt.importClause; + if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { + for (const el of clause.namedBindings.elements) { + result.push({ + importedName: (el.propertyName ?? el.name).text, + localName: el.name.text, + specifier, + }); + } } - return result; + } + return result; } /** Like `extractImports`, but skips `import type { ... }` and `import { type X }` * entries. Wrapper functions are values, so type-only imports can't introduce * one and we shouldn't eagerly parse their source files just to look for wrappers. */ function extractValueImports(sf: ts.SourceFile): ImportClause[] { - const result: ImportClause[] = []; - for (const stmt of sf.statements) { - if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; - if (stmt.importClause.isTypeOnly) continue; - const spec = stmt.moduleSpecifier; - if (!ts.isStringLiteral(spec)) continue; - const specifier = spec.text; + const result: ImportClause[] = []; + for (const stmt of sf.statements) { + if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; + if (stmt.importClause.isTypeOnly) continue; + const spec = stmt.moduleSpecifier; + if (!ts.isStringLiteral(spec)) continue; + const specifier = spec.text; - const clause = stmt.importClause; - if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { - for (const el of clause.namedBindings.elements) { - if (el.isTypeOnly) continue; - result.push({ - importedName: (el.propertyName ?? el.name).text, - localName: el.name.text, - specifier, - }); - } - } + const clause = stmt.importClause; + if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { + for (const el of clause.namedBindings.elements) { + if (el.isTypeOnly) continue; + result.push({ + importedName: (el.propertyName ?? el.name).text, + localName: el.name.text, + specifier, + }); + } } - return result; + } + return result; } -/** Resolve a relative module specifier to an absolute file path. Returns null if not found. */ -function resolveModulePath(specifier: string, importerPath: string): string | null { - if (!specifier.startsWith('.')) return null; // skip bare/alias specifiers +function extractExportAllSpecifiers(sf: ts.SourceFile): string[] { + const result: string[] = []; + for (const stmt of sf.statements) { + if (!ts.isExportDeclaration(stmt) || stmt.exportClause) continue; + const spec = stmt.moduleSpecifier; + if (spec && ts.isStringLiteral(spec)) result.push(spec.text); + } + return result; +} +// Compiler options used for bare-specifier module resolution. `Bundler` +// matches modern monorepo + vite tooling: it understands `package.json` +// `exports`, `main`, and workspace symlinks without forcing the caller +// to spell out file extensions. We pass these once per process — the +// only consumer here is `ts.resolveModuleName` and it doesn't mutate +// them. +const BARE_SPECIFIER_COMPILER_OPTIONS: ts.CompilerOptions = { + moduleResolution: ts.ModuleResolutionKind.Bundler, + module: ts.ModuleKind.ESNext, + target: ts.ScriptTarget.Latest, + allowImportingTsExtensions: true, +}; + +// Per-process cache for `ts.resolveModuleName`. Hot paths (rebuild on +// HMR) call this hundreds of times — without the cache each call +// re-walks `node_modules` and `package.json` lookups. +let bareModuleResolutionCache: ts.ModuleResolutionCache | null = null; + +function getBareModuleResolutionCache(): ts.ModuleResolutionCache { + if (!bareModuleResolutionCache) { + bareModuleResolutionCache = ts.createModuleResolutionCache( + process.cwd(), + (s) => s, + BARE_SPECIFIER_COMPILER_OPTIONS, + ); + } + return bareModuleResolutionCache; +} + +/** + * Resolve a module specifier (relative OR bare) to an absolute `.ts` + * source-file path. Returns `null` if the resolution lands on something + * proton can't consume (a `.d.ts` declaration, a `.js` build artifact, + * or just not-found). + * + * Two code paths: + * + * - **Relative** (`./foo`, `../bar`): direct file-existence probe. + * Same behavior as before — fast, no TS dependency. Preserved + * verbatim so that the common case (cross-file imports inside a + * single package) is unaffected by the new bare-specifier logic. + * + * - **Bare** (`@scope/pkg`, `pkg-name`, `~alias`): delegate to + * TypeScript's module resolution so monorepo workspaces / npm + * packages / tsconfig paths / package.json `exports` all just work. + * Required to support proto definitions that live in a separate + * workspace package — e.g. moving `bridge/proto/proton/*.ts` into a + * dedicated `@snowluma/proto-defs` package while keeping the call + * sites in `@snowluma/core`. + * + * We deliberately require the resolved file to be `.ts` (not + * `.d.ts`): proton collects `pb<…>` field tags by walking interface + * AST nodes, and a hand-written `.d.ts` *would* work too — but the + * typical `dist/index.d.ts` strips away the `pb<>` type arguments + * proton needs. Asking proto-definition packages to ship source + * `.ts` (the same model `@snowluma/proton` itself uses) avoids that + * footgun entirely. + */ +function resolveModulePath(specifier: string, importerPath: string): string | null { + if (specifier.startsWith('.')) { + // ── Relative path branch (preserved verbatim from the pre-bare- + // specifier implementation; existing callers depend on its + // exact behavior, including the .ts-only filter). ── const base = resolve(dirname(importerPath), specifier); // Try exact path (e.g., './types.ts') @@ -110,275 +180,290 @@ function resolveModulePath(specifier: string, importerPath: string): string | nu if (existsSync(indexTs)) return indexTs; return null; + } + + // ── Bare specifier branch ── + const result = ts.resolveModuleName( + specifier, + importerPath, + BARE_SPECIFIER_COMPILER_OPTIONS, + ts.sys, + getBareModuleResolutionCache(), + ); + const resolved = result.resolvedModule; + if (!resolved) return null; + // Only accept .ts source — see doc comment above for why. + if (resolved.extension !== ts.Extension.Ts) return null; + return resolved.resolvedFileName; } function hasExportModifier(node: ts.Node): boolean { - return ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword); + return ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword); } function matchForwardedProtobufFn( - body: ts.ConciseBody | ts.Block | undefined, - sf: ts.SourceFile, - typeParams: readonly ts.TypeParameterDeclaration[] | undefined, + body: ts.ConciseBody | ts.Block | undefined, + sf: ts.SourceFile, + typeParams: readonly ts.TypeParameterDeclaration[] | undefined, ): WrapperBinding | null { - if (!body || !typeParams?.length) return null; - const typeParamIndexes = new Map(typeParams.map((p, index) => [p.name.text, index])); - const typeParamNames = typeParams.map(p => p.name.text); - const bindings = collectProtobufImportBindings(sf); - let found: WrapperBinding | null = null; + if (!body || !typeParams?.length) return null; + const typeParamIndexes = new Map(typeParams.map((p, index) => [p.name.text, index])); + const typeParamNames = typeParams.map(p => p.name.text); + const bindings = collectProtobufImportBindings(sf); + let found: WrapperBinding | null = null; - function visit(node: ts.Node): void { - if (found) return; - if (ts.isCallExpression(node)) { - const cs = matchProtobufCallSite(node, sf, bindings, { - allowLegacyUnboundCanonical: true, - }); - if ( - cs && + function visit(node: ts.Node): void { + if (found) return; + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, bindings, { + allowLegacyUnboundCanonical: true, + }); + if ( + cs && ts.isTypeReferenceNode(cs.firstTypeArg) && ts.isIdentifier(cs.firstTypeArg.typeName) && typeParamIndexes.has(cs.firstTypeArg.typeName.text) - ) { - found = { - fnName: cs.fnName, - typeArgIndex: typeParamIndexes.get(cs.firstTypeArg.typeName.text)!, - sourceFilePath: sf.fileName, - }; - return; - } + ) { + found = { + fnName: cs.fnName, + typeArgIndex: typeParamIndexes.get(cs.firstTypeArg.typeName.text)!, + sourceFilePath: sf.fileName, + }; + return; + } - if (cs && containsTypeParameter(cs.firstTypeArg, typeParamIndexes)) { - found = { - fnName: cs.fnName, - typeArgIndex: firstTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) ?? 0, - typePattern: cs.firstTypeArg.getText(sf), - typeParamNames, - sourceFilePath: sf.fileName, - }; - return; - } - } - ts.forEachChild(node, visit); + if (cs && containsTypeParameter(cs.firstTypeArg, typeParamIndexes)) { + found = { + fnName: cs.fnName, + typeArgIndex: firstTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) ?? 0, + typePattern: cs.firstTypeArg.getText(sf), + typeParamNames, + sourceFilePath: sf.fileName, + }; + return; + } } + ts.forEachChild(node, visit); + } - visit(body); - return found; + visit(body); + return found; } function containsTypeParameter(typeNode: ts.TypeNode, typeParamIndexes: Map): boolean { - let found = false; - function visit(node: ts.Node): void { - if (found) return; - if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { - found = true; - return; - } - ts.forEachChild(node, visit); + let found = false; + function visit(node: ts.Node): void { + if (found) return; + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { + found = true; + return; } - visit(typeNode); - return found; + ts.forEachChild(node, visit); + } + visit(typeNode); + return found; } function firstTypeParameterIndex(typeNode: ts.TypeNode, typeParamIndexes: Map): number | null { - let index: number | null = null; - function visit(node: ts.Node): void { - if (index !== null) return; - if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { - index = typeParamIndexes.get(node.typeName.text)!; - return; - } - ts.forEachChild(node, visit); + let index: number | null = null; + function visit(node: ts.Node): void { + if (index !== null) return; + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { + index = typeParamIndexes.get(node.typeName.text)!; + return; } - visit(typeNode); - return index; + ts.forEachChild(node, visit); + } + visit(typeNode); + return index; } function instantiateWrapperTypePattern( - binding: WrapperBinding, - callerTypeArgs: ts.NodeArray, - sf: ts.SourceFile, + binding: WrapperBinding, + callerTypeArgs: ts.NodeArray, + sf: ts.SourceFile, ): ts.TypeNode | null { - if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null; + if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null; - let text = binding.typePattern; - for (let i = 0; i < binding.typeParamNames.length; i++) { - const arg = callerTypeArgs[i]; - if (!arg) return null; - text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf)); - } + let text = binding.typePattern; + for (let i = 0; i < binding.typeParamNames.length; i++) { + const arg = callerTypeArgs[i]; + if (!arg) return null; + text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf)); + } - const parsed = ts.createSourceFile('wrapper-type.ts', `type __T = ${text};`, ts.ScriptTarget.Latest, true); - const stmt = parsed.statements[0]; - if (!ts.isTypeAliasDeclaration(stmt)) return null; - return stmt.type; + const parsed = ts.createSourceFile('wrapper-type.ts', `type __T = ${text};`, ts.ScriptTarget.Latest, true); + const stmt = parsed.statements[0]; + if (!ts.isTypeAliasDeclaration(stmt)) return null; + return stmt.type; } function matchForwardedKnownWrapper( - body: ts.ConciseBody | ts.Block | undefined, - typeParams: readonly ts.TypeParameterDeclaration[] | undefined, - knownWrappers: Map, + body: ts.ConciseBody | ts.Block | undefined, + typeParams: readonly ts.TypeParameterDeclaration[] | undefined, + knownWrappers: Map, ): WrapperBinding | null { - if (!body || !typeParams?.length) return null; - const tps = typeParams; // narrowed copy for closure scope - const typeParamIndexes = new Map(tps.map((p, index) => [p.name.text, index])); - let found: WrapperBinding | null = null; + if (!body || !typeParams?.length) return null; + const tps = typeParams; // narrowed copy for closure scope + const typeParamIndexes = new Map(tps.map((p, index) => [p.name.text, index])); + let found: WrapperBinding | null = null; - function visit(node: ts.Node): void { - if (found) return; - if (ts.isCallExpression(node) && node.typeArguments?.length) { - const callableName = getCallableName(node.expression); - const wrapper = callableName ? knownWrappers.get(callableName) : undefined; - const forwardedTypeArg = wrapper ? node.typeArguments[wrapper.typeArgIndex] : undefined; - if ( - wrapper && + function visit(node: ts.Node): void { + if (found) return; + if (ts.isCallExpression(node) && node.typeArguments?.length) { + const callableName = getCallableName(node.expression); + const wrapper = callableName ? knownWrappers.get(callableName) : undefined; + const forwardedTypeArg = wrapper ? node.typeArguments[wrapper.typeArgIndex] : undefined; + if ( + wrapper && forwardedTypeArg && ts.isTypeReferenceNode(forwardedTypeArg) && ts.isIdentifier(forwardedTypeArg.typeName) && !forwardedTypeArg.typeArguments?.length && typeParamIndexes.has(forwardedTypeArg.typeName.text) - ) { - const chainTypeArgIndex = typeParamIndexes.get(forwardedTypeArg.typeName.text)!; - const binding: WrapperBinding = { - fnName: wrapper.fnName, - typeArgIndex: chainTypeArgIndex, - }; - // Propagate the typePattern from the inner wrapper, substituting - // its type-param names with the chain's own. Otherwise the chain - // would treat its own `` as the encoded type rather than the - // wrapped form (e.g. `Wrapper`). - if (wrapper.typePattern && wrapper.typeParamNames?.length === 1) { - const chainParamName = tps[chainTypeArgIndex].name.text; - const wrapperParamName = wrapper.typeParamNames[0]; - binding.typePattern = wrapperParamName === chainParamName - ? wrapper.typePattern - : wrapper.typePattern.replace(new RegExp(`\\b${wrapperParamName}\\b`, 'g'), chainParamName); - binding.typeParamNames = [chainParamName]; - binding.sourceFilePath = wrapper.sourceFilePath; - } - found = binding; - return; - } + ) { + const chainTypeArgIndex = typeParamIndexes.get(forwardedTypeArg.typeName.text)!; + const binding: WrapperBinding = { + fnName: wrapper.fnName, + typeArgIndex: chainTypeArgIndex, + }; + // Propagate the typePattern from the inner wrapper, substituting + // its type-param names with the chain's own. Otherwise the chain + // would treat its own `` as the encoded type rather than the + // wrapped form (e.g. `Wrapper`). + if (wrapper.typePattern && wrapper.typeParamNames?.length === 1) { + const chainParamName = tps[chainTypeArgIndex].name.text; + const wrapperParamName = wrapper.typeParamNames[0]; + binding.typePattern = wrapperParamName === chainParamName + ? wrapper.typePattern + : wrapper.typePattern.replace(new RegExp(`\\b${wrapperParamName}\\b`, 'g'), chainParamName); + binding.typeParamNames = [chainParamName]; + binding.sourceFilePath = wrapper.sourceFilePath; } - - ts.forEachChild(node, visit); + found = binding; + return; + } } - visit(body); - return found; + ts.forEachChild(node, visit); + } + + visit(body); + return found; } function collectWrapperCandidates( - sf: ts.SourceFile, - exportedOnly: boolean, + sf: ts.SourceFile, + exportedOnly: boolean, ): Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> { - const candidates: Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> = []; + const candidates: Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> = []; - for (const stmt of sf.statements) { - if (ts.isFunctionDeclaration(stmt) && stmt.name && (!exportedOnly || hasExportModifier(stmt))) { - candidates.push({ name: stmt.name.text, body: stmt.body, typeParameters: stmt.typeParameters }); - continue; - } - - if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; - for (const decl of stmt.declarationList.declarations) { - if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; - const init = decl.initializer; - if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) { - candidates.push({ name: decl.name.text, body: init.body, typeParameters: init.typeParameters }); - continue; - } - - if (ts.isObjectLiteralExpression(init)) { - for (const prop of init.properties) { - if (ts.isPropertyAssignment(prop)) { - const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; - const propInit = prop.initializer; - if (propName && (ts.isArrowFunction(propInit) || ts.isFunctionExpression(propInit))) { - candidates.push({ name: propName, body: propInit.body, typeParameters: propInit.typeParameters }); - } - continue; - } - - if (ts.isMethodDeclaration(prop)) { - const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; - if (propName) candidates.push({ name: propName, body: prop.body, typeParameters: prop.typeParameters }); - } - } - } - } + for (const stmt of sf.statements) { + if (ts.isFunctionDeclaration(stmt) && stmt.name && (!exportedOnly || hasExportModifier(stmt))) { + candidates.push({ name: stmt.name.text, body: stmt.body, typeParameters: stmt.typeParameters }); + continue; } - return candidates; + if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; + for (const decl of stmt.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; + const init = decl.initializer; + if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) { + candidates.push({ name: decl.name.text, body: init.body, typeParameters: init.typeParameters }); + continue; + } + + if (ts.isObjectLiteralExpression(init)) { + for (const prop of init.properties) { + if (ts.isPropertyAssignment(prop)) { + const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + const propInit = prop.initializer; + if (propName && (ts.isArrowFunction(propInit) || ts.isFunctionExpression(propInit))) { + candidates.push({ name: propName, body: propInit.body, typeParameters: propInit.typeParameters }); + } + continue; + } + + if (ts.isMethodDeclaration(prop)) { + const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + if (propName) candidates.push({ name: propName, body: prop.body, typeParameters: prop.typeParameters }); + } + } + } + } + } + + return candidates; } function collectWrappers( - sf: ts.SourceFile, - exportedOnly: boolean, - externalKnownWrappers: Map = new Map(), + sf: ts.SourceFile, + exportedOnly: boolean, + externalKnownWrappers: Map = new Map(), ): Map { - const wrappers = new Map(); - const localWrapperMembers = new Map>(); - const candidates = collectWrapperCandidates(sf, exportedOnly); + const wrappers = new Map(); + const localWrapperMembers = new Map>(); + const candidates = collectWrapperCandidates(sf, exportedOnly); - for (const candidate of candidates) { - const fn = matchForwardedProtobufFn(candidate.body, sf, candidate.typeParameters); - if (fn) wrappers.set(candidate.name, fn); - } + for (const candidate of candidates) { + const fn = matchForwardedProtobufFn(candidate.body, sf, candidate.typeParameters); + if (fn) wrappers.set(candidate.name, fn); + } - // Detect both intra-file forwarders (`encodeFoo(v) { return encodeBar(v); }` - // where `encodeBar` is local) AND cross-file forwarders to wrappers imported - // from already-parsed modules. Externally known wrappers are seeded by the - // caller (`parseFileForDefinitions`) after it resolves imports. - const knownForForwarding = new Map(); - for (const [k, v] of externalKnownWrappers) knownForForwarding.set(k, v); - for (const [k, v] of wrappers) knownForForwarding.set(k, v); + // Detect both intra-file forwarders (`encodeFoo(v) { return encodeBar(v); }` + // where `encodeBar` is local) AND cross-file forwarders to wrappers imported + // from already-parsed modules. Externally known wrappers are seeded by the + // caller (`parseFileForDefinitions`) after it resolves imports. + const knownForForwarding = new Map(); + for (const [k, v] of externalKnownWrappers) knownForForwarding.set(k, v); + for (const [k, v] of wrappers) knownForForwarding.set(k, v); - for (const candidate of candidates) { - if (wrappers.has(candidate.name)) continue; - const fn = matchForwardedKnownWrapper(candidate.body, candidate.typeParameters, knownForForwarding); - if (fn) wrappers.set(candidate.name, fn); - } + for (const candidate of candidates) { + if (wrappers.has(candidate.name)) continue; + const fn = matchForwardedKnownWrapper(candidate.body, candidate.typeParameters, knownForForwarding); + if (fn) wrappers.set(candidate.name, fn); + } - for (const stmt of sf.statements) { - if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; - for (const decl of stmt.declarationList.declarations) { - if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; - const init = decl.initializer; - if (ts.isObjectLiteralExpression(init)) { - const memberWrappers = new Map(); - for (const prop of init.properties) { - if (!('name' in prop) || !prop.name) continue; - const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; - if (!propName) continue; - const fn = wrappers.get(propName); - if (fn) { - memberWrappers.set(propName, fn); - } - } - if (memberWrappers.size) localWrapperMembers.set(decl.name.text, memberWrappers); - } + for (const stmt of sf.statements) { + if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; + for (const decl of stmt.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; + const init = decl.initializer; + if (ts.isObjectLiteralExpression(init)) { + const memberWrappers = new Map(); + for (const prop of init.properties) { + if (!('name' in prop) || !prop.name) continue; + const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + if (!propName) continue; + const fn = wrappers.get(propName); + if (fn) { + memberWrappers.set(propName, fn); + } } + if (memberWrappers.size) localWrapperMembers.set(decl.name.text, memberWrappers); + } } + } - for (const stmt of sf.statements) { - if (exportedOnly || !ts.isVariableStatement(stmt)) continue; - for (const decl of stmt.declarationList.declarations) { - if (!ts.isIdentifier(decl.name) || !decl.initializer || !ts.isPropertyAccessExpression(decl.initializer)) continue; - if (!ts.isIdentifier(decl.initializer.expression)) continue; - const memberWrappers = localWrapperMembers.get(decl.initializer.expression.text); - const fn = memberWrappers?.get(decl.initializer.name.text); - if (fn) wrappers.set(decl.name.text, fn); - } + for (const stmt of sf.statements) { + if (exportedOnly || !ts.isVariableStatement(stmt)) continue; + for (const decl of stmt.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer || !ts.isPropertyAccessExpression(decl.initializer)) continue; + if (!ts.isIdentifier(decl.initializer.expression)) continue; + const memberWrappers = localWrapperMembers.get(decl.initializer.expression.text); + const fn = memberWrappers?.get(decl.initializer.name.text); + if (fn) wrappers.set(decl.name.text, fn); } + } - return wrappers; + return wrappers; } function collectExportedWrappers( - sf: ts.SourceFile, - externalKnownWrappers: Map = new Map(), + sf: ts.SourceFile, + externalKnownWrappers: Map = new Map(), ): Map { - return collectWrappers(sf, true, externalKnownWrappers); + return collectWrappers(sf, true, externalKnownWrappers); } /** @@ -390,90 +475,110 @@ function collectExportedWrappers( * where `encodeBase` is imported from another module — can be detected. */ function parseFileForDefinitions( - absolutePath: string, - code?: string, - cache?: Map, - parsing?: Set, + absolutePath: string, + code?: string, + cache?: Map, + parsing?: Set, ): ParsedFileEntry { - const sourceText = code ?? readFileSync(absolutePath, 'utf-8'); - const sf = ts.createSourceFile(absolutePath, sourceText, ts.ScriptTarget.Latest, true); - const concrete: ProtobufMessage[] = []; - const templates = new Map(); - const resolveImportedTypeName = createImportedTypeNameResolver(sf); - const importedTypeSources = new Map(); + const sourceText = code ?? readFileSync(absolutePath, 'utf-8'); + const sf = ts.createSourceFile(absolutePath, sourceText, ts.ScriptTarget.Latest, true); + const concrete: ProtobufMessage[] = []; + const templates = new Map(); + const resolveImportedTypeName = createImportedTypeNameResolver(sf); + const importedTypeSources = new Map(); + const exportAllTypeSources = new Map(); - // Collect imported wrapper bindings under their LOCAL names so this file's - // forwarders can match against them. Skip work entirely if there's no cache - // (legacy callers that don't care about cross-file forwarding). - // - // Only descends into value imports (not `import type { ... }`), since - // type-only imports can never introduce a wrapper function. This avoids - // pulling unrelated type-only modules into the cache. - const importedKnownWrappers = new Map(); - if (cache) { - const inProgress = parsing ?? new Set(); - inProgress.add(absolutePath); - for (const imp of extractValueImports(sf)) { - const resolved = resolveModulePath(imp.specifier, absolutePath); - if (!resolved) continue; - if (inProgress.has(resolved)) continue; // cycle guard - let entry = cache.get(resolved); - if (!entry) { - entry = parseFileForDefinitions(resolved, undefined, cache, inProgress); - cache.set(resolved, entry); - } - const wrapperFn = entry.exportedWrappers.get(imp.importedName); - if (wrapperFn) importedKnownWrappers.set(imp.localName, wrapperFn); - } - inProgress.delete(absolutePath); + // Collect imported wrapper bindings under their LOCAL names so this file's + // forwarders can match against them. Skip work entirely if there's no cache + // (legacy callers that don't care about cross-file forwarding). + // + // Only descends into value imports (not `import type { ... }`), since + // type-only imports can never introduce a wrapper function. This avoids + // pulling unrelated type-only modules into the cache. + const importedKnownWrappers = new Map(); + if (cache) { + const inProgress = parsing ?? new Set(); + inProgress.add(absolutePath); + for (const imp of extractValueImports(sf)) { + const resolved = resolveModulePath(imp.specifier, absolutePath); + if (!resolved) continue; + if (inProgress.has(resolved)) continue; // cycle guard + let entry = cache.get(resolved); + if (!entry) { + entry = parseFileForDefinitions(resolved, undefined, cache, inProgress); + cache.set(resolved, entry); + } + const wrapperFn = entry.exportedWrappers.get(imp.importedName); + if (wrapperFn) importedKnownWrappers.set(imp.localName, wrapperFn); } + inProgress.delete(absolutePath); + } - const exportedWrappers = collectExportedWrappers(sf, importedKnownWrappers); + const exportedWrappers = collectExportedWrappers(sf, importedKnownWrappers); - for (const imp of extractImports(sf)) { - const resolved = resolveModulePath(imp.specifier, absolutePath); - if (!resolved) continue; - importedTypeSources.set(imp.importedName, resolved); - importedTypeSources.set(imp.localName, resolved); + for (const imp of extractImports(sf)) { + const resolved = resolveModulePath(imp.specifier, absolutePath); + if (!resolved) continue; + importedTypeSources.set(imp.importedName, resolved); + importedTypeSources.set(imp.localName, resolved); + } + + if (cache) { + const inProgress = parsing ?? new Set(); + inProgress.add(absolutePath); + for (const specifier of extractExportAllSpecifiers(sf)) { + const resolved = resolveModulePath(specifier, absolutePath); + if (!resolved || inProgress.has(resolved)) continue; + let entry = cache.get(resolved); + if (!entry) { + entry = parseFileForDefinitions(resolved, undefined, cache, inProgress); + cache.set(resolved, entry); + } + for (const msg of entry.concrete) exportAllTypeSources.set(msg.name, resolved); + for (const name of entry.templates.keys()) exportAllTypeSources.set(name, resolved); + for (const [name, source] of entry.exportAllTypeSources) exportAllTypeSources.set(name, source); } + inProgress.delete(absolutePath); + } - for (const stmt of sf.statements) { - if (!ts.isInterfaceDeclaration(stmt)) continue; - if (stmt.typeParameters?.length) { - const tpl = collectGenericInterface(stmt, sf, resolveImportedTypeName); - if (tpl) templates.set(tpl.name, tpl); - } else { - const msg = collectInterface(stmt, sf, resolveImportedTypeName); - if (msg) concrete.push(msg); - } + for (const stmt of sf.statements) { + if (!ts.isInterfaceDeclaration(stmt)) continue; + if (stmt.typeParameters?.length) { + const tpl = collectGenericInterface(stmt, sf, resolveImportedTypeName); + if (tpl) templates.set(tpl.name, tpl); + } else { + const msg = collectInterface(stmt, sf, resolveImportedTypeName); + if (msg) concrete.push(msg); } + } - return { - filePath: absolutePath, - concrete, - templates, - importedTypeSources, - resolveImportedTypeName, - exportedWrappers, - }; + return { + filePath: absolutePath, + concrete, + templates, + importedTypeSources, + exportAllTypeSources, + resolveImportedTypeName, + exportedWrappers, + }; } function collectCallRootTypeNodes(sf: ts.SourceFile): ts.TypeNode[] { - const roots: ts.TypeNode[] = []; - const importBindings = collectProtobufImportBindings(sf); + const roots: ts.TypeNode[] = []; + const importBindings = collectProtobufImportBindings(sf); - ts.forEachChild(sf, function visit(node) { - if (ts.isCallExpression(node)) { - const cs = matchProtobufCallSite(node, sf, importBindings, { - allowLegacyUnboundCanonical: true, - }); - if (cs) roots.push(cs.firstTypeArg); - } + ts.forEachChild(sf, function visit(node) { + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, importBindings, { + allowLegacyUnboundCanonical: true, + }); + if (cs) roots.push(cs.firstTypeArg); + } - ts.forEachChild(node, visit); - }); + ts.forEachChild(node, visit); + }); - return roots; + return roots; } interface RootTypeNode { @@ -485,175 +590,175 @@ interface RootTypeNode { * Resolve only the import definitions reachable from protobuf call-site roots. */ export function resolveImports( - code: string, - importerPath: string, - cache: Map, + code: string, + importerPath: string, + cache: Map, ): ImportedDefinitions { - const entryPath = resolve(importerPath); - const entry = parseFileForDefinitions(entryPath, code, cache); - const concrete = new Map(); - const templates = new Map(); - const fileEntries = new Map([[entryPath, entry]]); - const visitedConcrete = new Set(); - const visitedTemplates = new Set(); - const importedObjectWrapperMembers = new Map>(); + const entryPath = resolve(importerPath); + const entry = parseFileForDefinitions(entryPath, code, cache); + const concrete = new Map(); + const templates = new Map(); + const fileEntries = new Map([[entryPath, entry]]); + const visitedConcrete = new Set(); + const visitedTemplates = new Set(); + const importedObjectWrapperMembers = new Map>(); - function getEntry(filePath: string): ParsedFileEntry { - const abs = resolve(filePath); - const known = fileEntries.get(abs); - if (known) return known; + function getEntry(filePath: string): ParsedFileEntry { + const abs = resolve(filePath); + const known = fileEntries.get(abs); + if (known) return known; - let parsed = cache.get(abs); - if (!parsed) { - parsed = parseFileForDefinitions(abs, undefined, cache); - cache.set(abs, parsed); - } - - fileEntries.set(abs, parsed); - return parsed; + let parsed = cache.get(abs); + if (!parsed) { + parsed = parseFileForDefinitions(abs, undefined, cache); + cache.set(abs, parsed); } - function collectCalledGenericIdentifiers(sf: ts.SourceFile): Set { - const names = new Set(); + fileEntries.set(abs, parsed); + return parsed; + } - ts.forEachChild(sf, function visit(node) { - if (ts.isCallExpression(node) && node.typeArguments?.length) { - const callableName = getCallableName(node.expression); - if (callableName) names.add(callableName); - } + function collectCalledGenericIdentifiers(sf: ts.SourceFile): Set { + const names = new Set(); - ts.forEachChild(node, visit); - }); + ts.forEachChild(sf, function visit(node) { + if (ts.isCallExpression(node) && node.typeArguments?.length) { + const callableName = getCallableName(node.expression); + if (callableName) names.add(callableName); + } - return names; + ts.forEachChild(node, visit); + }); + + return names; + } + + function collectWrapperBindings(from: ParsedFileEntry, sf: ts.SourceFile): Map { + const bindings = new Map(); + const localWrappers = from.filePath === entryPath ? collectWrappers(sf, false) : from.exportedWrappers; + for (const [name, fn] of localWrappers) bindings.set(name, fn); + + const calledGenericIdentifiers = collectCalledGenericIdentifiers(sf); + for (const imp of extractImports(sf)) { + if (!calledGenericIdentifiers.has(imp.localName)) continue; + const resolved = resolveModulePath(imp.specifier, from.filePath); + if (!resolved) continue; + const wrapperFn = getEntry(resolved).exportedWrappers.get(imp.importedName); + if (wrapperFn) bindings.set(imp.localName, wrapperFn); + + const importedEntry = getEntry(resolved); + const memberNames = [...importedEntry.exportedWrappers.keys()].filter(name => calledGenericIdentifiers.has(name)); + if (memberNames.length) { + const members = new Map(); + for (const name of memberNames) { + const memberBinding = importedEntry.exportedWrappers.get(name)!; + members.set(name, memberBinding); + bindings.set(name, memberBinding); + } + importedObjectWrapperMembers.set(imp.localName, members); + } } - function collectWrapperBindings(from: ParsedFileEntry, sf: ts.SourceFile): Map { - const bindings = new Map(); - const localWrappers = from.filePath === entryPath ? collectWrappers(sf, false) : from.exportedWrappers; - for (const [name, fn] of localWrappers) bindings.set(name, fn); + return bindings; + } - const calledGenericIdentifiers = collectCalledGenericIdentifiers(sf); - for (const imp of extractImports(sf)) { - if (!calledGenericIdentifiers.has(imp.localName)) continue; - const resolved = resolveModulePath(imp.specifier, from.filePath); - if (!resolved) continue; - const wrapperFn = getEntry(resolved).exportedWrappers.get(imp.importedName); - if (wrapperFn) bindings.set(imp.localName, wrapperFn); + function resolveTypeName(typeName: string, from: ParsedFileEntry): void { + if (typeName in PRIMITIVE_TYPE_MAP) return; - const importedEntry = getEntry(resolved); - const memberNames = [...importedEntry.exportedWrappers.keys()].filter(name => calledGenericIdentifiers.has(name)); - if (memberNames.length) { - const members = new Map(); - for (const name of memberNames) { - const memberBinding = importedEntry.exportedWrappers.get(name)!; - members.set(name, memberBinding); - bindings.set(name, memberBinding); - } - importedObjectWrapperMembers.set(imp.localName, members); - } - } + const concreteMsg = from.concrete.find(msg => msg.name === typeName); + if (concreteMsg) { + const visitKey = `${from.filePath}:message:${typeName}`; + if (visitedConcrete.has(visitKey)) return; + visitedConcrete.add(visitKey); - return bindings; + if (from.filePath !== entryPath && !concrete.has(concreteMsg.name)) { + concrete.set(concreteMsg.name, concreteMsg); + } + + for (const field of concreteMsg.fields) { + resolveTypeName(field.typeName, from); + } + return; } - function resolveTypeName(typeName: string, from: ParsedFileEntry): void { - if (typeName in PRIMITIVE_TYPE_MAP) return; + const template = from.templates.get(typeName); + if (template) { + const visitKey = `${from.filePath}:template:${typeName}`; + if (visitedTemplates.has(visitKey)) return; + visitedTemplates.add(visitKey); - const concreteMsg = from.concrete.find(msg => msg.name === typeName); - if (concreteMsg) { - const visitKey = `${from.filePath}:message:${typeName}`; - if (visitedConcrete.has(visitKey)) return; - visitedConcrete.add(visitKey); + if (from.filePath !== entryPath && !templates.has(template.name)) { + templates.set(template.name, template); + } - if (from.filePath !== entryPath && !concrete.has(concreteMsg.name)) { - concrete.set(concreteMsg.name, concreteMsg); - } - - for (const field of concreteMsg.fields) { - resolveTypeName(field.typeName, from); - } - return; - } - - const template = from.templates.get(typeName); - if (template) { - const visitKey = `${from.filePath}:template:${typeName}`; - if (visitedTemplates.has(visitKey)) return; - visitedTemplates.add(visitKey); - - if (from.filePath !== entryPath && !templates.has(template.name)) { - templates.set(template.name, template); - } - - for (const field of template.fields) { - if (!field.isTypeParam) resolveTypeName(field.rawTypeName, from); - } - return; - } - - const importedPath = from.importedTypeSources.get(typeName); - if (!importedPath) return; - - resolveTypeName(typeName, getEntry(importedPath)); + for (const field of template.fields) { + if (!field.isTypeParam) resolveTypeName(field.rawTypeName, from); + } + return; } - function resolveTypeNode(typeNode: ts.TypeNode, from: ParsedFileEntry): void { - if (isKeywordTypeNode(typeNode)) return; - if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return; + const importedPath = from.importedTypeSources.get(typeName) ?? from.exportAllTypeSources.get(typeName); + if (!importedPath) return; - const typeName = from.resolveImportedTypeName(typeNode.typeName.text); - resolveTypeName(typeName, from); + resolveTypeName(typeName, getEntry(importedPath)); + } - if (!typeNode.typeArguments?.length) return; - for (const typeArg of typeNode.typeArguments) { - resolveTypeNode(typeArg, from); - } + function resolveTypeNode(typeNode: ts.TypeNode, from: ParsedFileEntry): void { + if (isKeywordTypeNode(typeNode)) return; + if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return; + + const typeName = from.resolveImportedTypeName(typeNode.typeName.text); + resolveTypeName(typeName, from); + + if (!typeNode.typeArguments?.length) return; + for (const typeArg of typeNode.typeArguments) { + resolveTypeNode(typeArg, from); } + } - const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true)) - .map(typeNode => ({ typeNode, from: entry })); - const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true); - const wrapperBindings = collectWrapperBindings(entry, entrySourceFile); + const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true)) + .map(typeNode => ({ typeNode, from: entry })); + const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true); + const wrapperBindings = collectWrapperBindings(entry, entrySourceFile); - ts.forEachChild(entrySourceFile, function visit(node) { - if ( - ts.isCallExpression(node) && + ts.forEachChild(entrySourceFile, function visit(node) { + if ( + ts.isCallExpression(node) && node.typeArguments?.length && getCallableName(node.expression) && ( - wrapperBindings.has(getCallableName(node.expression)!) || + wrapperBindings.has(getCallableName(node.expression)!) || ( - ts.isPropertyAccessExpression(node.expression) && + ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && importedObjectWrapperMembers.get(node.expression.expression.text)?.has(node.expression.name.text) ) ) - ) { - const binding = wrapperBindings.get(getCallableName(node.expression)!) ?? ( - ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) - ? importedObjectWrapperMembers.get(node.expression.expression.text)?.get(node.expression.name.text) - : undefined - ); - if (!binding) return; - const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile); - if (typeArg) rootTypeNodes.push({ - typeNode: typeArg, - from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry, - }); - if (binding.typePattern) { - for (const callerTypeArg of node.typeArguments) { - rootTypeNodes.push({ typeNode: callerTypeArg, from: entry }); - } - } + ) { + const binding = wrapperBindings.get(getCallableName(node.expression)!) ?? ( + ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) + ? importedObjectWrapperMembers.get(node.expression.expression.text)?.get(node.expression.name.text) + : undefined + ); + if (!binding) return; + const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile); + if (typeArg) rootTypeNodes.push({ + typeNode: typeArg, + from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry, + }); + if (binding.typePattern) { + for (const callerTypeArg of node.typeArguments) { + rootTypeNodes.push({ typeNode: callerTypeArg, from: entry }); } - - ts.forEachChild(node, visit); - }); - - for (const root of rootTypeNodes) { - resolveTypeNode(root.typeNode, root.from); + } } - return { concrete: [...concrete.values()], templates, wrapperBindings }; + ts.forEachChild(node, visit); + }); + + for (const root of rootTypeNodes) { + resolveTypeNode(root.typeNode, root.from); + } + + return { concrete: [...concrete.values()], templates, wrapperBindings }; } diff --git a/packages/proton/src/ast/monomorphizer.ts b/packages/proton/src/ast/monomorphizer.ts index 219c5d1a..29d9e47b 100644 --- a/packages/proton/src/ast/monomorphizer.ts +++ b/packages/proton/src/ast/monomorphizer.ts @@ -1,15 +1,15 @@ import ts from 'typescript'; import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js'; import { - isKeywordTypeNode, - createImportedTypeNameResolver, - resolveSourceFileForTypeNode, - type ImportedTypeNameResolver, - typeNodeToMangledName, + isKeywordTypeNode, + createImportedTypeNameResolver, + resolveSourceFileForTypeNode, + type ImportedTypeNameResolver, + typeNodeToMangledName, } from './utils.js'; function identityImportedTypeName(name: string): string { - return name; + return name; } /** Resolved value for a single template type parameter. */ @@ -28,104 +28,104 @@ interface ResolvedTypeArg { * Returns the mangled name of the concrete type, or null if it cannot be resolved. */ export function monomorphizeTypeNode( - typeNode: ts.TypeNode, - sf: ts.SourceFile, - templates: Map, - out: Map, - resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, + typeNode: ts.TypeNode, + sf: ts.SourceFile, + templates: Map, + out: Map, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, ): string | null { - if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null; + if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null; - const baseName = resolveImportedTypeName(typeNode.typeName.text); - const typeArgs = typeNode.typeArguments; - if (!typeArgs || typeArgs.length === 0) return baseName; // already concrete + const baseName = resolveImportedTypeName(typeNode.typeName.text); + const typeArgs = typeNode.typeArguments; + if (!typeArgs || typeArgs.length === 0) return baseName; // already concrete - const tpl = templates.get(baseName); - if (!tpl || typeArgs.length !== tpl.typeParams.length) return null; + const tpl = templates.get(baseName); + if (!tpl || typeArgs.length !== tpl.typeParams.length) return null; - const mangledName = typeNodeToMangledName(typeNode, sf, resolveImportedTypeName); - if (out.has(mangledName)) return mangledName; // already done + const mangledName = typeNodeToMangledName(typeNode, sf, resolveImportedTypeName); + if (out.has(mangledName)) return mangledName; // already done - // Resolve each type parameter → both mangled name AND source text. - const paramMap = new Map(); - for (let i = 0; i < tpl.typeParams.length; i++) { - const resolved = resolveTypeArg(typeArgs[i], sf, templates, out, resolveImportedTypeName); - if (!resolved) return null; - paramMap.set(tpl.typeParams[i], resolved); + // Resolve each type parameter → both mangled name AND source text. + const paramMap = new Map(); + for (let i = 0; i < tpl.typeParams.length; i++) { + const resolved = resolveTypeArg(typeArgs[i], sf, templates, out, resolveImportedTypeName); + if (!resolved) return null; + paramMap.set(tpl.typeParams[i], resolved); + } + + // Substitute type params in template fields. + const fields: ProtobufField[] = tpl.fields.map(f => { + if (f.genericTypeArgText) { + // Field type is an inner generic instantiation referencing template + // type params (e.g. `pb>`). Substitute the params into + // the captured text, re-parse, and re-monomorphize so the resulting + // concrete instantiation (`Wrapper`) lands in `out`. + let substituted = f.genericTypeArgText; + for (const [paramName, value] of paramMap) { + substituted = substituted.replace( + new RegExp(`\\b${paramName}\\b`, 'g'), + value.text, + ); + } + const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName; + const innerSf = ts.createSourceFile( + innerSfPath, + `type __X = ${substituted};`, + ts.ScriptTarget.Latest, + true, + ); + const stmt = innerSf.statements[0]; + let resolvedTypeName: string | null = null; + if (ts.isTypeAliasDeclaration(stmt)) { + const innerResolver = createImportedTypeNameResolver(innerSf); + resolvedTypeName = monomorphizeTypeNode(stmt.type, innerSf, templates, out, innerResolver); + } + return { + name: f.name, + fieldNumber: f.fieldNumber, + typeName: resolvedTypeName ?? f.rawTypeName, + wireType: WireType.Varint, + isMessage: false, + isOptional: f.isOptional, + isRepeated: f.isRepeated, + }; } + return { + name: f.name, + fieldNumber: f.fieldNumber, + typeName: f.isTypeParam ? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName) : f.rawTypeName, + wireType: WireType.Varint, + isMessage: false, + isOptional: f.isOptional, + isRepeated: f.isRepeated, + }; + }); - // Substitute type params in template fields. - const fields: ProtobufField[] = tpl.fields.map(f => { - if (f.genericTypeArgText) { - // Field type is an inner generic instantiation referencing template - // type params (e.g. `pb>`). Substitute the params into - // the captured text, re-parse, and re-monomorphize so the resulting - // concrete instantiation (`Wrapper`) lands in `out`. - let substituted = f.genericTypeArgText; - for (const [paramName, value] of paramMap) { - substituted = substituted.replace( - new RegExp(`\\b${paramName}\\b`, 'g'), - value.text, - ); - } - const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName; - const innerSf = ts.createSourceFile( - innerSfPath, - `type __X = ${substituted};`, - ts.ScriptTarget.Latest, - true, - ); - const stmt = innerSf.statements[0]; - let resolvedTypeName: string | null = null; - if (ts.isTypeAliasDeclaration(stmt)) { - const innerResolver = createImportedTypeNameResolver(innerSf); - resolvedTypeName = monomorphizeTypeNode(stmt.type, innerSf, templates, out, innerResolver); - } - return { - name: f.name, - fieldNumber: f.fieldNumber, - typeName: resolvedTypeName ?? f.rawTypeName, - wireType: WireType.Varint, - isMessage: false, - isOptional: f.isOptional, - isRepeated: f.isRepeated, - }; - } - return { - name: f.name, - fieldNumber: f.fieldNumber, - typeName: f.isTypeParam ? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName) : f.rawTypeName, - wireType: WireType.Varint, - isMessage: false, - isOptional: f.isOptional, - isRepeated: f.isRepeated, - }; - }); - - out.set(mangledName, { name: mangledName, fields }); - return mangledName; + out.set(mangledName, { name: mangledName, fields }); + return mangledName; } function resolveTypeArg( - node: ts.TypeNode, - sf: ts.SourceFile, - templates: Map, - out: Map, - resolveImportedTypeName: ImportedTypeNameResolver, + node: ts.TypeNode, + sf: ts.SourceFile, + templates: Map, + out: Map, + resolveImportedTypeName: ImportedTypeNameResolver, ): ResolvedTypeArg | null { - const effectiveSf = resolveSourceFileForTypeNode(node, sf); - // Try recursive monomorphization first (handles nested generics). - const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName); - if (mono) return { mangled: mono, text: node.getText(effectiveSf) }; - // Keyword type (string, number, …) - if (isKeywordTypeNode(node)) { - const text = node.getText(effectiveSf); - return { mangled: text, text }; - } - // Simple identifier (uint_32, SomeMsg, …) - if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) { - const name = resolveImportedTypeName(node.typeName.text); - return { mangled: name, text: name }; - } - return null; + const effectiveSf = resolveSourceFileForTypeNode(node, sf); + // Try recursive monomorphization first (handles nested generics). + const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName); + if (mono) return { mangled: mono, text: node.getText(effectiveSf) }; + // Keyword type (string, number, …) + if (isKeywordTypeNode(node)) { + const text = node.getText(effectiveSf); + return { mangled: text, text }; + } + // Simple identifier (uint_32, SomeMsg, …) + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) { + const name = resolveImportedTypeName(node.typeName.text); + return { mangled: name, text: name }; + } + return null; } diff --git a/packages/proton/src/ast/utils.ts b/packages/proton/src/ast/utils.ts index 04a0590f..68370772 100644 --- a/packages/proton/src/ast/utils.ts +++ b/packages/proton/src/ast/utils.ts @@ -3,7 +3,7 @@ import ts from 'typescript'; export type ImportedTypeNameResolver = (name: string) => string; function identityImportedTypeName(name: string): string { - return name; + return name; } // Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in @@ -13,47 +13,47 @@ function identityImportedTypeName(name: string): string { const syntheticTypeSourceFiles = new WeakMap(); export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void { - syntheticTypeSourceFiles.set(node, sf); + syntheticTypeSourceFiles.set(node, sf); } export function resolveSourceFileForTypeNode(node: ts.TypeNode, fallback: ts.SourceFile): ts.SourceFile { - return syntheticTypeSourceFiles.get(node) ?? fallback; + return syntheticTypeSourceFiles.get(node) ?? fallback; } // TS 5.9+ removed ts.isKeywordTypeNode — manual kind-based check const KEYWORD_TYPE_KINDS = new Set([ - ts.SyntaxKind.StringKeyword, - ts.SyntaxKind.NumberKeyword, - ts.SyntaxKind.BooleanKeyword, - ts.SyntaxKind.AnyKeyword, - ts.SyntaxKind.VoidKeyword, - ts.SyntaxKind.UndefinedKeyword, - ts.SyntaxKind.NullKeyword, - ts.SyntaxKind.NeverKeyword, - ts.SyntaxKind.UnknownKeyword, - ts.SyntaxKind.BigIntKeyword, - ts.SyntaxKind.SymbolKeyword, - ts.SyntaxKind.ObjectKeyword, + ts.SyntaxKind.StringKeyword, + ts.SyntaxKind.NumberKeyword, + ts.SyntaxKind.BooleanKeyword, + ts.SyntaxKind.AnyKeyword, + ts.SyntaxKind.VoidKeyword, + ts.SyntaxKind.UndefinedKeyword, + ts.SyntaxKind.NullKeyword, + ts.SyntaxKind.NeverKeyword, + ts.SyntaxKind.UnknownKeyword, + ts.SyntaxKind.BigIntKeyword, + ts.SyntaxKind.SymbolKeyword, + ts.SyntaxKind.ObjectKeyword, ]); export function isKeywordTypeNode(node: ts.Node): boolean { - return KEYWORD_TYPE_KINDS.has(node.kind); + return KEYWORD_TYPE_KINDS.has(node.kind); } export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver { - const localToImported = new Map(); + const localToImported = new Map(); - for (const stmt of sf.statements) { - if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; - const bindings = stmt.importClause.namedBindings; - if (!bindings || !ts.isNamedImports(bindings)) continue; + for (const stmt of sf.statements) { + if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; + const bindings = stmt.importClause.namedBindings; + if (!bindings || !ts.isNamedImports(bindings)) continue; - for (const el of bindings.elements) { - localToImported.set(el.name.text, (el.propertyName ?? el.name).text); - } + for (const el of bindings.elements) { + localToImported.set(el.name.text, (el.propertyName ?? el.name).text); } + } - return (name: string) => localToImported.get(name) ?? name; + return (name: string) => localToImported.get(name) ?? name; } /** @@ -67,19 +67,19 @@ export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeN * the substituted type text rather than garbage from `sf`. */ export function typeNodeToMangledName( - typeNode: ts.TypeNode, - sf: ts.SourceFile, - resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, + typeNode: ts.TypeNode, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, ): string { - const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf); - if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) { - const base = resolveImportedTypeName(typeNode.typeName.text); - if (typeNode.typeArguments && typeNode.typeArguments.length > 0) { - const args = typeNode.typeArguments.map(a => typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName)); - return base + '__' + args.join('__'); - } - return base; + const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf); + if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) { + const base = resolveImportedTypeName(typeNode.typeName.text); + if (typeNode.typeArguments && typeNode.typeArguments.length > 0) { + const args = typeNode.typeArguments.map(a => typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName)); + return base + '__' + args.join('__'); } - if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf); - return typeNode.getText(effectiveSf); + return base; + } + if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf); + return typeNode.getText(effectiveSf); } diff --git a/packages/proton/src/codegen/decoder.ts b/packages/proton/src/codegen/decoder.ts index 0d8b87d2..9b8477d2 100644 --- a/packages/proton/src/codegen/decoder.ts +++ b/packages/proton/src/codegen/decoder.ts @@ -1,154 +1,154 @@ import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js'; function tagValue(field: ProtobufField): number { - const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes' - ? WireType.LengthDelim - : field.wireType; - return ((field.fieldNumber << 3) | wireType) >>> 0; + const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes' + ? WireType.LengthDelim + : field.wireType; + return ((field.fieldNumber << 3) | wireType) >>> 0; } /** Emit inline varint decode, storing result in `varName`. */ function varintDec(varName: string, ind: string): string { - return [ - `${ind}let ${varName} = data[offset++];`, - `${ind}if (${varName} & 0x80) {`, - `${ind} let _s = 7, _b;`, - `${ind} ${varName} &= 0x7f;`, - `${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`, - `${ind}}`, - ].join('\n'); + return [ + `${ind}let ${varName} = data[offset++];`, + `${ind}if (${varName} & 0x80) {`, + `${ind} let _s = 7, _b;`, + `${ind} ${varName} &= 0x7f;`, + `${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`, + `${ind}}`, + ].join('\n'); } function varintDec64(varName: string, ind: string): string { - return [ - `${ind}let ${varName} = 0n, _s = 0n, _b;`, - `${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`, - ].join('\n'); + return [ + `${ind}let ${varName} = 0n, _s = 0n, _b;`, + `${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`, + ].join('\n'); } function isVarint64(typeName: string): boolean { - return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64'; + return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64'; } function isFixed64BigInt(typeName: string): boolean { - return typeName === 'fixed_64' || typeName === 'sfixed_64'; + return typeName === 'fixed_64' || typeName === 'sfixed_64'; } const INLINE_SKIP = [ - ` const wireType = _tag & 0x7;`, - ` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`, - ` else if (wireType === 1) offset += 8;`, - ` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`, - ` else if (wireType === 5) offset += 4;`, + ` const wireType = _tag & 0x7;`, + ` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`, + ` else if (wireType === 1) offset += 8;`, + ` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`, + ` else if (wireType === 5) offset += 4;`, ].join('\n'); export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string { - const locals = msg.fields.map((field, index) => { - const keyword = field.isRepeated ? 'const' : 'let'; - return ` ${keyword} _f${index} = ${getDefault(field)};`; - }); - const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', '); + const locals = msg.fields.map((field, index) => { + const keyword = field.isRepeated ? 'const' : 'let'; + return ` ${keyword} _f${index} = ${getDefault(field)};`; + }); + const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', '); - const L = [ - `function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`, - ...locals, - ` while (offset < end) {`, - ` let _tag = data[offset++];`, - ` if (_tag & 0x80) {`, - ` let _ts = 7, _tb;`, - ` _tag &= 0x7f;`, - ` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`, - ` }`, - ` switch (_tag) {`, - ]; + const L = [ + `function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`, + ...locals, + ` while (offset < end) {`, + ` let _tag = data[offset++];`, + ` if (_tag & 0x80) {`, + ` let _ts = 7, _tb;`, + ` _tag &= 0x7f;`, + ` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`, + ` }`, + ` switch (_tag) {`, + ]; - msg.fields.forEach((field, index) => { - L.push(decodeField(field, index)); - }); + msg.fields.forEach((field, index) => { + L.push(decodeField(field, index)); + }); - L.push( - ` default: {`, - INLINE_SKIP, - ` break;`, - ` }`, - ` }`, - ` }`, - ` return { ${result} };`, - `}`, - ); - return L.join('\n'); + L.push( + ` default: {`, + INLINE_SKIP, + ` break;`, + ` }`, + ` }`, + ` }`, + ` return { ${result} };`, + `}`, + ); + return L.join('\n'); } function decodeField(field: ProtobufField, index: number): string { - const { typeName, wireType, isMessage, isRepeated } = field; - const I = ' '; - const local = `_f${index}`; - const assign = (expr: string) => isRepeated - ? `${I}${local}.push(${expr});` - : `${I}${local} = ${expr};`; + const { typeName, wireType, isMessage, isRepeated } = field; + const I = ' '; + const local = `_f${index}`; + const assign = (expr: string) => isRepeated + ? `${I}${local}.push(${expr});` + : `${I}${local} = ${expr};`; - const L: string[] = [` case ${tagValue(field)}: {`]; + const L: string[] = [` case ${tagValue(field)}: {`]; - if (isMessage) { - L.push(varintDec('_len', I)); - L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`)); - L.push(`${I}offset += _len;`); - } else if (typeName === 'string') { - L.push(varintDec('_len', I)); - L.push(`${I}const _end = offset + _len;`); - L.push(assign(`__td.decode(data.subarray(offset, _end))`)); - L.push(`${I}offset = _end;`); - } else if (typeName === 'bytes') { - L.push(varintDec('_len', I)); - L.push(`${I}const _end = offset + _len;`); - L.push(assign(`data.slice(offset, _end)`)); - L.push(`${I}offset = _end;`); - } else if (typeName === 'bool') { - L.push(varintDec('_val', I)); - L.push(assign(`_val !== 0`)); - } else if (isVarint64(typeName)) { - L.push(varintDec64('_val', I)); - if (typeName === 'uint_64') { - L.push(assign(`_val`)); - } else if (typeName === 'int_64') { - L.push(assign(`BigInt.asIntN(64, _val)`)); - } else { - L.push(assign(`__zigZagDecode64(_val)`)); - } - } else if (typeName === 'sint_32') { - L.push(varintDec('_val', I)); - L.push(assign(`(_val >>> 1) ^ -(_val & 1)`)); - } else if (wireType === WireType.Varint) { - L.push(varintDec('_val', I)); - L.push(assign(`_val >>> 0`)); - } else if (typeName === 'float') { - L.push(assign(`__readFloat32(data, offset)`)); - L.push(`${I}offset += 4;`); - } else if (wireType === WireType.Bit32) { - L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); - L.push(`${I}offset += 4;`); - } else if (typeName === 'double') { - L.push(assign(`__readFloat64(data, offset)`)); - L.push(`${I}offset += 8;`); - } else if (isFixed64BigInt(typeName)) { - if (typeName === 'fixed_64') { - L.push(assign(`__readFixed64(data, offset)`)); - } else { - L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`)); - } - L.push(`${I}offset += 8;`); - } else if (wireType === WireType.Bit64) { - L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); - L.push(`${I}offset += 8;`); + if (isMessage) { + L.push(varintDec('_len', I)); + L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`)); + L.push(`${I}offset += _len;`); + } else if (typeName === 'string') { + L.push(varintDec('_len', I)); + L.push(`${I}const _end = offset + _len;`); + L.push(assign(`__td.decode(data.subarray(offset, _end))`)); + L.push(`${I}offset = _end;`); + } else if (typeName === 'bytes') { + L.push(varintDec('_len', I)); + L.push(`${I}const _end = offset + _len;`); + L.push(assign(`data.slice(offset, _end)`)); + L.push(`${I}offset = _end;`); + } else if (typeName === 'bool') { + L.push(varintDec('_val', I)); + L.push(assign(`_val !== 0`)); + } else if (isVarint64(typeName)) { + L.push(varintDec64('_val', I)); + if (typeName === 'uint_64') { + L.push(assign(`_val`)); + } else if (typeName === 'int_64') { + L.push(assign(`BigInt.asIntN(64, _val)`)); + } else { + L.push(assign(`__zigZagDecode64(_val)`)); } + } else if (typeName === 'sint_32') { + L.push(varintDec('_val', I)); + L.push(assign(`(_val >>> 1) ^ -(_val & 1)`)); + } else if (wireType === WireType.Varint) { + L.push(varintDec('_val', I)); + L.push(assign(`_val >>> 0`)); + } else if (typeName === 'float') { + L.push(assign(`__readFloat32(data, offset)`)); + L.push(`${I}offset += 4;`); + } else if (wireType === WireType.Bit32) { + L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); + L.push(`${I}offset += 4;`); + } else if (typeName === 'double') { + L.push(assign(`__readFloat64(data, offset)`)); + L.push(`${I}offset += 8;`); + } else if (isFixed64BigInt(typeName)) { + if (typeName === 'fixed_64') { + L.push(assign(`__readFixed64(data, offset)`)); + } else { + L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`)); + } + L.push(`${I}offset += 8;`); + } else if (wireType === WireType.Bit64) { + L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); + L.push(`${I}offset += 8;`); + } - L.push(`${I}break;`, ` }`); - return L.join('\n'); + L.push(`${I}break;`, ` }`); + return L.join('\n'); } function getDefault(field: ProtobufField): string { - if (field.isRepeated) return '[]'; - if (field.isOptional || field.isMessage) return 'null'; - const primitive = PRIMITIVE_TYPE_MAP[field.typeName]; - return primitive ? primitive.defaultValue : 'null'; + if (field.isRepeated) return '[]'; + if (field.isOptional || field.isMessage) return 'null'; + const primitive = PRIMITIVE_TYPE_MAP[field.typeName]; + return primitive ? primitive.defaultValue : 'null'; } diff --git a/packages/proton/src/codegen/encoder.ts b/packages/proton/src/codegen/encoder.ts index 372898e7..cc89efc4 100644 --- a/packages/proton/src/codegen/encoder.ts +++ b/packages/proton/src/codegen/encoder.ts @@ -5,65 +5,65 @@ import { WireType, type ProtobufField, type ProtobufMessage, type MessageRegistr * Field 1 + Varint(0) -> [0x08], Field 1 + LenDelim(2) -> [0x0a], etc. */ function computeTagBytes(fieldNumber: number, wireType: number): number[] { - let value = ((fieldNumber << 3) | wireType) >>> 0; - const bytes: number[] = []; - while (value > 0x7f) { - bytes.push((value & 0x7f) | 0x80); - value >>>= 7; - } - bytes.push(value & 0x7f); - return bytes; + let value = ((fieldNumber << 3) | wireType) >>> 0; + const bytes: number[] = []; + while (value > 0x7f) { + bytes.push((value & 0x7f) | 0x80); + value >>>= 7; + } + bytes.push(value & 0x7f); + return bytes; } function writeTag(fieldNumber: number, wireType: number, ind: string): string { - return computeTagBytes(fieldNumber, wireType) - .map(byte => `${ind}buf[offset++] = ${byte};`) - .join('\n'); + return computeTagBytes(fieldNumber, wireType) + .map(byte => `${ind}buf[offset++] = ${byte};`) + .join('\n'); } function varintSize(varName: string, ind: string): string { - return `${ind}size += ${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`; + return `${ind}size += ${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`; } function writeVarint(expr: string, ind: string): string { - return [ - `${ind}let _v = ${expr};`, - `${ind}if (_v < 0x80) {`, - `${ind} buf[offset++] = _v;`, - `${ind}} else if (_v < 0x4000) {`, - `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, - `${ind} buf[offset++] = _v >>> 7;`, - `${ind}} else if (_v < 0x200000) {`, - `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = _v >>> 14;`, - `${ind}} else if (_v < 0x10000000) {`, - `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = _v >>> 21;`, - `${ind}} else {`, - `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = _v >>> 28;`, - `${ind}}`, - ].join('\n'); + return [ + `${ind}let _v = ${expr};`, + `${ind}if (_v < 0x80) {`, + `${ind} buf[offset++] = _v;`, + `${ind}} else if (_v < 0x4000) {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 7;`, + `${ind}} else if (_v < 0x200000) {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 14;`, + `${ind}} else if (_v < 0x10000000) {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 21;`, + `${ind}} else {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 28;`, + `${ind}}`, + ].join('\n'); } function isVarint64(typeName: string): boolean { - return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64'; + return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64'; } function isFixed64BigInt(typeName: string): boolean { - return typeName === 'fixed_64' || typeName === 'sfixed_64'; + return typeName === 'fixed_64' || typeName === 'sfixed_64'; } function bigintVarintExpr(typeName: string, expr: string): string { - if (typeName === 'uint_64') return `BigInt.asUintN(64, ${expr})`; - if (typeName === 'int_64') return `BigInt.asUintN(64, ${expr})`; - return `__zigZagEncode64(${expr})`; + if (typeName === 'uint_64') return `BigInt.asUintN(64, ${expr})`; + if (typeName === 'int_64') return `BigInt.asUintN(64, ${expr})`; + return `__zigZagEncode64(${expr})`; } interface EncoderBlock { @@ -73,518 +73,518 @@ interface EncoderBlock { } export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry): string { - const blocks = msg.fields.map((field, index) => field.isRepeated ? buildRepeatedBlock(field, index) : buildSingularBlock(field, index)); + const blocks = msg.fields.map((field, index) => field.isRepeated ? buildRepeatedBlock(field, index) : buildSingularBlock(field, index)); - const L = [ - `function protobuf_encode_${msg.name}(obj) {`, - ` let size = 0;`, - ...blocks.flatMap(block => block.declare), - ...blocks.flatMap(block => block.size), - ` const buf = new Uint8Array(size);`, - ` let offset = 0;`, - ...blocks.flatMap(block => block.write), - ` return buf;`, - `}`, - ]; - return L.join('\n'); + const L = [ + `function protobuf_encode_${msg.name}(obj) {`, + ` let size = 0;`, + ...blocks.flatMap(block => block.declare), + ...blocks.flatMap(block => block.size), + ` const buf = new Uint8Array(size);`, + ` let offset = 0;`, + ...blocks.flatMap(block => block.write), + ` return buf;`, + `}`, + ]; + return L.join('\n'); } function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock { - const { name, fieldNumber, typeName, wireType, isMessage } = field; - const valueVar = `_f${index}`; - const cacheVar = `_c${index}`; - const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length; + const { name, fieldNumber, typeName, wireType, isMessage } = field; + const valueVar = `_f${index}`; + const cacheVar = `_c${index}`; + const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length; - if (isMessage) { - return { - declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], - size: [ - ` if (${valueVar} != null) {`, - ` ${cacheVar} = protobuf_encode_${typeName}(${valueVar});`, - ` const _len = ${cacheVar}.length;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ], - write: [ - ` if (${valueVar} != null) {`, - ` const _data = ${cacheVar};`, - writeTag(fieldNumber, 2, ' '), - ` const _len = _data.length;`, - writeVarint('_len', ' '), - ` buf.set(_data, offset);`, - ` offset += _len;`, - ` }`, - ], - }; - } + if (isMessage) { + return { + declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${valueVar} != null) {`, + ` ${cacheVar} = protobuf_encode_${typeName}(${valueVar});`, + ` const _len = ${cacheVar}.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${valueVar} != null) {`, + ` const _data = ${cacheVar};`, + writeTag(fieldNumber, 2, ' '), + ` const _len = _data.length;`, + writeVarint('_len', ' '), + ` buf.set(_data, offset);`, + ` offset += _len;`, + ` }`, + ], + }; + } - if (typeName === 'string') { - return { - declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], - size: [ - ` if (${valueVar} != null && ${valueVar} !== "") {`, - ` ${cacheVar} = __utf8Len(${valueVar});`, - ` const _len = ${cacheVar};`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar} !== "") {`, - writeTag(fieldNumber, 2, ' '), - ` const _len = ${cacheVar};`, - writeVarint('_len', ' '), - ` offset = __utf8Write(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } + if (typeName === 'string') { + return { + declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== "") {`, + ` ${cacheVar} = __utf8Len(${valueVar});`, + ` const _len = ${cacheVar};`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== "") {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${cacheVar};`, + writeVarint('_len', ' '), + ` offset = __utf8Write(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } - if (typeName === 'bytes') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [ - ` if (${valueVar} != null && ${valueVar}.length > 0) {`, - ` const _len = ${valueVar}.length;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar}.length > 0) {`, - writeTag(fieldNumber, 2, ' '), - ` const _len = ${valueVar}.length;`, - writeVarint('_len', ' '), - ` buf.set(${valueVar}, offset);`, - ` offset += _len;`, - ` }`, - ], - }; - } + if (typeName === 'bytes') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar}.length > 0) {`, + ` const _len = ${valueVar}.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar}.length > 0) {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${valueVar}.length;`, + writeVarint('_len', ' '), + ` buf.set(${valueVar}, offset);`, + ` offset += _len;`, + ` }`, + ], + }; + } - if (typeName === 'bool') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} === true) size += ${tagLength + 1};`], - write: [ - ` if (${valueVar} === true) {`, - writeTag(fieldNumber, 0, ' '), - ` buf[offset++] = 1;`, - ` }`, - ], - }; - } + if (typeName === 'bool') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} === true) size += ${tagLength + 1};`], + write: [ + ` if (${valueVar} === true) {`, + writeTag(fieldNumber, 0, ' '), + ` buf[offset++] = 1;`, + ` }`, + ], + }; + } - if (isVarint64(typeName)) { - const bigintExpr = bigintVarintExpr(typeName, valueVar); - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [ - ` if (${valueVar} != null && ${valueVar} !== 0n) {`, - ` const _val = ${bigintExpr};`, - ` size += ${tagLength};`, - ` size += __varint64Size(_val);`, - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0n) {`, - ` const _val = ${bigintExpr};`, - writeTag(fieldNumber, 0, ' '), - ` offset = __writeVarint64(buf, offset, _val);`, - ` }`, - ], - }; - } + if (isVarint64(typeName)) { + const bigintExpr = bigintVarintExpr(typeName, valueVar); + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== 0n) {`, + ` const _val = ${bigintExpr};`, + ` size += ${tagLength};`, + ` size += __varint64Size(_val);`, + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0n) {`, + ` const _val = ${bigintExpr};`, + writeTag(fieldNumber, 0, ' '), + ` offset = __writeVarint64(buf, offset, _val);`, + ` }`, + ], + }; + } - if (typeName === 'sint_32') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - ` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '), - ` }`, - ], - }; - } + if (typeName === 'sint_32') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + ` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '), + ` }`, + ], + }; + } - if (wireType === WireType.Varint) { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - ` const _val = ${valueVar} >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`${valueVar} >>> 0`, ' '), - ` }`, - ], - }; - } + if (wireType === WireType.Varint) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + ` const _val = ${valueVar} >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`${valueVar} >>> 0`, ' '), + ` }`, + ], + }; + } - if (typeName === 'float') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 5, ' '), - ` offset = __writeFloat32(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } + if (typeName === 'float') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 5, ' '), + ` offset = __writeFloat32(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } - if (wireType === WireType.Bit32) { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 5, ' '), - ` const _val = ${valueVar};`, - ` buf[offset++] = _val & 0xff;`, - ` buf[offset++] = (_val >> 8) & 0xff;`, - ` buf[offset++] = (_val >> 16) & 0xff;`, - ` buf[offset++] = (_val >> 24) & 0xff;`, - ` }`, - ], - }; - } + if (wireType === WireType.Bit32) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 5, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` }`, + ], + }; + } - if (typeName === 'double') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFloat64(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } + if (typeName === 'double') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFloat64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } - if (isFixed64BigInt(typeName)) { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0n) size += ${tagLength + 8};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0n) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFixed64(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } + if (isFixed64BigInt(typeName)) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0n) size += ${tagLength + 8};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0n) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFixed64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } - if (wireType === WireType.Bit64) { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 1, ' '), - ` const _val = ${valueVar};`, - ` buf[offset++] = _val & 0xff;`, - ` buf[offset++] = (_val >> 8) & 0xff;`, - ` buf[offset++] = (_val >> 16) & 0xff;`, - ` buf[offset++] = (_val >> 24) & 0xff;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` }`, - ], - }; - } + if (wireType === WireType.Bit64) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 1, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` }`, + ], + }; + } - return { declare: [], size: [], write: [] }; + return { declare: [], size: [], write: [] }; } function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock { - const { name, fieldNumber, typeName, wireType, isMessage } = field; - const arrayVar = `_f${index}`; - const cacheVar = `_c${index}`; - const tagWireType = isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType; - const tagLength = computeTagBytes(fieldNumber, tagWireType).length; + const { name, fieldNumber, typeName, wireType, isMessage } = field; + const arrayVar = `_f${index}`; + const cacheVar = `_c${index}`; + const tagWireType = isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType; + const tagLength = computeTagBytes(fieldNumber, tagWireType).length; - if (isMessage) { - return { - declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` ${cacheVar} = new Array(${arrayVar}.length);`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _data = protobuf_encode_${typeName}(${arrayVar}[_i]);`, - ` ${cacheVar}[_i] = _data;`, - ` const _len = _data.length;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _data = ${cacheVar}[_i];`, - writeTag(fieldNumber, 2, ' '), - ` const _len = _data.length;`, - writeVarint('_len', ' '), - ` buf.set(_data, offset);`, - ` offset += _len;`, - ` }`, - ` }`, - ], - }; - } + if (isMessage) { + return { + declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` ${cacheVar} = new Array(${arrayVar}.length);`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = protobuf_encode_${typeName}(${arrayVar}[_i]);`, + ` ${cacheVar}[_i] = _data;`, + ` const _len = _data.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = ${cacheVar}[_i];`, + writeTag(fieldNumber, 2, ' '), + ` const _len = _data.length;`, + writeVarint('_len', ' '), + ` buf.set(_data, offset);`, + ` offset += _len;`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'string') { - return { - declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` ${cacheVar} = new Array(${arrayVar}.length);`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _len = __utf8Len(${arrayVar}[_i]);`, - ` ${cacheVar}[_i] = _len;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _len = ${cacheVar}[_i];`, - writeTag(fieldNumber, 2, ' '), - writeVarint('_len', ' '), - ` offset = __utf8Write(buf, offset, ${arrayVar}[_i]);`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'string') { + return { + declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` ${cacheVar} = new Array(${arrayVar}.length);`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _len = __utf8Len(${arrayVar}[_i]);`, + ` ${cacheVar}[_i] = _len;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _len = ${cacheVar}[_i];`, + writeTag(fieldNumber, 2, ' '), + writeVarint('_len', ' '), + ` offset = __utf8Write(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'bytes') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _data = ${arrayVar}[_i];`, - ` const _len = _data.length;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _data = ${arrayVar}[_i];`, - writeTag(fieldNumber, 2, ' '), - ` const _len = _data.length;`, - writeVarint('_len', ' '), - ` buf.set(_data, offset);`, - ` offset += _len;`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'bytes') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = ${arrayVar}[_i];`, + ` const _len = _data.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = ${arrayVar}[_i];`, + writeTag(fieldNumber, 2, ' '), + ` const _len = _data.length;`, + writeVarint('_len', ' '), + ` buf.set(_data, offset);`, + ` offset += _len;`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'bool') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 1};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 0, ' '), - ` buf[offset++] = ${arrayVar}[_i] ? 1 : 0;`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'bool') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 1};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 0, ' '), + ` buf[offset++] = ${arrayVar}[_i] ? 1 : 0;`, + ` }`, + ` }`, + ], + }; + } - if (isVarint64(typeName)) { - const bigintExpr = bigintVarintExpr(typeName, `${arrayVar}[_i]`); - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _val = ${bigintExpr};`, - ` size += ${tagLength};`, - ` size += __varint64Size(_val);`, - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _val = ${bigintExpr};`, - writeTag(fieldNumber, 0, ' '), - ` offset = __writeVarint64(buf, offset, _val);`, - ` }`, - ` }`, - ], - }; - } + if (isVarint64(typeName)) { + const bigintExpr = bigintVarintExpr(typeName, `${arrayVar}[_i]`); + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ${bigintExpr};`, + ` size += ${tagLength};`, + ` size += __varint64Size(_val);`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ${bigintExpr};`, + writeTag(fieldNumber, 0, ' '), + ` offset = __writeVarint64(buf, offset, _val);`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'sint_32') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _val = ((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0`, ' '), - ` }`, - ` }`, - ], - }; - } + if (typeName === 'sint_32') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0`, ' '), + ` }`, + ` }`, + ], + }; + } - if (wireType === WireType.Varint) { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _val = ${arrayVar}[_i] >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`${arrayVar}[_i] >>> 0`, ' '), - ` }`, - ` }`, - ], - }; - } + if (wireType === WireType.Varint) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ${arrayVar}[_i] >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`${arrayVar}[_i] >>> 0`, ' '), + ` }`, + ` }`, + ], + }; + } - if (typeName === 'float') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 5, ' '), - ` offset = __writeFloat32(buf, offset, ${arrayVar}[_i]);`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'float') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 5, ' '), + ` offset = __writeFloat32(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } - if (wireType === WireType.Bit32) { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 5, ' '), - ` const _val = ${arrayVar}[_i];`, - ` buf[offset++] = _val & 0xff;`, - ` buf[offset++] = (_val >> 8) & 0xff;`, - ` buf[offset++] = (_val >> 16) & 0xff;`, - ` buf[offset++] = (_val >> 24) & 0xff;`, - ` }`, - ` }`, - ], - }; - } + if (wireType === WireType.Bit32) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 5, ' '), + ` const _val = ${arrayVar}[_i];`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'double') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFloat64(buf, offset, ${arrayVar}[_i]);`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'double') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFloat64(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } - if (isFixed64BigInt(typeName)) { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFixed64(buf, offset, ${arrayVar}[_i]);`, - ` }`, - ` }`, - ], - }; - } + if (isFixed64BigInt(typeName)) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFixed64(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } - if (wireType === WireType.Bit64) { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 1, ' '), - ` const _val = ${arrayVar}[_i];`, - ` buf[offset++] = _val & 0xff;`, - ` buf[offset++] = (_val >> 8) & 0xff;`, - ` buf[offset++] = (_val >> 16) & 0xff;`, - ` buf[offset++] = (_val >> 24) & 0xff;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` }`, - ` }`, - ], - }; - } + if (wireType === WireType.Bit64) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 1, ' '), + ` const _val = ${arrayVar}[_i];`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` }`, + ` }`, + ], + }; + } - return { declare: [], size: [], write: [] }; + return { declare: [], size: [], write: [] }; } diff --git a/packages/proton/src/runtime.ts b/packages/proton/src/runtime.ts index a4236fbc..b3b8b185 100644 --- a/packages/proton/src/runtime.ts +++ b/packages/proton/src/runtime.ts @@ -8,11 +8,11 @@ import type { MessageRegistry } from './ast/types.js'; import { buildDependencyRegistry } from './ast/dependency-graph.js'; import { generateCode } from './codegen/generator.js'; import { - normalizeRuntimeMapPath, - runtimeMapToRegistry, - type ProtobufRuntimeMap, - type RuntimeMapCallSite, - type RuntimeMapFnName, + normalizeRuntimeMapPath, + runtimeMapToRegistry, + type ProtobufRuntimeMap, + type RuntimeMapCallSite, + type RuntimeMapFnName, } from './runtime-map.js'; type DynamicEncode = (params: unknown) => Uint8Array; @@ -41,180 +41,180 @@ const dynamicTypeCache = new Map(); * This is disabled by default. */ export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void { - runtimeMapFallback = map; - runtimeMapRegistry = runtimeMapToRegistry(map); - runtimeMapCallSites = map.callSites.map(cs => ({ - ...cs, - file: normalizeRuntimeMapPath(cs.file), - })); - dynamicTypeCache.clear(); + runtimeMapFallback = map; + runtimeMapRegistry = runtimeMapToRegistry(map); + runtimeMapCallSites = map.callSites.map(cs => ({ + ...cs, + file: normalizeRuntimeMapPath(cs.file), + })); + dynamicTypeCache.clear(); } /** Disable dynamic runtime fallback and clear all generated function caches. */ export function protobuf_disableRuntimeMapFallback(): void { - runtimeMapFallback = null; - runtimeMapRegistry = null; - runtimeMapCallSites = []; - dynamicTypeCache.clear(); + runtimeMapFallback = null; + runtimeMapRegistry = null; + runtimeMapCallSites = []; + dynamicTypeCache.clear(); } export function protobuf_encode(_params: T): Uint8Array { - const dynamic = tryDynamicInvoke('protobuf_encode', _params); - if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array; + const dynamic = tryDynamicInvoke('protobuf_encode', _params); + if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array; - throw new Error( - 'protobuf_encode() was not transformed by the @snowluma/proton Vite plugin. ' + + throw new Error( + 'protobuf_encode() was not transformed by the @snowluma/proton Vite plugin. ' + 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', - ); + ); } export function protobuf_decode(_data: Uint8Array): T { - const dynamic = tryDynamicInvoke('protobuf_decode', _data); - if (dynamic !== DYNAMIC_MISS) return dynamic as T; + const dynamic = tryDynamicInvoke('protobuf_decode', _data); + if (dynamic !== DYNAMIC_MISS) return dynamic as T; - throw new Error( - 'protobuf_decode() was not transformed by the @snowluma/proton Vite plugin. ' + + throw new Error( + 'protobuf_decode() was not transformed by the @snowluma/proton Vite plugin. ' + 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', - ); + ); } function tryDynamicInvoke(fnName: RuntimeMapFnName, payload: unknown): unknown { - if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) { - return DYNAMIC_MISS; - } + if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) { + return DYNAMIC_MISS; + } - const caller = getFirstUserFrame(); - if (!caller) return DYNAMIC_MISS; + const caller = getFirstUserFrame(); + if (!caller) return DYNAMIC_MISS; - const callSite = resolveCallSite(fnName, caller); - if (!callSite) return DYNAMIC_MISS; + const callSite = resolveCallSite(fnName, caller); + if (!callSite) return DYNAMIC_MISS; - const typeFns = ensureTypeFunctions(callSite.typeName); - if (!typeFns) return DYNAMIC_MISS; + const typeFns = ensureTypeFunctions(callSite.typeName); + if (!typeFns) return DYNAMIC_MISS; - const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode; - if (typeof fn !== 'function') return DYNAMIC_MISS; + const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode; + if (typeof fn !== 'function') return DYNAMIC_MISS; - return fn(payload as never); + return fn(payload as never); } function ensureTypeFunctions(typeName: string): DynamicTypeFns | null { - const cached = dynamicTypeCache.get(typeName); - if (cached) return cached; - if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null; + const cached = dynamicTypeCache.get(typeName); + if (cached) return cached; + if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null; - const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]); - if (subset.size === 0) return null; + const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]); + if (subset.size === 0) return null; - const generated = generateCode(subset); - if (!generated) return null; + const generated = generateCode(subset); + if (!generated) return null; - const factory = new Function( - `${generated}\nreturn {\n` + + const factory = new Function( + `${generated}\nreturn {\n` + ` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` + ` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` + `};`, - ) as () => DynamicTypeFns; + ) as () => DynamicTypeFns; - const compiled = factory(); - dynamicTypeCache.set(typeName, compiled); - return compiled; + const compiled = factory(); + dynamicTypeCache.set(typeName, compiled); + return compiled; } function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeMapCallSite | null { - const callerFile = normalizeRuntimeMapPath(caller.file); + const callerFile = normalizeRuntimeMapPath(caller.file); - const candidates = runtimeMapCallSites.filter(cs => - cs.fnName === fnName && + const candidates = runtimeMapCallSites.filter(cs => + cs.fnName === fnName && cs.line === caller.line && pathsLikelySame(callerFile, cs.file), - ); + ); - if (candidates.length === 0) return null; - if (candidates.length === 1) return candidates[0]; + if (candidates.length === 0) return null; + if (candidates.length === 1) return candidates[0]; - let best = candidates[0]; - let bestDistance = Math.abs(best.column - caller.column); - for (let i = 1; i < candidates.length; i++) { - const dist = Math.abs(candidates[i].column - caller.column); - if (dist < bestDistance) { - best = candidates[i]; - bestDistance = dist; - } + let best = candidates[0]; + let bestDistance = Math.abs(best.column - caller.column); + for (let i = 1; i < candidates.length; i++) { + const dist = Math.abs(candidates[i].column - caller.column); + if (dist < bestDistance) { + best = candidates[i]; + bestDistance = dist; } - return best; + } + return best; } function getFirstUserFrame(): StackFrame | null { - const err = new Error(); - if (!err.stack) return null; + const err = new Error(); + if (!err.stack) return null; - const lines = err.stack.split('\n').slice(1); - for (const raw of lines) { - const frame = parseStackLine(raw); - if (!frame) continue; + const lines = err.stack.split('\n').slice(1); + for (const raw of lines) { + const frame = parseStackLine(raw); + if (!frame) continue; - const file = normalizeRuntimeMapPath(frame.file); - if (isRuntimeInternalFile(file)) continue; + const file = normalizeRuntimeMapPath(frame.file); + if (isRuntimeInternalFile(file)) continue; - return { - file, - line: frame.line, - column: frame.column, - }; - } + return { + file, + line: frame.line, + column: frame.column, + }; + } - return null; + return null; } function parseStackLine(line: string): StackFrame | null { - const trimmed = line.trim(); - if (!trimmed) return null; + const trimmed = line.trim(); + if (!trimmed) return null; - let location = trimmed; - const atPrefix = 'at '; - if (location.startsWith(atPrefix)) { - location = location.slice(atPrefix.length).trim(); - } + let location = trimmed; + const atPrefix = 'at '; + if (location.startsWith(atPrefix)) { + location = location.slice(atPrefix.length).trim(); + } - const openParen = location.lastIndexOf('('); - if (openParen >= 0 && location.endsWith(')')) { - location = location.slice(openParen + 1, -1); - } + const openParen = location.lastIndexOf('('); + if (openParen >= 0 && location.endsWith(')')) { + location = location.slice(openParen + 1, -1); + } - const lastColon = location.lastIndexOf(':'); - if (lastColon < 0) return null; - const secondLastColon = location.lastIndexOf(':', lastColon - 1); - if (secondLastColon < 0) return null; + const lastColon = location.lastIndexOf(':'); + if (lastColon < 0) return null; + const secondLastColon = location.lastIndexOf(':', lastColon - 1); + if (secondLastColon < 0) return null; - const file = location.slice(0, secondLastColon); - const linePart = location.slice(secondLastColon + 1, lastColon); - const colPart = location.slice(lastColon + 1); + const file = location.slice(0, secondLastColon); + const linePart = location.slice(secondLastColon + 1, lastColon); + const colPart = location.slice(lastColon + 1); - const parsedLine = Number(linePart); - const parsedCol = Number(colPart); - if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) return null; + const parsedLine = Number(linePart); + const parsedCol = Number(colPart); + if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) return null; - return { - file, - line: parsedLine, - column: parsedCol, - }; + return { + file, + line: parsedLine, + column: parsedCol, + }; } function isRuntimeInternalFile(file: string): boolean { - return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js'); + return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js'); } function pathsLikelySame(a: string, b: string): boolean { - if (a === b) return true; - const aBase = basename(a); - const bBase = basename(b); - return aBase !== '' && aBase === bBase; + if (a === b) return true; + const aBase = basename(a); + const bBase = basename(b); + return aBase !== '' && aBase === bBase; } function basename(file: string): string { - const normalized = normalizeRuntimeMapPath(file); - const idx = normalized.lastIndexOf('/'); - return idx >= 0 ? normalized.slice(idx + 1) : normalized; + const normalized = normalizeRuntimeMapPath(file); + const idx = normalized.lastIndexOf('/'); + return idx >= 0 ? normalized.slice(idx + 1) : normalized; } diff --git a/packages/proton/test/__tests__/cross-file.test.ts b/packages/proton/test/__tests__/cross-file.test.ts index 9f553cba..a088acbb 100644 --- a/packages/proton/test/__tests__/cross-file.test.ts +++ b/packages/proton/test/__tests__/cross-file.test.ts @@ -11,332 +11,332 @@ import { execAndGet } from '../helpers'; const crossDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures', 'cross-file'); function loadCross(name: string): { code: string; path: string } { - const path = resolve(crossDir, name); - return { code: readFileSync(path, 'utf-8'), path }; + const path = resolve(crossDir, name); + return { code: readFileSync(path, 'utf-8'), path }; } describe('cross-file import resolution', () => { - // ── Scenario A: imported type in encode/decode call site ────────── + // ── Scenario A: imported type in encode/decode call site ────────── - it('resolves imported type for protobuf_encode/decode call site', () => { - const { code, path } = loadCross('consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('resolves imported type for protobuf_encode/decode call site', () => { + const { code, path } = loadCross('consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - expect(imported.concrete.some(m => m.name === 'UserMsg')).toBe(true); + expect(imported.concrete.some(m => m.name === 'UserMsg')).toBe(true); - const { registry, callSites, sourceFile } = analyze(code, path, imported); - expect(registry.has('UserMsg')).toBe(true); + const { registry, callSites, sourceFile } = analyze(code, path, imported); + expect(registry.has('UserMsg')).toBe(true); - const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry); - expect(hasReplacements).toBe(true); - expect(transformedCode).toContain('protobuf_encode_UserMsg'); - expect(transformedCode).toContain('protobuf_decode_UserMsg'); - }); + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_UserMsg'); + expect(transformedCode).toContain('protobuf_decode_UserMsg'); + }); - it('Scenario A round-trip', () => { - const { code, path } = loadCross('consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); + it('Scenario A round-trip', () => { + const { code, path } = loadCross('consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(gen + `\n const enc = protobuf_encode_UserMsg({ id: 42, name: 'alice' }); globalThis.__r = protobuf_decode_UserMsg(enc); `, '__r'); - expect(result.id).toBe(42); - expect(result.name).toBe('alice'); - }); + expect(result.id).toBe(42); + expect(result.name).toBe('alice'); + }); - // ── Scenario B: imported type as pb<> field ────────────────────── + // ── Scenario B: imported type as pb<> field ────────────────────── - it('resolves imported nested message type', () => { - const { code, path } = loadCross('outer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('resolves imported nested message type', () => { + const { code, path } = loadCross('outer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - expect(imported.concrete.some(m => m.name === 'Inner')).toBe(true); + expect(imported.concrete.some(m => m.name === 'Inner')).toBe(true); - const registry = analyzeSource(code, path, imported); - expect(registry.has('Inner')).toBe(true); - expect(registry.has('Outer')).toBe(true); + const registry = analyzeSource(code, path, imported); + expect(registry.has('Inner')).toBe(true); + expect(registry.has('Outer')).toBe(true); - const outer = registry.get('Outer')!; - const innerField = outer.fields.find(f => f.name === 'inner')!; - expect(innerField.isMessage).toBe(true); - }); + const outer = registry.get('Outer')!; + const innerField = outer.fields.find(f => f.name === 'inner')!; + expect(innerField.isMessage).toBe(true); + }); - it('Scenario B round-trip', () => { - const { code, path } = loadCross('outer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); + it('Scenario B round-trip', () => { + const { code, path } = loadCross('outer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(gen + `\n const enc = protobuf_encode_Outer({ inner: { value: 42 } }); globalThis.__r = protobuf_decode_Outer(enc); `, '__r'); - expect(result.inner.value).toBe(42); - }); + expect(result.inner.value).toBe(42); + }); - // ── Generic template import ────────────────────────────────────── + // ── Generic template import ────────────────────────────────────── - it('resolves imported generic template', () => { - const { code, path } = loadCross('generic-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('resolves imported generic template', () => { + const { code, path } = loadCross('generic-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - expect(imported.templates.has('Wrapper')).toBe(true); + expect(imported.templates.has('Wrapper')).toBe(true); - const registry = analyzeSource(code, path, imported); - expect(registry.has('Wrapper__string')).toBe(true); - }); + const registry = analyzeSource(code, path, imported); + expect(registry.has('Wrapper__string')).toBe(true); + }); - it('generic import round-trip', () => { - const { code, path } = loadCross('generic-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); + it('generic import round-trip', () => { + const { code, path } = loadCross('generic-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(gen + `\n const enc = protobuf_encode_Wrapper__string({ value: 'hello' }); globalThis.__r = protobuf_decode_Wrapper__string(enc); `, '__r'); - expect(result.value).toBe('hello'); - }); + expect(result.value).toBe('hello'); + }); - it('resolves generic type passed through imported wrapper functions', () => { - const { code, path } = loadCross('wrapper-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('resolves generic type passed through imported wrapper functions', () => { + const { code, path } = loadCross('wrapper-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - expect(imported.templates.has('Wrapper')).toBe(true); + expect(imported.templates.has('Wrapper')).toBe(true); - const { registry, callSites, sourceFile } = analyze(code, path, imported); - const used = selectUsedRegistry(registry, callSites, sourceFile); + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); - expect(used.registry.has('Wrapper__string')).toBe(true); - expect(used.callSites).toHaveLength(2); - expect(used.callSites[0].fnName).toBe('protobuf_encode'); - expect(used.callSites[1].fnName).toBe('protobuf_decode'); + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(2); + expect(used.callSites[0].fnName).toBe('protobuf_encode'); + expect(used.callSites[1].fnName).toBe('protobuf_decode'); - const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); - expect(hasReplacements).toBe(true); - expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); - expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); - }); + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + }); - it('handles wrapper aliases, arrows, nested generics, and non-first generic forwarding', () => { - const { code, path } = loadCross('wrapper-edge-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('handles wrapper aliases, arrows, nested generics, and non-first generic forwarding', () => { + const { code, path } = loadCross('wrapper-edge-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - const { registry, callSites, sourceFile } = analyze(code, path, imported); - const used = selectUsedRegistry(registry, callSites, sourceFile); + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); - expect(used.registry.has('Wrapper__string')).toBe(true); - expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); - expect(used.callSites).toHaveLength(5); + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(5); - const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); - expect(hasReplacements).toBe(true); - expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); - expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); - expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); - expect(transformedCode).toContain('protobuf_decode_Wrapper__Wrapper__string('); - expect(transformedCode).toContain('passthroughOnly>'); - }); + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__Wrapper__string('); + expect(transformedCode).toContain('passthroughOnly>'); + }); - it('handles local wrapper functions in the entry file', () => { - const { code, path } = loadCross('local-wrapper-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('handles local wrapper functions in the entry file', () => { + const { code, path } = loadCross('local-wrapper-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - const { registry, callSites, sourceFile } = analyze(code, path, imported); - const used = selectUsedRegistry(registry, callSites, sourceFile); + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); - expect(used.registry.has('Wrapper__string')).toBe(true); - expect(used.callSites).toHaveLength(2); + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(2); - const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); - expect(hasReplacements).toBe(true); - expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); - expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); - }); + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + }); - it('handles complex wrapper objects, branches, nested helpers, and chains', () => { - const { code, path } = loadCross('wrapper-complex-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('handles complex wrapper objects, branches, nested helpers, and chains', () => { + const { code, path } = loadCross('wrapper-complex-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - const { registry, callSites, sourceFile } = analyze(code, path, imported); - const used = selectUsedRegistry(registry, callSites, sourceFile); + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); - expect(used.registry.has('Wrapper__string')).toBe(true); - expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); - expect(used.callSites).toHaveLength(7); + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(7); - const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); - expect(hasReplacements).toBe(true); - expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); - expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); - expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); - expect(transformedCode).not.toContain('encodeChained>'); - }); + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); + expect(transformedCode).not.toContain('encodeChained>'); + }); - it('handles wrapper protobuf type derived from another generic type', () => { - const { code, path } = loadCross('wrapper-type-source-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('handles wrapper protobuf type derived from another generic type', () => { + const { code, path } = loadCross('wrapper-type-source-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - const { registry, callSites, sourceFile } = analyze(code, path, imported); - const used = selectUsedRegistry(registry, callSites, sourceFile); + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); - expect(used.registry.has('Wrapper__string')).toBe(true); - expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); - expect(used.callSites).toHaveLength(5); + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(5); - const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); - expect(hasReplacements).toBe(true); - expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); - expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); - expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); - expect(transformedCode).not.toContain('encodeBoxed'); - }); + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); + expect(transformedCode).not.toContain('encodeBoxed'); + }); - // ── Transitive imports ─────────────────────────────────────────── + // ── Transitive imports ─────────────────────────────────────────── - it('resolves transitive imports (A → B → C)', () => { - const { code, path } = loadCross('top.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('resolves transitive imports (A → B → C)', () => { + const { code, path } = loadCross('top.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - expect(imported.concrete.some(m => m.name === 'Mid')).toBe(true); - expect(imported.concrete.some(m => m.name === 'Deep')).toBe(true); + expect(imported.concrete.some(m => m.name === 'Mid')).toBe(true); + expect(imported.concrete.some(m => m.name === 'Deep')).toBe(true); - const registry = analyzeSource(code, path, imported); - expect(registry.has('Top')).toBe(true); - expect(registry.has('Mid')).toBe(true); - expect(registry.has('Deep')).toBe(true); - }); + const registry = analyzeSource(code, path, imported); + expect(registry.has('Top')).toBe(true); + expect(registry.has('Mid')).toBe(true); + expect(registry.has('Deep')).toBe(true); + }); - it('transitive import round-trip', () => { - const { code, path } = loadCross('top.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); + it('transitive import round-trip', () => { + const { code, path } = loadCross('top.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(gen + `\n const enc = protobuf_encode_Top({ nested: { inner: { val: 99 } } }); globalThis.__r = protobuf_decode_Top(enc); `, '__r'); - expect(result.nested.inner.val).toBe(99); - }); + expect(result.nested.inner.val).toBe(99); + }); - // ── Cache behavior ─────────────────────────────────────────────── + // ── Cache behavior ─────────────────────────────────────────────── - it('uses cache on repeated resolves', () => { - const { code, path } = loadCross('consumer.ts'); - const cache = new Map(); + it('uses cache on repeated resolves', () => { + const { code, path } = loadCross('consumer.ts'); + const cache = new Map(); - resolveImports(code, path, cache); - expect(cache.size).toBeGreaterThan(0); + resolveImports(code, path, cache); + expect(cache.size).toBeGreaterThan(0); - const cached = new Map(cache); - resolveImports(code, path, cache); + const cached = new Map(cache); + resolveImports(code, path, cache); - // Same entries, not re-created - for (const [key, val] of cache) { - expect(val).toBe(cached.get(key)); - } - }); + // Same entries, not re-created + for (const [key, val] of cache) { + expect(val).toBe(cached.get(key)); + } + }); - // ── Graceful fallback ──────────────────────────────────────────── + // ── Graceful fallback ──────────────────────────────────────────── - it('handles missing import file gracefully', () => { - const code = `import type { Ghost } from './nonexistent';\nconst x = 1;`; - const fakePath = resolve(crossDir, 'fake.ts'); - const cache = new Map(); + it('handles missing import file gracefully', () => { + const code = `import type { Ghost } from './nonexistent';\nconst x = 1;`; + const fakePath = resolve(crossDir, 'fake.ts'); + const cache = new Map(); - const imported = resolveImports(code, fakePath, cache); - expect(imported.concrete).toEqual([]); - expect(imported.templates.size).toBe(0); - }); + const imported = resolveImports(code, fakePath, cache); + expect(imported.concrete).toEqual([]); + expect(imported.templates.size).toBe(0); + }); - it('only resolves imports reachable from protobuf call roots', () => { - const code = ` + it('only resolves imports reachable from protobuf call roots', () => { + const code = ` import { protobuf_encode } from '@snowluma/proton'; import type { UserMsg } from './types'; import type { Inner } from './inner'; const buf = protobuf_encode({ id: 42, name: 'alice' }); `; - const fakePath = resolve(crossDir, 'on-demand.ts'); - const cache = new Map(); + const fakePath = resolve(crossDir, 'on-demand.ts'); + const cache = new Map(); - const imported = resolveImports(code, fakePath, cache); + const imported = resolveImports(code, fakePath, cache); - expect(imported.concrete.map(m => m.name)).toEqual(['UserMsg']); - expect(cache.has(resolve(crossDir, 'types.ts'))).toBe(true); - expect(cache.has(resolve(crossDir, 'inner.ts'))).toBe(false); - }); + expect(imported.concrete.map(m => m.name)).toEqual(['UserMsg']); + expect(cache.has(resolve(crossDir, 'types.ts'))).toBe(true); + expect(cache.has(resolve(crossDir, 'inner.ts'))).toBe(false); + }); - // ── Value import (non-type import) ─────────────────────────────── + // ── Value import (non-type import) ─────────────────────────────── - it('resolves value import { SimpleMessage } (not import type)', () => { - const { code, path } = loadCross('value-import-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('resolves value import { SimpleMessage } (not import type)', () => { + const { code, path } = loadCross('value-import-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - expect(imported.concrete.some(m => m.name === 'SimpleMessage')).toBe(true); + expect(imported.concrete.some(m => m.name === 'SimpleMessage')).toBe(true); - const { registry, callSites, sourceFile } = analyze(code, path, imported); - expect(registry.has('SimpleMessage')).toBe(true); - expect(callSites.length).toBe(2); + const { registry, callSites, sourceFile } = analyze(code, path, imported); + expect(registry.has('SimpleMessage')).toBe(true); + expect(callSites.length).toBe(2); - const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry); - expect(hasReplacements).toBe(true); - expect(transformedCode).toContain('protobuf_encode_SimpleMessage('); - expect(transformedCode).toContain('protobuf_decode_SimpleMessage('); - }); + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_SimpleMessage('); + expect(transformedCode).toContain('protobuf_decode_SimpleMessage('); + }); - it('value import round-trip', () => { - const { code, path } = loadCross('value-import-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); + it('value import round-trip', () => { + const { code, path } = loadCross('value-import-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(gen + `\n const enc = protobuf_encode_SimpleMessage({ id: 42 }); globalThis.__r = protobuf_decode_SimpleMessage(enc); `, '__r'); - expect(result.id).toBe(42); - }); + expect(result.id).toBe(42); + }); - it('canonicalizes imported type aliases to the original message name', () => { - const { code, path } = loadCross('aliased-consumer.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('canonicalizes imported type aliases to the original message name', () => { + const { code, path } = loadCross('aliased-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); - const { registry, callSites, sourceFile } = analyze(code, path, imported); - const used = selectUsedRegistry(registry, callSites, sourceFile); + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); - expect(used.registry.has('UserMsg')).toBe(true); - expect(used.registry.has('AliasMsg')).toBe(false); - expect(used.callSites).toHaveLength(2); - expect(used.callSites[0].typeName).toBe('UserMsg'); - expect(used.callSites[1].typeName).toBe('UserMsg'); + expect(used.registry.has('UserMsg')).toBe(true); + expect(used.registry.has('AliasMsg')).toBe(false); + expect(used.callSites).toHaveLength(2); + expect(used.callSites[0].typeName).toBe('UserMsg'); + expect(used.callSites[1].typeName).toBe('UserMsg'); - const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); - expect(hasReplacements).toBe(true); - expect(transformedCode).toContain('protobuf_encode_UserMsg('); - expect(transformedCode).toContain('protobuf_decode_UserMsg('); - expect(transformedCode).not.toContain('protobuf_encode_AliasMsg('); - expect(transformedCode).not.toContain('protobuf_decode_AliasMsg('); - }); + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_UserMsg('); + expect(transformedCode).toContain('protobuf_decode_UserMsg('); + expect(transformedCode).not.toContain('protobuf_encode_AliasMsg('); + expect(transformedCode).not.toContain('protobuf_decode_AliasMsg('); + }); }); diff --git a/packages/proton/test/__tests__/cross-package.test.ts b/packages/proton/test/__tests__/cross-package.test.ts new file mode 100644 index 00000000..854bb176 --- /dev/null +++ b/packages/proton/test/__tests__/cross-package.test.ts @@ -0,0 +1,176 @@ +// Cross-package bare-specifier resolution. +// +// Companion to `cross-file.test.ts` — that suite covers relative-path +// imports between sibling files in the same package. Here we exercise +// the OTHER branch of `resolveModulePath`: a TypeScript-driven module +// resolution path that handles bare specifiers (`@scope/pkg`, +// `pkg-name`, …) so monorepo workspaces / npm packages can host proto +// definitions used from a different package. +// +// The motivating use case is decoupling `bridge/proto/proton/*.ts` +// from `@snowluma/core` into a standalone `@snowluma/proto-defs` +// package, so SnowLumaExtended (and any other consumer) can reuse the +// same wire definitions without copy-pasting them. +// +// The fixture is built in `os.tmpdir()` per-test-suite rather than +// committed to `test/fixtures/`. The reason: the resolution lookup +// has to find a real `node_modules/@fake/proto-defs/...` layout, and +// the repo-level `.gitignore` rule `**/node_modules/` would clobber a +// committed copy of that layout. A scratch tmpdir sidesteps the issue +// entirely and self-cleans in `afterAll`. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs'; +import { join, resolve } from 'path'; +import { tmpdir } from 'os'; +import { analyze, analyzeSource } from '../../src/ast/analyzer'; +import { generateCode } from '../../src/codegen/generator'; +import { applyReplacements } from '../../src/transform/replacer'; +import { resolveImports, type ParsedFileEntry } from '../../src/ast/import-resolver'; +import { execAndGet } from '../helpers'; + +describe('cross-package import resolution (bare specifier)', () => { + let tmpRoot: string; + let consumerPath: string; + + beforeAll(() => { + // Build a tiny fake monorepo layout: + // + // / + // consumer.ts ← uses `import { RemoteMsg } from '@fake/proto-defs'` + // node_modules/ + // @fake/ + // proto-defs/ + // package.json ← exports → ./src/index.ts + // src/ + // index.ts ← exported interfaces + // + // Bundler-mode `ts.resolveModuleName` walks importer → parent + // dirs looking for `node_modules`, so placing the consumer at + // `/consumer.ts` lets `/node_modules/...` satisfy the + // lookup. + tmpRoot = mkdtempSync(join(tmpdir(), 'proton-cross-pkg-')); + + const pkgDir = resolve(tmpRoot, 'node_modules', '@fake', 'proto-defs'); + mkdirSync(resolve(pkgDir, 'src'), { recursive: true }); + + // `exports."."` must point at a `.ts` source file — proton walks + // interface AST nodes to collect `pb<…>` field tags, and a + // generated `.d.ts` typically strips those generic args. Telling + // consumers to ship source `.ts` is the same model + // `@snowluma/proton` itself uses (`"default": "./src/runtime.ts"`). + writeFileSync( + resolve(pkgDir, 'package.json'), + JSON.stringify({ + name: '@fake/proto-defs', + version: '1.0.0', + type: 'module', + main: './src/index.ts', + types: './src/index.ts', + exports: { + '.': { + types: './src/index.ts', + default: './src/index.ts', + }, + }, + }, null, 2), + ); + + writeFileSync( + resolve(pkgDir, 'src', 'index.ts'), + // proton's `collectInterface` recognises `pb` as a marker + // type by NAME — no actual import of `@snowluma/proton` is + // needed for the fixture to parse. Matches the existing + // cross-file fixtures (`fixtures/cross-file/types.ts` does the + // same). + 'export interface RemoteMsg {\n' + + ' id?: pb<1, uint_32>;\n' + + ' name?: pb<2, string>;\n' + + '}\n', + ); + + consumerPath = resolve(tmpRoot, 'consumer.ts'); + writeFileSync( + consumerPath, + 'import type { RemoteMsg } from \'@fake/proto-defs\';\n' + + '\n' + + 'const buf = protobuf_encode({ id: 42, name: \'alice\' });\n' + + 'const decoded = protobuf_decode(buf);\n' + + '\n' + + 'export { buf, decoded };\n', + ); + }); + + afterAll(() => { + if (tmpRoot) rmSync(tmpRoot, { recursive: true, force: true }); + }); + + it('collects interfaces from a `@fake/proto-defs` bare-specifier import', () => { + // Smoke test: the import resolver MUST find the package and pick + // up `RemoteMsg`. If this fails, `ts.resolveModuleName` likely + // can't find the fake node_modules layout (check that the + // BARE_SPECIFIER_COMPILER_OPTIONS in import-resolver.ts still + // sets `moduleResolution: Bundler`). + const code = readFileSync(consumerPath, 'utf-8'); + const cache = new Map(); + const imported = resolveImports(code, consumerPath, cache); + + expect(imported.concrete.some(m => m.name === 'RemoteMsg')).toBe(true); + }); + + it('rewrites encode/decode call sites against the imported type', () => { + const code = readFileSync(consumerPath, 'utf-8'); + const cache = new Map(); + const imported = resolveImports(code, consumerPath, cache); + + const { registry, callSites, sourceFile } = analyze(code, consumerPath, imported); + expect(registry.has('RemoteMsg')).toBe(true); + + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_RemoteMsg'); + expect(transformedCode).toContain('protobuf_decode_RemoteMsg'); + }); + + it('round-trips encode/decode of a bare-specifier-imported message', () => { + // End-to-end: parse → analyze → generate codec → encode → + // decode → assert payload survived. The same shape as + // cross-file.test.ts's "Scenario A round-trip", but with the + // type sourced from a separate package. + const code = readFileSync(consumerPath, 'utf-8'); + const cache = new Map(); + const imported = resolveImports(code, consumerPath, cache); + const registry = analyzeSource(code, consumerPath, imported); + const gen = generateCode(registry); + + const result = execAndGet<{ id: number; name: string }>( + gen + '\n' + + 'const enc = protobuf_encode_RemoteMsg({ id: 42, name: \'alice\' });\n' + + 'globalThis.__r = protobuf_decode_RemoteMsg(enc);\n', + '__r', + ); + expect(result.id).toBe(42); + expect(result.name).toBe('alice'); + }); + + it('returns null for an unresolvable bare specifier (does not throw)', () => { + // Pre-existing relative-path behavior: missing files return + // null, never throw. The bare-specifier branch must match that + // — otherwise a typo in a package name turns into a build crash + // rather than a silent "no codec emitted" warning further down + // the pipeline. + const orphanPath = resolve(tmpRoot, 'orphan.ts'); + writeFileSync( + orphanPath, + 'import type { Whatever } from \'@does-not-exist/nope\';\n' + + 'export type _ = Whatever;\n', + ); + const code = readFileSync(orphanPath, 'utf-8'); + const cache = new Map(); + // resolveImports swallows resolution failures by design — it + // simply produces an empty `concrete` for the unresolvable + // import. The assertion is that we got here without an exception. + const imported = resolveImports(code, orphanPath, cache); + expect(imported.concrete).toEqual([]); + }); +}); diff --git a/packages/proton/test/__tests__/generator.test.ts b/packages/proton/test/__tests__/generator.test.ts index cc1bbae5..31c543be 100644 --- a/packages/proton/test/__tests__/generator.test.ts +++ b/packages/proton/test/__tests__/generator.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest'; import { analyzeSource } from '../../src/ast/analyzer'; import { generateCode } from '../../src/codegen/generator'; -import { loadFixture, execAndGet } from '../helpers'; +import { loadFixture } from '../helpers'; /** Analyze fixture → generate → eval → return encode/decode pair */ function makeRoundTrip(fixtureName: string, msgName: string) { diff --git a/packages/proton/test/helpers/index.ts b/packages/proton/test/helpers/index.ts index 9ac63567..03ad4535 100644 --- a/packages/proton/test/helpers/index.ts +++ b/packages/proton/test/helpers/index.ts @@ -6,7 +6,7 @@ const fixturesDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixt /** Load a fixture file as a string. */ export function loadFixture(name: string): string { - return readFileSync(resolve(fixturesDir, name), 'utf-8'); + return readFileSync(resolve(fixturesDir, name), 'utf-8'); } /** @@ -14,8 +14,8 @@ export function loadFixture(name: string): string { * Cleans up the global after retrieval. */ export function execAndGet(code: string, globalKey: string): T { - new Function(code)(); - const val = (globalThis as any)[globalKey] as T; - delete (globalThis as any)[globalKey]; - return val; + new Function(code)(); + const val = (globalThis as any)[globalKey] as T; + delete (globalThis as any)[globalKey]; + return val; } diff --git a/packages/runtime/native/better-sqlite3-v127-darwin-arm64.node b/packages/runtime/native/better-sqlite3-v127-darwin-arm64.node new file mode 100644 index 00000000..f43da9ce Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-darwin-arm64.node differ diff --git a/packages/runtime/native/better-sqlite3-v127-darwin-x64.node b/packages/runtime/native/better-sqlite3-v127-darwin-x64.node new file mode 100644 index 00000000..c4df275b Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-darwin-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v127-linux-arm64.node b/packages/runtime/native/better-sqlite3-v127-linux-arm64.node new file mode 100644 index 00000000..b6e59662 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-linux-arm64.node differ diff --git a/packages/runtime/native/better-sqlite3-v127-linux-x64.node b/packages/runtime/native/better-sqlite3-v127-linux-x64.node new file mode 100644 index 00000000..dfc2a4a8 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-linux-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v127-win32-x64.node b/packages/runtime/native/better-sqlite3-v127-win32-x64.node new file mode 100644 index 00000000..b54d6060 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-win32-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-darwin-arm64.node b/packages/runtime/native/better-sqlite3-v137-darwin-arm64.node new file mode 100644 index 00000000..b192e495 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-darwin-arm64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-darwin-x64.node b/packages/runtime/native/better-sqlite3-v137-darwin-x64.node new file mode 100644 index 00000000..c189de35 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-darwin-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-linux-arm64.node b/packages/runtime/native/better-sqlite3-v137-linux-arm64.node new file mode 100644 index 00000000..ecc84e9b Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-linux-arm64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-linux-x64.node b/packages/runtime/native/better-sqlite3-v137-linux-x64.node new file mode 100644 index 00000000..d475c3f6 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-linux-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-win32-x64.node b/packages/runtime/native/better-sqlite3-v137-win32-x64.node new file mode 100644 index 00000000..2f872f81 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-win32-x64.node differ diff --git a/packages/runtime/native/snowluma-linux-arm64.node b/packages/runtime/native/snowluma-linux-arm64.node old mode 100755 new mode 100644 index fc12c0e3..a1e7b79a Binary files a/packages/runtime/native/snowluma-linux-arm64.node and b/packages/runtime/native/snowluma-linux-arm64.node differ diff --git a/packages/runtime/native/snowluma-linux-arm64.so b/packages/runtime/native/snowluma-linux-arm64.so old mode 100755 new mode 100644 index af86c267..ead226eb Binary files a/packages/runtime/native/snowluma-linux-arm64.so and b/packages/runtime/native/snowluma-linux-arm64.so differ diff --git a/packages/runtime/native/snowluma-win32-x64.dll b/packages/runtime/native/snowluma-win32-x64.dll index 2b92acfc..94660cc6 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.dll and b/packages/runtime/native/snowluma-win32-x64.dll differ diff --git a/packages/runtime/native/snowluma-win32-x64.node b/packages/runtime/native/snowluma-win32-x64.node index 088b0bc7..7f2b3a30 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.node and b/packages/runtime/native/snowluma-win32-x64.node differ diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 3e30cb7a..185a5bda 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,8 +1,8 @@ { "name": "@snowluma/runtime", - "version": "1.9.0", + "version": "1.9.1", "private": true, "type": "module", "main": "index.mjs", - "description": "SnowLuma runtime distribution manifest: ships into dist/ (launcher.bat, package.json, native/*.dll, native/*.node). Native libraries are loaded via process.dlopen()." + "description": "SnowLuma runtime distribution manifest: ships into dist/ (launcher.bat, package.json, native/*.dll, native/*.node). All native bindings ship as standalone `.node` files in `dist/native/` — loaded via `process.dlopen()` / `createRequire().require()` from inside the bundle. There are intentionally NO runtime npm dependencies; production artifacts are self-contained." } diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 50475569..d6c4ae54 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.0", + "version": "1.9.1", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/sdk/src/actions.ts b/packages/sdk/src/actions.ts deleted file mode 100644 index f3782ca7..00000000 --- a/packages/sdk/src/actions.ts +++ /dev/null @@ -1,151 +0,0 @@ -import type { SnowLumaActionMap } from './types/index'; - -export const SNOWLUMA_ACTIONS = [ - 'get_login_info', - 'get_status', - 'get_version_info', - 'can_send_image', - 'can_send_record', - 'send_msg', - 'send_private_msg', - 'send_group_msg', - 'get_msg', - 'delete_msg', - 'get_friend_list', - 'get_stranger_info', - 'delete_friend', - 'get_group_list', - 'get_group_info', - 'get_group_member_list', - 'get_group_member_info', - 'get_group_honor_info', - 'get_group_system_msg', - 'set_group_kick', - 'set_group_kick_members', - 'set_group_ban', - 'set_group_whole_ban', - 'set_group_add_option', - 'set_group_search', - 'set_group_admin', - 'set_group_card', - 'set_group_name', - 'set_group_leave', - 'set_group_special_title', - 'set_group_anonymous', - 'set_group_anonymous_ban', - 'set_group_portrait', - 'upload_group_file', - 'upload_private_file', - 'get_group_file_url', - 'get_group_root_files', - 'get_group_files_by_folder', - 'delete_group_file', - 'move_group_file', - 'create_group_file_folder', - 'delete_group_file_folder', - 'rename_group_file_folder', - 'get_private_file_url', - 'set_friend_add_request', - 'set_group_add_request', - 'send_like', - 'friend_poke', - 'group_poke', - 'send_poke', - 'set_essence_msg', - 'delete_essence_msg', - 'get_essence_msg_list', - 'set_group_reaction', - 'get_group_msg_history', - 'get_friend_msg_history', - 'mark_group_msg_as_read', - 'mark_private_msg_as_read', - 'mark_msg_as_read', - 'get_rkey', - 'ocr_image', - '.ocr_image', - '_send_group_notice', - '_get_group_notice', - '_del_group_notice', - 'upload_forward_msg', - 'upload_foward_msg', - 'send_forward_msg', - 'send_group_forward_msg', - 'send_private_forward_msg', - 'get_forward_msg', - 'get_image', - 'get_record', - 'get_cookies', - 'get_csrf_token', - 'get_credentials', - 'set_restart', - 'clean_cache', - '.handle_quick_operation', - 'set_friend_remark', - 'set_group_remark', - 'set_msg_emoji_like', - '_mark_all_as_read', - 'get_group_file_system_info', - 'check_url_safely', - 'download_file', - 'set_qq_profile', - 'set_online_status', - 'get_group_ignored_notifies', - 'get_group_shut_list', - 'forward_friend_single_msg', - 'forward_group_single_msg', - 'get_recent_contact', - 'get_profile_like', - 'fetch_custom_face', - 'get_emoji_likes', - 'fetch_emoji_like', - 'get_friends_with_category', - 'get_online_clients', - '_get_model_show', - '_set_model_show', - '.get_word_slices', - 'get_group_at_all_remain', - 'get_unidirectional_friend_list', - 'set_self_longnick', - 'get_collection_list', - 'create_collection', - 'set_qq_avatar', - 'set_input_status', - 'translate_en2zh', - 'get_clientkey', - 'get_mini_app_ark', - 'click_inline_keyboard_button', - 'set_group_sign', - 'send_group_sign', - 'get_group_info_ex', - 'get_group_detail_info', - 'trans_group_file', - 'rename_group_file', - 'get_file', - '.send_packet', - - // napcat-parity extensions (Tier 1 + Tier 2) - 'send_packet', - 'bot_exit', - 'nc_get_packet_status', - 'nc_get_rkey', - 'nc_get_user_status', - 'get_group_ignore_add_request', - 'delete_group_folder', - 'set_group_todo', - 'complete_group_todo', - 'cancel_group_todo', - // Tier 3: DIY status - 'set_diy_online_status', - // AI voice trio - 'get_ai_characters', - 'get_ai_record', - 'send_group_ai_record', -] as const satisfies readonly (keyof SnowLumaActionMap)[]; - -export type SnowLumaKnownAction = typeof SNOWLUMA_ACTIONS[number]; - -const ACTION_SET = new Set(SNOWLUMA_ACTIONS); - -export function isSnowLumaAction(action: string): action is SnowLumaKnownAction { - return ACTION_SET.has(action); -} diff --git a/packages/sdk/src/client/api-client.ts b/packages/sdk/src/client/api-client.ts index a05d5128..9dc6dd38 100644 --- a/packages/sdk/src/client/api-client.ts +++ b/packages/sdk/src/client/api-client.ts @@ -15,7 +15,6 @@ import type { JsonObject, JsonValue, OutgoingMessage, - PrivateForwardMessageParams, RequestOptions, SendMsgParams, SetGroupReactionParams, diff --git a/packages/sdk/src/events/context.ts b/packages/sdk/src/events/context.ts index a34d8817..3f4457ae 100644 --- a/packages/sdk/src/events/context.ts +++ b/packages/sdk/src/events/context.ts @@ -3,7 +3,7 @@ import type { SnowLumaEvent } from '../types/index'; import { isGroupMessageEvent, isPrivateMessageEvent, isRequestEvent } from './guards'; import type { SnowLumaEventContext } from './types'; -/** Creates the helper context object used by WebSocket event handlers. */ + export function createEventContext( event: TEvent, client: SnowLumaApiClient, diff --git a/packages/sdk/src/events/types.ts b/packages/sdk/src/events/types.ts index e8cd8eee..58700faa 100644 --- a/packages/sdk/src/events/types.ts +++ b/packages/sdk/src/events/types.ts @@ -10,53 +10,46 @@ import type { export type MaybePromise = T | Promise; export type EventNext = () => Promise; -/** Type guard or predicate used by client.when(). */ + export type EventPredicate = (event: SnowLumaEvent) => event is TEvent; -/** Handler for one narrowed SnowLuma event. */ + export type EventHandler = ( event: TEvent, context: SnowLumaEventContext, ) => MaybePromise; -/** Middleware in the WebSocket event dispatch pipeline. */ + export type EventMiddleware = ( event: SnowLumaEvent, context: SnowLumaEventContext, next: EventNext, ) => MaybePromise; -/** Options for accepting or rejecting OneBot request events. */ + export interface RequestDecisionOptions extends RequestOptions { reason?: string; subType?: string; } -/** Convenience context passed to event middleware and handlers. */ + export interface SnowLumaEventContext { readonly event: TEvent; readonly client: SnowLumaApiClient; readonly stopped: boolean; - /** Prevents subsequent middleware and final onEvent listeners from running. */ stopPropagation(): void; - /** Replies to private or group message events with the correct API. */ reply(message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise; - /** Approves a friend or group request event. */ approve(options?: RequestDecisionOptions): Promise; - /** Rejects a friend or group request event. */ reject(reason?: string, options?: RequestDecisionOptions): Promise; - /** Sends OneBot .handle_quick_operation with the current event as context. */ quickOperation(operation: JsonObject, options?: RequestOptions): Promise; } -/** Command matching options for WebSocketClient.command(). */ export interface CommandOptions { prefixes?: string | string[]; trim?: boolean; caseSensitive?: boolean; } -/** Parsed command information passed to command handlers. */ export interface CommandMatch { command: string; text: string; diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index 347af598..ba515723 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -1,20 +1,32 @@ -export { SNOWLUMA_ACTIONS, isSnowLumaAction } from './actions'; export { SnowLumaApiClient } from './client/api-client'; -export { SnowLumaHttpClient, createHttpClient } from './client/http-client'; -export { SnowLumaWebSocketClient, createWebSocketClient } from './client/websocket-client'; +export { createHttpClient, SnowLumaHttpClient } from './client/http-client'; +export type { + SnowLumaHttpClientOptions +} from './client/http-client'; +export { createWebSocketClient, SnowLumaWebSocketClient } from './client/websocket-client'; export { - SnowLumaAbortError, + createSnowLumaApiError, SnowLumaAbortError, SnowLumaApiError, SnowLumaAuthError, SnowLumaConnectionError, SnowLumaError, SnowLumaParseError, SnowLumaTimeoutError, - SnowLumaTransportError, - createSnowLumaApiError, + SnowLumaTransportError } from './errors'; export { - MessageChain, + createEventContext, + isGroupMessageEvent, + isMessageEvent, + isMetaEvent, + isNoticeEvent, + isPrivateMessageEvent, + isRequestEvent, + matchCommand, + noticeType, + requestType +} from './events/index'; +export { at, atAll, br, @@ -23,12 +35,10 @@ export { escapeCqParam, escapeCqText, face, - forward, - image, + forward, fromCQString, image, json, location, - message, - music, + message, MessageChain, music, node, normalizeMessage, parseSegments, @@ -40,36 +50,15 @@ export { text, toCQString, video, - xml, - fromCQString, + xml } from './messages/index'; -export { - createEventContext, - isGroupMessageEvent, - isMessageEvent, - isMetaEvent, - isNoticeEvent, - isPrivateMessageEvent, - isRequestEvent, - matchCommand, - noticeType, - requestType, -} from './events/index'; - -export type { - SnowLumaKnownAction, -} from './actions'; - -export type { - SnowLumaHttpClientOptions, -} from './client/http-client'; export type { ReconnectOptions, SnowLumaWebSocketClientOptions, SnowLumaWebSocketEvents, WebSocketCloseInfo, - WebSocketConstructor, + WebSocketConstructor } from './client/websocket-client'; export type { @@ -82,7 +71,8 @@ export type { EventPredicate, MaybePromise, RequestDecisionOptions, - SnowLumaEventContext, + SnowLumaEventContext } from './events/index'; export type * from './types/index'; + diff --git a/packages/sdk/src/messages/chain.ts b/packages/sdk/src/messages/chain.ts index 46600a3b..6df4f8d6 100644 --- a/packages/sdk/src/messages/chain.ts +++ b/packages/sdk/src/messages/chain.ts @@ -1,5 +1,3 @@ -import { segments } from './segments'; -import { segmentsToCQString } from './cq-format'; import type { AnyMessageSegment, ContactSegment, @@ -7,7 +5,6 @@ import type { JsonObject, LocationSegment, MessageChainLike, - MessageSegment, MusicSegment, OutgoingMessage, RecordSegment, @@ -16,6 +13,8 @@ import type { VideoSegment, XmlSegment, } from '../types/index'; +import { segmentsToCQString } from './cq-format'; +import { segments } from './segments'; export interface MessageChainSender { sendGroupMessage(groupId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise; @@ -24,40 +23,30 @@ export interface MessageChainSender { const SINGLE_USE_TYPES = new Set(['reply']); -/** - * Immutable fluent builder for OneBot message segments. - * - * The generic state tracks single-use segments such as reply(), so TypeScript - * can reject duplicate reply segments in normal chained calls. - */ export class MessageChain implements MessageChainLike { private readonly replyStateBrand?: THasReply; private constructor( private readonly items: AnyMessageSegment[] = [], private readonly used: ReadonlySet = new Set(), - ) {} + ) { } static empty(): MessageChain { return new MessageChain(); } - /** Number of segments currently in the chain. */ get length(): number { return this.items.length; } - /** True when no segment has been appended. */ get isEmpty(): boolean { return this.items.length === 0; } - /** Appends a text segment. */ text(text = ''): MessageChain { return this.addSegment(segments.text(text)); } - /** Appends a newline text segment. */ br(): MessageChain { return this.text('\n'); } @@ -66,7 +55,6 @@ export class MessageChain implements MessageC return this.addSegment(segments.face(id)); } - /** Mentions a user or everyone in a group. */ at(qq: number | 'all', options: { name?: string; uid?: string } = {}): MessageChain { return this.addSegment(segments.at(qq, options)); } @@ -75,12 +63,10 @@ export class MessageChain implements MessageC return this.at('all'); } - /** Adds a reply segment. A chain can contain at most one reply segment. */ reply(this: MessageChain, id: number | string): MessageChain { return this.addSegment(segments.reply(id), 'reply') as MessageChain; } - /** Appends an image segment from a URL, local path, file id, or base64 URI. */ image(file: string, options: Omit = {}): MessageChain { return this.addSegment(segments.image(file, options)); } @@ -133,7 +119,6 @@ export class MessageChain implements MessageC return this.addSegment(segments.raw(type, data), type); } - /** Appends another outgoing message while preserving single-use segment checks. */ append(messageInput: OutgoingMessage): MessageChain { let next: MessageChain = this; const normalized = normalizeMessage(messageInput); @@ -146,7 +131,6 @@ export class MessageChain implements MessageC return next; } - /** Returns a fresh segment array suitable for OneBot array message format. */ build(): AnyMessageSegment[] { return this.toSegments(); } @@ -167,7 +151,6 @@ export class MessageChain implements MessageC return segmentsToCQString(this.items); } - /** Sends this chain to a group through a compatible SnowLuma client. */ sendToGroup( client: MessageChainSender, groupId: number, @@ -176,7 +159,6 @@ export class MessageChain implements MessageC return client.sendGroupMessage(groupId, this, options); } - /** Sends this chain to a private chat through a compatible SnowLuma client. */ sendToPrivate( client: MessageChainSender, userId: number, @@ -213,7 +195,6 @@ export function chain(): MessageChain { return MessageChain.empty(); } -/** Starts a message chain with a text segment. */ export function text(value = ''): MessageChain { return chain().text(value); } @@ -238,7 +219,6 @@ export function reply(id: number | string): MessageChain { return chain().reply(id); } -/** Starts a message chain with an image segment. */ export function image(file: string, options: Omit = {}): MessageChain { return chain().image(file, options); } @@ -291,7 +271,6 @@ export function raw(type: TType, return chain().raw(type, data); } -/** Normalizes a string, segment, segment array, or MessageChain into OneBot output. */ export function normalizeMessage(input: OutgoingMessage): string | AnyMessageSegment[] { if (typeof input === 'string') return input; if (isMessageChainLike(input)) return input.toSegments(); diff --git a/packages/sdk/tests/actions-sync.test.ts b/packages/sdk/tests/actions-sync.test.ts index 5b31386e..41c79daf 100644 --- a/packages/sdk/tests/actions-sync.test.ts +++ b/packages/sdk/tests/actions-sync.test.ts @@ -5,7 +5,9 @@ import { SNOWLUMA_ACTIONS } from '../src'; describe('SnowLuma action list', () => { it('stays in sync with core registerAction calls', () => { - const actionsDir = fileURLToPath(new URL('../../core/src/onebot/actions/', import.meta.url)); + // Actions moved out of @snowluma/core into the dedicated + // @snowluma/onebot package in the RoadMap #3 4-way split. + const actionsDir = fileURLToPath(new URL('../../onebot/src/actions/', import.meta.url)); const registered = new Set(); for (const file of fs.readdirSync(actionsDir)) { diff --git a/packages/sqlite/package.json b/packages/sqlite/package.json new file mode 100644 index 00000000..ae72a354 --- /dev/null +++ b/packages/sqlite/package.json @@ -0,0 +1,24 @@ +{ + "name": "@snowluma/sqlite", + "version": "1.9.1", + "private": true, + "type": "module", + "description": "SnowLuma SQLite wrapper. Exposes the `better-sqlite3` Database constructor + Statement type, but loads the native `.node` binding from `dist/native/sqlite/-/` at runtime instead of going through `bindings('better_sqlite3.node')` + `node_modules/.../build/Release/`. The vendored prebuilds under `packages/runtime/native/sqlite/` get copied into the dist tree by `vite-plugin-cp` during the @snowluma/core build, mirroring how `websocket-*.node` and `ffmpegAddon.*.node` are handled. The end result: production artifacts ship as a single self-contained dist/ directory with no `dist/node_modules/` and no install step at runtime.", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@types/better-sqlite3": "^7.6.13", + "@types/node": "^24.12.2", + "better-sqlite3": "12.10.0", + "typescript": "catalog:" + } +} diff --git a/packages/sqlite/src/index.ts b/packages/sqlite/src/index.ts new file mode 100644 index 00000000..7ccfd6a2 --- /dev/null +++ b/packages/sqlite/src/index.ts @@ -0,0 +1,118 @@ +// @snowluma/sqlite — wraps better-sqlite3 so the native `.node` binding +// is loaded from +// `dist/native/better-sqlite3-v--.node` instead +// of `node_modules/better-sqlite3/build/Release/`. This lets the +// production artifact ship as a single self-contained `dist/` +// directory (no `dist/node_modules/`, no `npm install --omit=dev` +// step) — the same pattern SnowLuma already uses for its +// `websocket--.node` and `snowluma-*.{dll,node,so}` +// addons (flat dir, dash-separated triplet). +// +// How it works: +// 1. better-sqlite3's `Database` constructor accepts a `nativeBinding` +// option (string path or already-`require()`-ed object) that +// overrides the default `require('bindings')('better_sqlite3.node')` +// lookup. We forward through every other option/argument +// verbatim and inject this one. +// 2. The vendored `.node` lives at one of two locations depending +// on whether we're in dev (workspace TS source) or production +// (bundled into dist/native/): +// - Prod: `/native/better-sqlite3-v-.node` +// - Dev: `/packages/runtime/native/better-sqlite3-v-.node` +// We probe both paths and take whichever exists. +// 3. `` is `-` (e.g. +// `darwin-arm64`, `linux-x64`, `linux-arm64`, `win32-x64`). +// 4. `` is `process.versions.modules` (NODE_MODULE_VERSION). +// better-sqlite3 is NOT N-API — its binding is locked to one +// Node ABI per build. Vendoring `vNNN` in the filename lets us +// ship multiple ABIs side-by-side (e.g. v127 for Node 22 LTS +// shipped to CI, v137 for Node 24 used by some dev boxes). + +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; +import { dirname, join, resolve } from 'node:path'; +import { existsSync } from 'node:fs'; +import BetterSqlite3 from 'better-sqlite3'; + +// Re-export the public types/classes consumers need. `Database` and +// `Statement` come straight from better-sqlite3 — we only intercept +// the constructor at call time, not the class shape. +export type { Database, Statement, RunResult, Options } from 'better-sqlite3'; + +function triplet(): string { + return `${process.platform}-${process.arch}`; +} + +function abi(): string { + // `process.versions.modules` is the NODE_MODULE_VERSION the running + // Node binary expects — e.g. "127" for Node 22, "137" for Node 24. + // Stays in sync with whatever the host actually does at load time. + return `v${process.versions.modules}`; +} + +function locateBinding(): string { + const tri = triplet(); + const fileName = `better-sqlite3-${abi()}-${tri}.node`; + // Two candidate locations, tried in order: + // 1. Production: dist/native/better-sqlite3-.node + // — `import.meta.url` resolves to dist/ at runtime (the wrapper + // is bundled into index.mjs alongside it). + // 2. Dev: /packages/runtime/native/better-sqlite3-.node + // — `import.meta.url` resolves to packages/sqlite/src/index.ts; + // walk up to repo root + into runtime/native. + const here = dirname(fileURLToPath(import.meta.url)); + const distCandidate = join(here, 'native', fileName); + if (existsSync(distCandidate)) return distCandidate; + + // From packages/sqlite/src ⇢ go up to packages/, then into + // runtime/native. (Two `..` segments, not three — `src` → `sqlite/` + // → `packages/`, then descend into `runtime/native`.) + const devCandidate = resolve(here, '..', '..', 'runtime', 'native', fileName); + if (existsSync(devCandidate)) return devCandidate; + + throw new Error( + `@snowluma/sqlite: could not locate ${fileName}. ` + + `Tried:\n ${distCandidate}\n ${devCandidate}\n` + + `Run \`node tools/fetch-sqlite-prebuilts.mjs\` to vendor the missing platform binary.`, + ); +} + +// Load the native addon once at module import — keeping it module- +// scoped so the require() cost is paid exactly once per process. +let addon: unknown | null = null; +function loadAddon(): unknown { + if (addon) return addon; + const bindingPath = locateBinding(); + // better-sqlite3 expects the addon to be loaded via the CJS + // require() mechanism (N-API init runs through it). createRequire + // is the ESM-safe way to do that with an absolute path. + const req = createRequire(import.meta.url); + addon = req(bindingPath); + return addon; +} + +// Drop-in `Database` factory. Matches the better-sqlite3 default- +// export signature exactly: `new Database(filename[, options])` → +// `Database` instance. +// +// We can't just `class extends BetterSqlite3` because better-sqlite3's +// default export is a function that returns the instance (the `new +// Database(...)` shape works through that function's `new.target` +// check). Wrapping at the function-call boundary keeps that contract +// intact. +type BetterSqlite3Type = typeof BetterSqlite3; +type DatabaseInstance = InstanceType; +type DatabaseOptions = ConstructorParameters[1]; + +const Database = function Database(filename?: string | Buffer, options?: DatabaseOptions): DatabaseInstance { + const opts = { ...(options ?? {}), nativeBinding: loadAddon() } as DatabaseOptions; + // The `as any` shrug here is unavoidable — better-sqlite3's + // overload set declares `new Database(...)` returns the class type + // but its default export is a callable that *also* returns it via + // an internal `new.target == null` branch. TS can't reconcile the + // two without `as any`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return new (BetterSqlite3 as any)(filename, opts); +} as unknown as BetterSqlite3Type; + +export default Database; diff --git a/packages/sqlite/tsconfig.json b/packages/sqlite/tsconfig.json new file mode 100644 index 00000000..4cd329d7 --- /dev/null +++ b/packages/sqlite/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"], + "noEmit": true + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/packages/ui/package.json b/packages/ui/package.json index e1a310e4..0120b6ff 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.0", + "version": "1.9.1", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index 4fc99bce..3e6dcd13 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.9.0", + "version": "1.9.1", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/websocket/src/native.ts b/packages/websocket/src/native.ts index 9fabf451..0497c522 100644 --- a/packages/websocket/src/native.ts +++ b/packages/websocket/src/native.ts @@ -102,7 +102,6 @@ function createStubAddon(reason: string): NativeAddon { return fail(); } } - // eslint-disable-next-line no-console console.warn( `[snowluma/websocket] WARNING: using stub addon (${reason}). WebSocket features are disabled.`, ); diff --git a/packages/websocket/src/server.ts b/packages/websocket/src/server.ts index 99d9fd29..a6a0defa 100644 --- a/packages/websocket/src/server.ts +++ b/packages/websocket/src/server.ts @@ -24,7 +24,7 @@ function abortUpgrade(socket: Duplex, status: number, message?: string): void { 'Connection: close\r\n' + `Content-Length: ${Buffer.byteLength(body)}\r\n` + 'Content-Type: text/plain\r\n\r\n'; - socket.write(head + body); + socket.write(head + body); } catch { /* noop */ } try { socket.destroy(); } catch { /* noop */ } } diff --git a/packages/webui/eslint.config.js b/packages/webui/eslint.config.js deleted file mode 100644 index 5e6b472f..00000000 --- a/packages/webui/eslint.config.js +++ /dev/null @@ -1,23 +0,0 @@ -import js from '@eslint/js' -import globals from 'globals' -import reactHooks from 'eslint-plugin-react-hooks' -import reactRefresh from 'eslint-plugin-react-refresh' -import tseslint from 'typescript-eslint' -import { defineConfig, globalIgnores } from 'eslint/config' - -export default defineConfig([ - globalIgnores(['dist']), - { - files: ['**/*.{ts,tsx}'], - extends: [ - js.configs.recommended, - tseslint.configs.recommended, - reactHooks.configs.flat.recommended, - reactRefresh.configs.vite, - ], - languageOptions: { - ecmaVersion: 2020, - globals: globals.browser, - }, - }, -]) diff --git a/packages/webui/eslint.config.ts b/packages/webui/eslint.config.ts new file mode 100644 index 00000000..dcd2d053 --- /dev/null +++ b/packages/webui/eslint.config.ts @@ -0,0 +1,33 @@ +import js from '@eslint/js'; +import globals from 'globals'; +import reactHooks from 'eslint-plugin-react-hooks'; +import reactRefresh from 'eslint-plugin-react-refresh'; +import tseslint from 'typescript-eslint'; +import { defineConfig, globalIgnores } from 'eslint/config'; + +const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1'); + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + parserOptions: { + tsconfigRootDir, + }, + }, + rules: { + 'indent': ['error', 2, { SwitchCase: 1 }], + 'react-refresh/only-export-components': 'off', + 'react-hooks/set-state-in-effect': 'off', + }, + }, +]); \ No newline at end of file diff --git a/packages/webui/package.json b/packages/webui/package.json index d9bfbd86..29949e1a 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.9.0", + "version": "1.9.1", "type": "module", "scripts": { "dev": "vite", @@ -39,6 +39,7 @@ "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.5.2", "globals": "^17.5.0", + "jiti": "^2.6.1", "tailwindcss": "^4.2.2", "typescript": "catalog:", "typescript-eslint": "^8.58.2", diff --git a/packages/webui/src/components/process-probe-dialog.tsx b/packages/webui/src/components/process-probe-dialog.tsx index bbd221ba..768347da 100644 --- a/packages/webui/src/components/process-probe-dialog.tsx +++ b/packages/webui/src/components/process-probe-dialog.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; import { Eye, Loader2, User, UserX } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { @@ -37,7 +37,7 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: Pro const [info, setInfo] = useState(null); const [error, setError] = useState(null); - const probe = async () => { + const probe = useCallback(async () => { setLoading(true); setError(null); setInfo(null); @@ -52,7 +52,7 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: Pro } finally { setLoading(false); } - }; + }, [api.processes, pid]); useEffect(() => { if (open) { @@ -61,7 +61,7 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: Pro setInfo(null); setError(null); } - }, [open]); + }, [open, probe]); return (

diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a9544933..277c7bbb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -20,18 +20,91 @@ importers: .: devDependencies: + '@eslint/js': + specifier: ^10.0.1 + version: 10.0.1(eslint@10.2.0(jiti@2.6.1)) cross-env: specifier: ^10.1.0 version: 10.1.0 + eslint: + specifier: ^10.2.0 + version: 10.2.0(jiti@2.6.1) + eslint-plugin-react-hooks: + specifier: ^7.0.1 + version: 7.0.1(eslint@10.2.0(jiti@2.6.1)) + eslint-plugin-react-refresh: + specifier: ^0.5.2 + version: 0.5.2(eslint@10.2.0(jiti@2.6.1)) + globals: + specifier: ^17.5.0 + version: 17.5.0 + jiti: + specifier: ^2.6.1 + version: 2.6.1 + typescript: + specifier: 'catalog:' + version: 6.0.2 + typescript-eslint: + specifier: ^8.58.2 + version: 8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) + + packages/bridge: + dependencies: + '@snowluma/common': + specifier: workspace:* + version: link:../common + '@snowluma/proto-defs': + specifier: workspace:* + version: link:../proto-defs + '@snowluma/proton': + specifier: workspace:* + version: link:../proton + '@snowluma/sqlite': + specifier: workspace:* + version: link:../sqlite + devDependencies: + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + typescript: + specifier: 'catalog:' + version: 6.0.2 + vite: + specifier: 'catalog:' + version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + vitest: + specifier: ^4.1.4 + version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + + packages/common: + devDependencies: + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 typescript: specifier: 'catalog:' version: 6.0.2 packages/core: dependencies: + '@snowluma/bridge': + specifier: workspace:* + version: link:../bridge + '@snowluma/common': + specifier: workspace:* + version: link:../common + '@snowluma/onebot': + specifier: workspace:* + version: link:../onebot + '@snowluma/proto-defs': + specifier: workspace:* + version: link:../proto-defs '@snowluma/proton': specifier: workspace:* version: link:../proton + '@snowluma/sqlite': + specifier: workspace:* + version: link:../sqlite '@snowluma/websocket': specifier: workspace:* version: link:../websocket @@ -67,6 +140,62 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/onebot: + dependencies: + '@snowluma/bridge': + specifier: workspace:* + version: link:../bridge + '@snowluma/common': + specifier: workspace:* + version: link:../common + '@snowluma/core': + specifier: workspace:* + version: link:../core + '@snowluma/proto-defs': + specifier: workspace:* + version: link:../proto-defs + '@snowluma/proton': + specifier: workspace:* + version: link:../proton + '@snowluma/sqlite': + specifier: workspace:* + version: link:../sqlite + '@snowluma/websocket': + specifier: workspace:* + version: link:../websocket + devDependencies: + '@hono/node-server': + specifier: ^1.19.14 + version: 1.19.14(hono@4.12.14) + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + hono: + specifier: ^4.12.14 + version: 4.12.14 + typescript: + specifier: 'catalog:' + version: 6.0.2 + vite: + specifier: 'catalog:' + version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + vitest: + specifier: ^4.1.4 + version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + + packages/proto-defs: + dependencies: + '@snowluma/proton': + specifier: workspace:* + version: link:../proton + devDependencies: + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + typescript: + specifier: 'catalog:' + version: 6.0.2 + packages/proton: dependencies: typescript: @@ -100,6 +229,21 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/sqlite: + devDependencies: + '@types/better-sqlite3': + specifier: ^7.6.13 + version: 7.6.13 + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + better-sqlite3: + specifier: 12.10.0 + version: 12.10.0 + typescript: + specifier: 'catalog:' + version: 6.0.2 + packages/ui: dependencies: '@radix-ui/react-alert-dialog': @@ -263,6 +407,9 @@ importers: globals: specifier: ^17.5.0 version: 17.5.0 + jiti: + specifier: ^2.6.1 + version: 2.6.1 tailwindcss: specifier: ^4.2.2 version: 4.2.2 @@ -1513,6 +1660,9 @@ packages: '@tybys/wasm-util@0.10.1': resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} + '@types/better-sqlite3@7.6.13': + resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==} + '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} @@ -1689,11 +1839,24 @@ packages: base-log-factory@2.1.4: resolution: {integrity: sha512-FK1tHOB+rXvlBcGYYhSNR2QS2juEG4SZ1ekXQRQ2XscYNtDxllzqkzfgBFr12EVrKb2/07NLdbr0cSwVoc378A==} + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + baseline-browser-mapping@2.10.19: resolution: {integrity: sha512-qCkNLi2sfBOn8XhZQ0FXsT1Ki/Yo5P90hrkRamVFRS7/KV9hpfA4HkoWNU152+8w0zPjnxo5psx5NL3PSGgv5g==} engines: {node: '>=6.0.0'} hasBin: true + better-sqlite3@12.10.0: + resolution: {integrity: sha512-CyzaZRQKyHkB2ZInfTTl2nvT33EbDpjkLEbE8/Zck3Ll6O0qqvuGdrJ45HgtH+HykRg88ITY3AdreBGN70aBSQ==} + engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x} + + bindings@1.5.0: + resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} + + bl@4.1.0: + resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + blf-colorful-appender@1.0.6: resolution: {integrity: sha512-MdwOI17J8iOC2XKi5b4VagAJg308R4QesRoCAPw/w7ihzwkTst91LvkTAF3GvPJCEaHXptiUS2UsFkCNiBIEGg==} @@ -1709,6 +1872,9 @@ packages: engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true + buffer@5.7.1: + resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + bundle-require@5.1.0: resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -1730,6 +1896,9 @@ packages: resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} engines: {node: '>= 14.16.0'} + chownr@1.1.4: + resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} + class-variance-authority@0.7.1: resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==} @@ -1782,6 +1951,14 @@ packages: supports-color: optional: true + decompress-response@6.0.0: + resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} + engines: {node: '>=10'} + + deep-extend@0.6.0: + resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==} + engines: {node: '>=4.0.0'} + deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} @@ -1799,6 +1976,9 @@ packages: electron-to-chromium@1.5.339: resolution: {integrity: sha512-Is+0BBHJ4NrdpAYiperrmp53pLywG/yV/6lIMTAnhxvzj/Cmn5Q/ogSHC6AKe7X+8kPLxxFk0cs5oc/3j/fxIg==} + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + enhanced-resolve@5.20.1: resolution: {integrity: sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==} engines: {node: '>=10.13.0'} @@ -1882,6 +2062,10 @@ packages: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} + expand-template@2.0.3: + resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==} + engines: {node: '>=6'} + expect-type@1.3.0: resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} engines: {node: '>=12.0.0'} @@ -1913,6 +2097,9 @@ packages: resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} engines: {node: '>=16.0.0'} + file-uri-to-path@1.0.0: + resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} + find-up@5.0.0: resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} engines: {node: '>=10'} @@ -1941,6 +2128,9 @@ packages: react-dom: optional: true + fs-constants@1.0.0: + resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} + fs-extra@11.3.4: resolution: {integrity: sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==} engines: {node: '>=14.14'} @@ -1964,6 +2154,9 @@ packages: get-tsconfig@4.14.0: resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==} + github-from-package@0.0.0: + resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==} + glob-parent@6.0.2: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} @@ -1989,6 +2182,9 @@ packages: resolution: {integrity: sha512-RWzP96k/yv0PQfyXnWjs6zot20TqfpfsNXhOnev8d1InAxubW93L11/oNUc3tQqn2G0bSdAOBpX+2uDFHV7kdQ==} engines: {node: '>=16.9.0'} + ieee754@1.2.1: + resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -2004,6 +2200,12 @@ packages: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + ini@1.3.8: + resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} + is-core-module@2.16.1: resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==} engines: {node: '>= 0.4'} @@ -2169,10 +2371,20 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + mimic-response@3.1.0: + resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} + engines: {node: '>=10'} + minimatch@10.2.5: resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} engines: {node: 18 || 20 || >=22} + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + mkdirp-classic@0.5.3: + resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} + mlly@1.8.2: resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==} @@ -2207,9 +2419,16 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true + napi-build-utils@2.0.0: + resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==} + natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + node-abi@3.92.0: + resolution: {integrity: sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==} + engines: {node: '>=10'} + node-addon-api@7.1.1: resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==} @@ -2223,6 +2442,9 @@ packages: obug@2.1.1: resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + optionator@0.9.4: resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} engines: {node: '>= 0.8.0'} @@ -2285,14 +2507,27 @@ packages: resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==} engines: {node: ^10 || ^12 || >=14} + prebuild-install@7.1.3: + resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} + engines: {node: '>=10'} + deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available. + hasBin: true + prelude-ls@1.2.1: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} + pump@3.0.4: + resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} + punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} + rc@1.2.8: + resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} + hasBin: true + react-dom@19.2.5: resolution: {integrity: sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==} peerDependencies: @@ -2332,6 +2567,10 @@ packages: resolution: {integrity: sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==} engines: {node: '>=0.10.0'} + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + readdirp@4.1.2: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} @@ -2358,6 +2597,9 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + sass@1.99.0: resolution: {integrity: sha512-kgW13M54DUB7IsIRM5LvJkNlpH+WhMpooUcaWGFARkF1Tc82v9mIWkCbCYf+MBvpIUBSeSOTilpZjEPr2VYE6Q==} engines: {node: '>=14.0.0'} @@ -2396,6 +2638,12 @@ packages: siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + simple-concat@1.0.1: + resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} + + simple-get@4.0.1: + resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==} + sonner@2.0.7: resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==} peerDependencies: @@ -2416,6 +2664,13 @@ packages: std-env@4.1.0: resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} + string_decoder@1.3.0: + resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} + + strip-json-comments@2.0.1: + resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} + engines: {node: '>=0.10.0'} + sucrase@3.35.1: resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==} engines: {node: '>=16 || 14 >=14.17'} @@ -2435,6 +2690,13 @@ packages: resolution: {integrity: sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==} engines: {node: '>=6'} + tar-fs@2.1.4: + resolution: {integrity: sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==} + + tar-stream@2.2.0: + resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} + engines: {node: '>=6'} + thenify-all@1.6.0: resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} engines: {node: '>=0.8'} @@ -2500,6 +2762,9 @@ packages: engines: {node: '>=18.0.0'} hasBin: true + tunnel-agent@0.6.0: + resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} + tw-animate-css@1.4.0: resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} @@ -2566,6 +2831,9 @@ packages: peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + vite-plugin-cp@6.0.3: resolution: {integrity: sha512-qxKGH3v9wPwUDbDchJf4IH4mRE1zkLWgzZSxwrl8LapwUWm48IFS7SlbRmcF4NquC/fESA5cHFge9E2Ps+woxg==} engines: {node: '>=14.18.0', vite: '>=3.1.0'} @@ -2672,6 +2940,9 @@ packages: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -3711,6 +3982,10 @@ snapshots: tslib: 2.8.1 optional: true + '@types/better-sqlite3@7.6.13': + dependencies: + '@types/node': 25.6.0 + '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 @@ -3922,8 +4197,25 @@ snapshots: date-manip: 2.0.6 is-what-type: 1.1.4 + base64-js@1.5.1: {} + baseline-browser-mapping@2.10.19: {} + better-sqlite3@12.10.0: + dependencies: + bindings: 1.5.0 + prebuild-install: 7.1.3 + + bindings@1.5.0: + dependencies: + file-uri-to-path: 1.0.0 + + bl@4.1.0: + dependencies: + buffer: 5.7.1 + inherits: 2.0.4 + readable-stream: 3.6.2 + blf-colorful-appender@1.0.6: dependencies: base-log-factory: 2.1.4 @@ -3951,6 +4243,11 @@ snapshots: node-releases: 2.0.37 update-browserslist-db: 1.2.3(browserslist@4.28.2) + buffer@5.7.1: + dependencies: + base64-js: 1.5.1 + ieee754: 1.2.1 + bundle-require@5.1.0(esbuild@0.27.7): dependencies: esbuild: 0.27.7 @@ -3966,6 +4263,8 @@ snapshots: dependencies: readdirp: 4.1.2 + chownr@1.1.4: {} + class-variance-authority@0.7.1: dependencies: clsx: 2.1.1 @@ -4003,6 +4302,12 @@ snapshots: dependencies: ms: 2.1.3 + decompress-response@6.0.0: + dependencies: + mimic-response: 3.1.0 + + deep-extend@0.6.0: {} + deep-is@0.1.4: {} deepmerge@4.3.1: {} @@ -4013,6 +4318,10 @@ snapshots: electron-to-chromium@1.5.339: {} + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + enhanced-resolve@5.20.1: dependencies: graceful-fs: 4.2.11 @@ -4142,6 +4451,8 @@ snapshots: esutils@2.0.3: {} + expand-template@2.0.3: {} + expect-type@1.3.0: {} fast-deep-equal@3.1.3: {} @@ -4162,6 +4473,8 @@ snapshots: dependencies: flat-cache: 4.0.1 + file-uri-to-path@1.0.0: {} + find-up@5.0.0: dependencies: locate-path: 6.0.0 @@ -4189,6 +4502,8 @@ snapshots: react: 19.2.5 react-dom: 19.2.5(react@19.2.5) + fs-constants@1.0.0: {} + fs-extra@11.3.4: dependencies: graceful-fs: 4.2.11 @@ -4208,6 +4523,8 @@ snapshots: dependencies: resolve-pkg-maps: 1.0.0 + github-from-package@0.0.0: {} + glob-parent@6.0.2: dependencies: is-glob: 4.0.3 @@ -4228,6 +4545,8 @@ snapshots: hono@4.12.18: {} + ieee754@1.2.1: {} + ignore@5.3.2: {} ignore@7.0.5: {} @@ -4237,6 +4556,10 @@ snapshots: imurmurhash@0.1.4: {} + inherits@2.0.4: {} + + ini@1.3.8: {} + is-core-module@2.16.1: dependencies: hasown: 2.0.2 @@ -4357,10 +4680,16 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 + mimic-response@3.1.0: {} + minimatch@10.2.5: dependencies: brace-expansion: 5.0.5 + minimist@1.2.8: {} + + mkdirp-classic@0.5.3: {} + mlly@1.8.2: dependencies: acorn: 8.16.0 @@ -4392,8 +4721,14 @@ snapshots: nanoid@3.3.11: {} + napi-build-utils@2.0.0: {} + natural-compare@1.4.0: {} + node-abi@3.92.0: + dependencies: + semver: 7.7.4 + node-addon-api@7.1.1: optional: true @@ -4403,6 +4738,10 @@ snapshots: obug@2.1.1: {} + once@1.4.0: + dependencies: + wrappy: 1.0.2 + optionator@0.9.4: dependencies: deep-is: 0.1.4 @@ -4454,10 +4793,37 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 + prebuild-install@7.1.3: + dependencies: + detect-libc: 2.1.2 + expand-template: 2.0.3 + github-from-package: 0.0.0 + minimist: 1.2.8 + mkdirp-classic: 0.5.3 + napi-build-utils: 2.0.0 + node-abi: 3.92.0 + pump: 3.0.4 + rc: 1.2.8 + simple-get: 4.0.1 + tar-fs: 2.1.4 + tunnel-agent: 0.6.0 + prelude-ls@1.2.1: {} + pump@3.0.4: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + punycode@2.3.1: {} + rc@1.2.8: + dependencies: + deep-extend: 0.6.0 + ini: 1.3.8 + minimist: 1.2.8 + strip-json-comments: 2.0.1 + react-dom@19.2.5(react@19.2.5): dependencies: react: 19.2.5 @@ -4492,6 +4858,12 @@ snapshots: react@19.2.5: {} + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.3.0 + util-deprecate: 1.0.2 + readdirp@4.1.2: {} resolve-from@5.0.0: {} @@ -4557,6 +4929,8 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.60.4 fsevents: 2.3.3 + safe-buffer@5.2.1: {} + sass@1.99.0: dependencies: chokidar: 4.0.3 @@ -4586,6 +4960,14 @@ snapshots: siginfo@2.0.0: {} + simple-concat@1.0.1: {} + + simple-get@4.0.1: + dependencies: + decompress-response: 6.0.0 + once: 1.4.0 + simple-concat: 1.0.1 + sonner@2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5): dependencies: react: 19.2.5 @@ -4599,6 +4981,12 @@ snapshots: std-env@4.1.0: {} + string_decoder@1.3.0: + dependencies: + safe-buffer: 5.2.1 + + strip-json-comments@2.0.1: {} + sucrase@3.35.1: dependencies: '@jridgewell/gen-mapping': 0.3.13 @@ -4617,6 +5005,21 @@ snapshots: tapable@2.3.2: {} + tar-fs@2.1.4: + dependencies: + chownr: 1.1.4 + mkdirp-classic: 0.5.3 + pump: 3.0.4 + tar-stream: 2.2.0 + + tar-stream@2.2.0: + dependencies: + bl: 4.1.0 + end-of-stream: 1.4.5 + fs-constants: 1.0.0 + inherits: 2.0.4 + readable-stream: 3.6.2 + thenify-all@1.6.0: dependencies: thenify: 3.3.1 @@ -4683,6 +5086,10 @@ snapshots: optionalDependencies: fsevents: 2.3.3 + tunnel-agent@0.6.0: + dependencies: + safe-buffer: 5.2.1 + tw-animate-css@1.4.0: {} type-check@0.4.0: @@ -4739,6 +5146,8 @@ snapshots: dependencies: react: 19.2.5 + util-deprecate@1.0.2: {} + vite-plugin-cp@6.0.3: dependencies: fs-extra: 11.3.4 @@ -4827,6 +5236,8 @@ snapshots: word-wrap@1.2.5: {} + wrappy@1.0.2: {} + yallist@3.1.1: {} yocto-queue@0.1.0: {} diff --git a/tools/fetch-sqlite-prebuilts.mjs b/tools/fetch-sqlite-prebuilts.mjs new file mode 100644 index 00000000..0af48024 --- /dev/null +++ b/tools/fetch-sqlite-prebuilts.mjs @@ -0,0 +1,121 @@ +#!/usr/bin/env node +// Downloads better-sqlite3 prebuilt native bindings for all SnowLuma +// CI matrix targets (win32-x64, linux-x64, linux-arm64) plus the +// developer host (darwin-arm64 / darwin-x64) and vendors them into +// `packages/runtime/native/better-sqlite3--.node`. +// +// vite-plugin-cp picks the matching binary for `SNOWLUMA_TARGET` +// during `pnpm build` and copies it into `dist/native/`, where +// `@snowluma/sqlite/index.ts` finds it at runtime. Naming + layout +// mirror the existing `websocket--.node` convention +// (flat dir, dash-separated triplet) so SnowLuma's existing +// per-target packaging step doesn't need a new code path. +// +// Usage: +// node tools/fetch-sqlite-prebuilts.mjs # default version +// node tools/fetch-sqlite-prebuilts.mjs 11.10.0 # explicit version +// +// Re-run when bumping the better-sqlite3 pin in +// `packages/sqlite/package.json`. The script is idempotent — +// existing binaries with the same SHA256 are left alone. + +import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawnSync } from 'node:child_process'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const repoRoot = join(__dirname, '..'); +const nativeRoot = join(repoRoot, 'packages', 'runtime', 'native'); + +// Default NODE_MODULE_VERSIONs to vendor. v127 = Node 22 LTS (matches +// the CI matrix + `engines.node: ">=22"`). v137 = Node 24 (covers dev +// boxes already on the newer release). Pass extra versions positionally +// after the better-sqlite3 version to add more: +// node tools/fetch-sqlite-prebuilts.mjs 11.10.0 v127 v137 v115 +const DEFAULT_NODE_ABIS = ['v127', 'v137']; + +// The targets vendored into the repo. linuxmusl-* variants are +// available too (for Alpine-based Docker images) but SnowLuma's +// existing native vendoring (websocket / ffmpeg) only ships glibc +// Linux, so we follow that lead. Add musl entries here if/when a +// downstream Alpine consumer asks. +const TARGETS = [ + { triplet: 'darwin-arm64', prebuildName: 'darwin-arm64' }, + { triplet: 'darwin-x64', prebuildName: 'darwin-x64' }, + { triplet: 'linux-arm64', prebuildName: 'linux-arm64' }, + { triplet: 'linux-x64', prebuildName: 'linux-x64' }, + { triplet: 'win32-x64', prebuildName: 'win32-x64' }, +]; + +async function main() { + const version = process.argv[2] ?? readVersionFromPin(); + const abis = process.argv.slice(3).filter(a => a.startsWith('v')); + const targetAbis = abis.length > 0 ? abis : DEFAULT_NODE_ABIS; + console.log(`fetching better-sqlite3 v${version} prebuilds (ABIs: ${targetAbis.join(', ')})`); + + mkdirSync(nativeRoot, { recursive: true }); + for (const abi of targetAbis) { + for (const target of TARGETS) { + const destBin = join(nativeRoot, `better-sqlite3-${abi}-${target.triplet}.node`); + if (existsSync(destBin)) { + console.log(` ✓ ${abi} ${target.triplet} (already vendored, skipping)`); + continue; + } + + const url = `https://github.com/WiseLibs/better-sqlite3/releases/download/v${version}/better-sqlite3-v${version}-node-${abi}-${target.prebuildName}.tar.gz`; + console.log(` ↓ ${abi} ${target.triplet}: ${url}`); + + const tarPath = join(tmpdir(), `better-sqlite3-${version}-${abi}-${target.triplet}.tar.gz`); + await downloadTo(url, tarPath); + extractBinding(tarPath, destBin); + console.log(` → ${destBin}`); + } + } + + console.log('done.'); +} + +function readVersionFromPin() { + const pkg = JSON.parse(readFileSync(join(repoRoot, 'packages', 'sqlite', 'package.json'), 'utf8')); + const raw = pkg.devDependencies?.['better-sqlite3']; + if (!raw) { + throw new Error('cannot find better-sqlite3 pin in packages/sqlite/package.json'); + } + // strip the `^` / `~` / `>=` etc prefix. + return raw.replace(/^[\^~>=<]+/, ''); +} + +async function downloadTo(url, dest) { + // curl is in every CI image SnowLuma cares about (and on every + // dev mac/linux), so we just shell out — keeps this script free + // of npm dependencies, which matters because pnpm install hasn't + // necessarily run yet when someone clones the repo fresh. + const result = spawnSync('curl', ['-fsSL', '--retry', '3', '-o', dest, url], { stdio: 'inherit' }); + if (result.status !== 0) { + throw new Error(`curl failed for ${url} (exit ${result.status})`); + } +} + +function extractBinding(tarPath, destBin) { + // The prebuild archive is `build/Release/better_sqlite3.node` + // wrapped in the standard better-sqlite3 layout. We capture tar's + // stdout as a buffer (spawnSync's `stdio: 'pipe'` + `encoding: null`) + // and write that buffer to the destination — simpler than wiring + // a Node WriteStream which spawnSync's stdio doesn't accept. + const result = spawnSync( + 'tar', + ['-xzOf', tarPath, '--strip-components=2', 'build/Release/better_sqlite3.node'], + { stdio: ['ignore', 'pipe', 'inherit'], encoding: null, maxBuffer: 64 * 1024 * 1024 }, + ); + if (result.status !== 0) { + throw new Error(`tar failed for ${tarPath} (exit ${result.status})`); + } + writeFileSync(destBin, result.stdout); +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/tsconfig.base.json b/tsconfig.base.json index 74f6d69f..0f4ad410 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -3,7 +3,9 @@ "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", - "lib": ["ES2022"], + "lib": [ + "ES2022" + ], "strict": true, "esModuleInterop": true, "skipLibCheck": true,