Compare commits

..

23 Commits

Author SHA1 Message Date
snowluma-bot[bot]
fd9a239241 Merge pull request #27 from SnowLuma/dev
chore: promote dev → main (8636222)
2026-05-11 15:32:46 +00:00
DrSmoothl
8636222d91 [merge] fix & upd 2026-05-11 23:30:08 +08:00
DrSmoothl
6f506ff52c fix onebot video file sending 2026-05-11 23:26:45 +08:00
DrSmoothl
e917720d9d fix linux hook stale socket detection 2026-05-11 23:14:27 +08:00
DrSmoothl
af80855d2d fix(core): persist identities from request events 2026-05-11 19:16:39 +08:00
DrSmoothl
9a30a40a1f feat(core): add persistent identity service 2026-05-11 19:09:05 +08:00
H3CoF6
df5e3a26ac implement some onebot actions (#26)
* feat: implement more group admin action (kick members and set search and set add type)

* feat: implement some user extend func (set group mark \\ get custom emoji)

* feat: implement get send emoji his
2026-05-11 16:00:25 +08:00
DrSmoothl
bf0a89e221 fix(core): resolve group join member identity 2026-05-10 17:38:05 +08:00
snowluma-bot[bot]
5a4028d5dc Merge pull request #25 from SnowLuma/dev
chore: promote dev → main (6f6ce11)
2026-05-10 10:17:23 +08:00
H3CoF6
6f6ce1144b 补全一些onebot action实现 2 (#24)
* feat: implement get profile like

* feat: implement get at all remain

* feat: implement get undirectional friends

* feat: implement set self long nick

* feat: implement set input status

* feat: implement EN 2 ZH

* feat: implement get mini app ark

* feat: implement click inline button

* feat: implement set and send group sign

* feat: implement set qq avatar

* feat: group notice with pic and delete notice implement

* fix(group-notice): POST api and fix new bkn logic
2026-05-10 10:14:41 +08:00
snowluma-bot[bot]
d02e7cc3ab Merge pull request #23 from SnowLuma/dev
chore: promote dev → main (bec23c4)
2026-05-10 01:32:20 +08:00
DrSmoothl
bec23c4dbb [merge] promote SDK changes 2026-05-10 01:29:57 +08:00
DrSmoothl
c343021318 feat: add SnowLuma TypeScript SDK 2026-05-10 01:26:35 +08:00
DrSmoothl
9ab4128799 Implement video message upload 2026-05-09 23:06:55 +08:00
手瓜一十雪
95df5234fb Support forced group member cache refresh
Add a `force` flag to member cache refresh logic so events that affect the bot itself trigger an immediate refresh. When the event userUin matches the bot's UIN, `triggerMemberCacheRefresh` sets `force = true` and forwards it to `fetchGroupMemberList`. `fetchGroupMemberList` now accepts an optional `force` parameter (default false) and bypasses the TTL cache when `force` is true, ensuring up-to-date member data after join/leave events.
2026-05-09 19:54:20 +08:00
snowluma-bot[bot]
9938545788 Merge pull request #21 from SnowLuma/dev
chore: promote dev → main (a7b3809)
2026-05-09 19:40:04 +08:00
手瓜一十雪
a7b3809a12 Only track hook states for running PIDs
Stop exposing and retaining hook state for PIDs that are not currently running. listProcesses() no longer returns orphaned states; live-pipe handling ignores PIDs not present in the current process list. When a process is not running its state is immediately torn down (tearDownClient called) and removed, and bridgeManager.onPidDisconnected is notified if the state was logged in. Also reorganized runningSet creation so it can be reused for these checks.
2026-05-09 19:38:52 +08:00
snowluma-bot[bot]
7149bc8689 Merge pull request #20 from SnowLuma/dev
chore: promote dev → main (c39b3f5)
2026-05-09 19:33:40 +08:00
snowluma-bot[bot]
9802128421 Merge pull request #19 from SnowLuma/dev
chore: promote dev → main (2af273b)
2026-05-09 16:40:37 +08:00
墨梓柒
a572d05c25 Merge pull request #18 from SnowLuma/dependabot/npm_and_yarn/hono-4.12.18
build(deps-dev): bump hono from 4.12.14 to 4.12.18
2026-05-09 16:03:21 +08:00
dependabot[bot]
cb06624d12 build(deps-dev): bump hono from 4.12.14 to 4.12.18
Bumps [hono](https://github.com/honojs/hono) from 4.12.14 to 4.12.18.
- [Release notes](https://github.com/honojs/hono/releases)
- [Commits](https://github.com/honojs/hono/compare/v4.12.14...v4.12.18)

---
updated-dependencies:
- dependency-name: hono
  dependency-version: 4.12.18
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-09 08:01:11 +00:00
snowluma-bot[bot]
7b93839186 Merge pull request #17 from SnowLuma/dev
chore: promote dev → main (1565749)
2026-05-09 15:37:22 +08:00
snowluma-bot[bot]
d0085ec052 Merge pull request #15 from SnowLuma/dev
chore: promote dev → main (c3b328f)
2026-05-09 15:04:19 +08:00
76 changed files with 7773 additions and 177 deletions

106
.github/workflows/sdk-npm-publish.yml vendored Normal file
View File

@@ -0,0 +1,106 @@
name: Publish SDK to npm
on:
push:
branches: [main]
paths:
- 'packages/sdk/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
- 'tsconfig.base.json'
workflow_dispatch:
permissions:
contents: read
id-token: write
concurrency:
group: sdk-npm-publish-${{ github.ref }}
cancel-in-progress: false
jobs:
publish:
name: Build, test, and publish SDK
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Type check SDK
run: pnpm --filter @snowluma/sdk typecheck
- name: Test SDK
run: pnpm --filter @snowluma/sdk test
- name: Build SDK
run: pnpm --filter @snowluma/sdk build
- name: Check npm package version
id: npm
working-directory: packages/sdk
shell: bash
run: |
set -euo pipefail
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
{
echo "package_name=${package_name}"
echo "package_version=${package_version}"
} >> "${GITHUB_OUTPUT}"
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
echo "already_published=true" >> "${GITHUB_OUTPUT}"
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
else
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
- name: Publish SDK to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/sdk
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
shell: bash
run: |
{
echo "## SDK npm publish"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
} >> "${GITHUB_STEP_SUMMARY}"

View File

@@ -1,3 +1,3 @@
# V2.0.0 前计划
- [ ] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。
- [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。

View File

@@ -6,8 +6,9 @@
"type": "module",
"scripts": {
"build": "pnpm --filter @snowluma/core build",
"build:sdk": "pnpm --filter @snowluma/sdk build",
"build:webui": "pnpm --filter webui build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter webui build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
"dev": "pnpm --filter @snowluma/core dev",
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
"dev:web": "pnpm --filter webui dev",
@@ -32,4 +33,4 @@
"engines": {
"node": ">=22"
}
}
}

View File

@@ -21,7 +21,7 @@
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "^24.12.2",
"cross-env": "^10.1.0",
"hono": "^4.12.14",
"hono": "^4.12.18",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",

View File

@@ -9,10 +9,13 @@ import { computeHashes, computeMd5, loadBinarySource } from './highway/utils';
import { buildSendElems } from './builders/element-builder';
import { parseMsgPush } from './handlers/msg-push-handler';
import type { ForwardNodePayload, MessageElement } from './events';
import { createLogger } from '../utils/logger';
import { PushMsgSchema } from './proto/message';
import {
OidbMuteMemberSchema,
OidbMuteAllSchema,
Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema,
OidbKickMemberSchema,
OidbLeaveGroupSchema,
OidbFriendRequestActionSchema,
@@ -47,6 +50,32 @@ import {
SetStatusReqSchema,
SetStatusRespSchema,
OidbSetProfileSchema,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
Oidb0x8a0ReqSchema,
Oidb0x8a0RespSchema,
Oidb0xf16ReqSchema,
Oidb0xf16RespSchema,
Oidb0x8a7RespSchema,
Oidb0x8a7ReqSchema,
Oidb0xe17RespSchema,
Oidb0xe17ReqSchema,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
MiniAppShareReqSchema,
MiniAppShareRespSchema,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
FaceroamOpReqSchema,
FaceroamOpRespSchema,
Oidb0x9083ReqSchema,
Oidb0x9083RespSchema,
} from './proto/oidb-action';
import { FileUploadExtSchema } from './proto/highway';
import {
@@ -58,6 +87,8 @@ import {
} from './proto/longmsg';
import { gzipSync, gunzipSync } from 'zlib';
const log = createLogger('BridgeActions');
export interface GroupFileInfo {
fileId: string;
fileName: string;
@@ -389,6 +420,11 @@ export async function setFriendRemark(bridge: Bridge, userId: number, remark: st
{ targetUid: uid, remark }, OidbSetFriendRemarkSchema);
}
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xf16_1', 0xF16, 1,
{ inner: { groupId: BigInt(groupId), remark }, field12: 0 }, Oidb0xf16ReqSchema);
}
// ---------------------------------------------------------------------------
// Group file count
// ---------------------------------------------------------------------------
@@ -420,12 +456,28 @@ export async function muteGroupAll(bridge: Bridge, groupId: number, enable: bool
{ groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, OidbMuteAllSchema);
}
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: BigInt(groupId), settings: { addType }, field12: 0 }, Oidb0x89a_0AddOptionSchema);
}
export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, Oidb0x89a_0SearchSchema);
}
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, OidbKickMemberSchema);
}
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
const targetUids = await Promise.all(userIds.map(userId => resolveUserUid(bridge, userId, groupId)));
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 }, Oidb0x8a0ReqSchema);
}
export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1097_1', 0x1097, 1,
{ groupUin: groupId }, OidbLeaveGroupSchema);
@@ -1358,4 +1410,405 @@ export async function setProfile(
req,
OidbSetProfileSchema
);
}
}
export async function getProfileLike(
bridge: Bridge,
userId?: number,
start: number = 0,
limit: number = 10
) {
// const isSelf = !userId || userId === bridge.qqInfo.uin;
// const targetUid = isSelf
// ? bridge.qqInfo.uid
// : await bridge.getUidByUinV2(userId!);
const isSelf = !userId
const targetUid = isSelf
? await resolveSelfUid(bridge)
: await resolveUserUid(bridge, 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 result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x7ed_12',
0x7ED,
12,
req,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema
);
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 getGroupAtAllRemain(
bridge: Bridge,
groupId: number
) {
const req = {
basic1: 1,
basic2: 2,
basic3: 1,
uin: BigInt(bridge.qqInfo.uin),
groupId: BigInt(groupId),
type: 0,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x8a7_0',
0x8A7,
0,
req,
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema
);
if (!result) {
throw new Error('get group at all remain result empty');
}
return {
can_at_all: !!result.canAtAll,
remain_at_all_count_for_group: Number(result.groupRemain || 0), // 【修改点】:防止底层库将 uint32 也返回成 BigInt 导致无法被 JSON 序列化
remain_at_all_count_for_uin: Number(result.uinRemain || 0) // 【修改点】:同上
};
}
export async function getUnidirectionalFriendList(
bridge: Bridge
) {
const reqObj = {
uint64_uin: String(bridge.qqInfo.uin),
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: ""
};
const req = {
jsonBody: JSON.stringify(reqObj)
};
const result = await sendOidbAndDecode<any>(
bridge,
'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
0xE17,
0,
req,
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema
);
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 setSelfLongNick(
bridge: Bridge,
longNick: string
) {
const req = {
uin: BigInt(bridge.qqInfo.uin),
profile: {
tag: 102,
value: String(longNick)
}
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112a_2',
0x112A,
2,
req,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema
);
}
export async function setInputStatus(
bridge: Bridge,
userId: number,
eventType: number
) {
const targetUid = await resolveUserUid(bridge, userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
reqBody: {
uid: targetUid,
chatType: 0,
eventType: eventType
}
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xcd4_1',
0xCD4,
1,
req,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema
);
}
export async function translateEn2Zh(
bridge: Bridge,
words: string[]
) {
const req = {
translateReq: {
srcLang: 'en',
dstLang: 'zh',
words: words
},
tag10: 1,
tag12: 1
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x990_2',
0x990,
2,
req,
Oidb0x990ReqSchema,
Oidb0x990RespSchema
);
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"; // 默认 bili
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 result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112e_1',
0x112E,
1,
req,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema
);
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.qqInfo.uin),
groupId: String(groupId),
version: "9.0.90"
}
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xEB7_1',
0xEB7,
1,
req,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema
);
}
export async function setAvatar(
bridge: Bridge,
source: string,
): Promise<void> {
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));
}
export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise<string[]> {
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(bridge.qqInfo.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.qqInfo.uin}/${id}/0`);
}
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 = {
groupId: BigInt(groupId),
sequence,
emojiType,
emojiId,
cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0),
field7: 0,
count,
field12: 1,
};
const resp = await sendOidbAndDecode<any>(bridge, 'OidbSvcTrpcTcp.0x9083_1', 0x9083, 1, req, Oidb0x9083ReqSchema, Oidb0x9083RespSchema);
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 };
}

View File

@@ -91,7 +91,7 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
if (nextUin === 0) nextUin = null;
} while (nextUin !== null);
bridge.qqInfo.setFriends(friends);
bridge.identity.rememberFriends(friends);
return friends;
}
@@ -138,7 +138,7 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
});
}
}
bridge.qqInfo.setGroups(groups);
bridge.identity.rememberGroups(groups);
return groups;
}
@@ -189,7 +189,7 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
token = resp?.token ?? '';
} while (token);
bridge.qqInfo.setGroupMembers(groupId, members);
bridge.identity.rememberGroupMembers(groupId, members);
return members;
}
@@ -248,9 +248,7 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
info.age = numMap.get(20037) ?? 0;
}
bridge.qqInfo.setUserProfile(info);
const selfUin = parseInt(bridge.qqInfo.uin, 10) || 0;
if (info.uin === selfUin) bridge.qqInfo.setSelfProfile(info);
bridge.identity.rememberUserProfile(info);
return info;
}
@@ -286,6 +284,7 @@ export async function fetchGroupRequests(bridge: Bridge, filtered = false): Prom
filtered,
});
}
bridge.identity.rememberGroupRequests(requests);
return requests;
}

View File

@@ -74,15 +74,15 @@ export async function sendOidbAndDecode<T>(
export async function resolveUserUid(bridge: Bridge, uin: number, groupId?: number): Promise<string> {
// Try group member first
if (groupId !== undefined) {
const uid = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
const uid = bridge.identity.findUidByUin(uin, groupId);
if (uid) return uid;
// Try fetching member list
try { await bridge.fetchGroupMemberList(groupId); } catch { /* ignore */ }
const uid2 = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
const uid2 = bridge.identity.findUidByUin(uin, groupId);
if (uid2) return uid2;
}
// Try cached
const uid = bridge.qqInfo.findUidByUin(uin);
const uid = bridge.identity.findUidByUin(uin);
if (uid) return uid;
// Fetch profile
const profile = await bridge.fetchUserProfile(uin);

View File

@@ -10,6 +10,7 @@ import { MSG_PUSH_CMD, parseMsgPush } from './handlers/msg-push-handler';
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { buildSendElems } from './builders/element-builder';
import { IdentityService } from './identity-service';
import { createLogger } from '../utils/logger';
import {
SendMessageRequestSchema,
@@ -30,7 +31,10 @@ import type { WebHonorType } from './web/group-honor';
import {
muteGroupMember as muteGroupMember_,
muteGroupAll as muteGroupAll_,
setGroupAddOption as setGroupAddOption_,
setGroupSearch as setGroupSearch_,
kickGroupMember as kickGroupMember_,
kickGroupMembers as kickGroupMembers_,
leaveGroup as leaveGroup_,
setGroupAdmin as setGroupAdmin_,
setGroupCard as setGroupCard_,
@@ -64,9 +68,22 @@ import {
markPrivateMessageRead as markGroupMsgAsRead_,
markGroupMessageRead as markPrivateMsgAsRead_,
setFriendRemark as setFriendRemark_,
setGroupRemark as setGroupRemark_,
fetchGroupFileCount as fetchGroupFileCount_,
setOnlineStatus as setOnlineStatus_,
setProfile as setProfile_,
getProfileLike as getProfileLike_,
getGroupAtAllRemain as getGroupAtAllRemain_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
setSelfLongNick as setSelfLongNick_,
setInputStatus as setInputStatus_,
translateEn2Zh as translateEn2Zh_,
getMiniAppArk as getMiniAppArk_,
clickInlineKeyboardButton as clickInlineKeyboardButton_,
sendGroupSign as sendGroupSign_,
setAvatar as setAvatar_,
fetchCustomFace as fetchCustomFace_,
getEmojiLikes as getEmojiLikes_,
} from './bridge-actions';
import {
getGroupHonorInfo as getGroupHonorInfo_,
@@ -75,6 +92,7 @@ import {
getGroupEssenceAll as getGroupEssenceAll_,
sendGroupNotice as sendGroupNotice_,
getGroupNotice as getGroupNotice_,
deleteGroupNoticeByFid as deleteGroupNotice_,
getCookiesStr as getCookiesStr_,
getCsrfToken as getCsrfToken_,
getCredentials as getCredentials_,
@@ -107,6 +125,8 @@ export interface ClientKeyInfo {
keyIndex: string
}
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
@@ -114,6 +134,7 @@ export class Bridge {
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
private qqInfo_: QQInfo;
readonly identity: IdentityService;
private pids_ = new Set<number>();
/**
* Per-kind event subscription. Replaces the legacy single-callback
@@ -138,13 +159,19 @@ export class Bridge {
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(qqInfo: QQInfo) {
constructor(qqInfo: QQInfo, identity = IdentityService.memory(qqInfo)) {
this.qqInfo_ = qqInfo;
this.identity = identity;
this.registerDefaultHandlers();
}
get qqInfo(): QQInfo { return this.qqInfo_; }
dispose(): void {
this.identity.close();
this.events.clear();
}
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
}
@@ -188,9 +215,13 @@ export class Bridge {
try {
const events = handler(pkt, this.qqInfo_);
for (const event of events) {
this.triggerMemberCacheRefresh(event);
printEvent(event);
this.emitEvent(event);
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event);
} else {
this.triggerMemberCacheRefresh(event);
printEvent(event);
this.emitEvent(event);
}
}
} catch (e) {
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
@@ -198,19 +229,76 @@ export class Bridge {
}
}
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.triggerMemberCacheRefresh(event, refreshed);
printEvent(event);
this.emitEvent(event);
}
private emitEvent(event: QQEventVariant): void {
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
// own onError hook so one bad listener never blocks the others.
void this.events.emit(event);
}
private triggerMemberCacheRefresh(event: QQEventVariant): void {
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
const refreshed = await this.refreshMemberCache(
event.groupId,
!this.qqInfo_.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
true,
);
this.resolveMemberIdentityFromCache(event);
return refreshed;
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
if (event.groupId <= 0) return;
if (event.userUin <= 0 && event.userUid) {
const uin = this.resolveUidFromCache(event.groupId, event.userUid);
if (uin !== null) event.userUin = uin;
}
if (event.operatorUin <= 0 && event.operatorUid) {
const uin = this.resolveUidFromCache(event.groupId, event.operatorUid);
if (uin !== null) event.operatorUin = uin;
}
}
private resolveUidFromCache(groupId: number, uid: string): number | null {
return this.identity.findUinByUid(uid, groupId);
}
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
const selfUin = Number(this.qqInfo_.uin);
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.qqInfo_.selfUid);
}
private triggerMemberCacheRefresh(event: QQEventVariant, alreadyRefreshed = false): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
let refreshGroupList = false;
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
break;
case 'group_member_leave':
groupId = event.groupId;
@@ -226,13 +314,13 @@ export class Bridge {
if (groupId <= 0) return;
if (this.memberRefreshTasks_.has(groupId)) return;
if (event.kind === 'group_member_join' && !this.qqInfo_.findGroup(groupId)) {
refreshGroupList = true;
}
const task = (async () => {
try {
if (!this.qqInfo_.findGroup(groupId)) {
try { await this.fetchGroupList(); } catch { /* ignore */ }
}
await this.fetchGroupMemberList(groupId);
await this.refreshMemberCache(groupId, refreshGroupList, false);
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
@@ -245,6 +333,62 @@ export class Bridge {
this.memberRefreshTasks_.set(groupId, task);
}
private rememberEventIdentity(event: QQEventVariant): void {
switch (event.kind) {
case 'group_member_join':
this.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_member_leave':
this.identity.markGroupMemberInactive(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_admin':
this.identity.rememberGroupMemberIdentity(event.groupId, {
uin: event.userUin,
});
break;
case 'friend_request':
this.identity.rememberRequestIdentity({
uid: event.fromUid,
uin: event.fromUin,
source: 'friend_request',
});
break;
case 'group_invite':
this.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: event.fromUin,
source: 'group_request',
});
break;
default:
break;
}
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.qqInfo_.findGroup(groupId)) return false;
await this.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
// --- Sequence / random generators ---
private nextClientSequence(): number {
@@ -326,7 +470,7 @@ export class Bridge {
async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
// Resolve UID for image upload (C++ resolves UID before building elems)
// 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) {
@@ -341,6 +485,7 @@ export class Bridge {
routingHead: {
c2c: {
uin: userUin,
...(userUid ? { uid: userUid } : {}),
},
} as any,
contentHead: {
@@ -401,11 +546,11 @@ export class Bridge {
async fetchFriendList(): Promise<FriendInfo[]> { return fetchFriendList_(this); }
async fetchGroupList(): Promise<QQGroupInfo[]> { return fetchGroupList_(this); }
async fetchGroupMemberList(groupId: number): Promise<GroupMemberInfo[]> {
async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> {
const kMemberListTtlMs = 60_000;
const now = Date.now();
const last = this.memberListLastFetch_.get(groupId);
if (last && now - last.at < kMemberListTtlMs) {
if (!options.force && last && now - last.at < kMemberListTtlMs) {
return last.data;
}
const inflight = this.memberListInflight_.get(groupId);
@@ -430,7 +575,10 @@ export class Bridge {
async muteGroupMember(groupId: number, userId: number, duration: number): Promise<void> { return muteGroupMember_(this, groupId, userId, duration); }
async muteGroupAll(groupId: number, enable: boolean): Promise<void> { return muteGroupAll_(this, groupId, enable); }
async setGroupAddOption(groupId: number, addType: number): Promise<void> { return setGroupAddOption_(this, groupId, addType); }
async setGroupSearch(groupId: number): Promise<void> { return setGroupSearch_(this, groupId); }
async kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { return kickGroupMember_(this, groupId, userId, reject, reason); }
async kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> { return kickGroupMembers_(this, groupId, userIds, reject); }
async leaveGroup(groupId: number): Promise<void> { return leaveGroup_(this, groupId); }
async setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void> { return setGroupAdmin_(this, groupId, userId, enable); }
async setGroupCard(groupId: number, userId: number, card: string): Promise<void> { return setGroupCard_(this, groupId, userId, card); }
@@ -468,6 +616,7 @@ export class Bridge {
async markGroupMsgAsRead(groupId: number, sequence: number): Promise<void> { return markGroupMsgAsRead_(this, groupId, sequence); }
async markPrivateMsgAsRead(userId: number, sequence: number): Promise<void> { return markPrivateMsgAsRead_(this, userId, sequence); }
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
async setGroupRemark(groupId: number, remark: string): Promise<void> { return setGroupRemark_(this, groupId, remark); }
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
return getGroupHonorInfo_(this, groupId, type);
}
@@ -488,8 +637,15 @@ export class Bridge {
return getGroupNotice_(this, groupId);
}
async deleteGroupNotice(groupId: number, fid: string): Promise<boolean> {
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<void> {
return setOnlineStatus_(this, status, extStatus, batteryStatus);
@@ -500,7 +656,39 @@ export class Bridge {
async getCookiesStr(domain: string): Promise<string> { return getCookiesStr_(this, domain); }
async getCsrfToken(): Promise<number> { 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<void> {
return setAvatar_(this, source);
}
async fetchCustomFace(count?: number): Promise<string[]> {
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);
}
}
// --- Module-level helper functions ---
@@ -527,6 +715,11 @@ function elementsToText(elements: MessageElement[]): string {
}).join('');
}
function formatEventUser(uin: number, uid?: string): string {
if (uin > 0) return String(uin);
return uid || '未知用户';
}
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message':
@@ -541,10 +734,10 @@ function printEvent(event: QQEventVariant): void {
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.info('入群 %d 加入 %d', event.userUin, event.groupId);
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
break;
case 'group_member_leave':
eventLog.warn('退群 %d %s %d', event.userUin, event.isKick ? '被踢出' : '退出', event.groupId);
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
break;
case 'group_mute':
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);

View File

@@ -15,6 +15,7 @@ import {
} from '../proto/action';
import { uploadImageMsgInfo } from '../highway/image-upload';
import { uploadPttMsgInfo } from '../highway/ptt-upload';
import { uploadVideoMsgInfo } from '../highway/video-upload';
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
@@ -170,10 +171,28 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise<P
};
}
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private video target uid is missing');
}
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: 21,
} as any,
};
}
/**
* Build proto Elem objects from an array of MessageElements.
* Supports: text, face, at, reply, json, xml, markdown, image, record, forward.
* Image and record elements trigger NTV2 highway upload via the SendContext.
* Supports: text, face, at, reply, json, xml, markdown, image, record, video, forward.
* Image, record and video elements trigger NTV2 highway upload via the SendContext.
*/
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
const result: ProtoElem[] = [];
@@ -229,7 +248,11 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
break;
case 'video':
console.warn(`[ElemBuilder] ${elem.type} send not yet implemented`);
if (ctx) {
result.push(await makeVideoElem(ctx, elem));
} else {
console.warn('[ElemBuilder] video send requires SendContext');
}
break;
default:

View File

@@ -18,6 +18,7 @@ export interface MessageElement {
replyTime?: number; // For reply: original message timestamp
replyRandom?: number; // For reply: original message random/msgId
url?: string;
thumbUrl?: string;
subType?: number;
duration?: number;
width?: number;
@@ -97,6 +98,8 @@ export interface GroupMemberJoin extends QQEvent {
groupId: number;
userUin: number;
operatorUin: number;
userUid?: string;
operatorUid?: string;
}
export interface GroupMemberLeave extends QQEvent {
@@ -104,6 +107,8 @@ export interface GroupMemberLeave extends QQEvent {
groupId: number;
userUin: number;
operatorUin: number;
userUid?: string;
operatorUid?: string;
isKick: boolean;
}
@@ -139,6 +144,7 @@ export interface GroupRecallEvent extends QQEvent {
export interface FriendRequestEvent extends QQEvent {
kind: 'friend_request';
fromUin: number;
fromUid?: string;
message: string;
flag: string;
}
@@ -147,6 +153,7 @@ export interface GroupInviteEvent extends QQEvent {
kind: 'group_invite';
groupId: number;
fromUin: number;
fromUid?: string;
subType: string;
message: string;
flag: string;

View File

@@ -597,12 +597,16 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
case PkgType.GroupMemberIncreaseNotice: {
const change = protoDecode(content, GroupChangeSchema);
if (!change) return [];
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
const ev: GroupMemberJoin = {
kind: 'group_member_join', time: timestamp, selfUin,
groupId: change.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
groupId,
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0),
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0),
userUid,
operatorUid,
};
return [ev];
}
@@ -611,12 +615,16 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const change = protoDecode(content, GroupChangeSchema);
if (!change) return [];
const dt = change.decreaseType ?? 0;
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
const ev: GroupMemberLeave = {
kind: 'group_member_leave', time: timestamp, selfUin,
groupId: change.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
groupId,
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0),
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0),
userUid,
operatorUid,
isKick: dt !== 0 && dt !== 130,
};
return [ev];
@@ -643,6 +651,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
kind: 'group_invite', time: timestamp, selfUin,
groupId: join.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, join.groupUin ?? 0, join.targetUid ?? '', fromUin),
fromUid: join.targetUid ?? '',
subType: 'add', message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
};
@@ -657,6 +666,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
kind: 'group_invite', time: timestamp, selfUin,
groupId: inner.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin),
fromUid: inner.invitorUid ?? '',
subType: 'invite', message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
};
@@ -670,6 +680,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
kind: 'group_invite', time: timestamp, selfUin,
groupId: invite.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin),
fromUid: invite.invitorUid ?? '',
subType: 'invite', message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
};
@@ -685,6 +696,7 @@ export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[]
const ev: FriendRequestEvent = {
kind: 'friend_request', time: timestamp, selfUin,
fromUin: resolveUidToUin(qqInfo, 0, sourceUid, fromUin),
fromUid: sourceUid,
message: request.info.message ?? '', flag: sourceUid,
};
return [ev];

View File

@@ -94,12 +94,16 @@ function makeHighwayHead(
}
export function buildHighwayExtend(
uKey: string, msgInfo: any, ipv4s: any[], sha1: Uint8Array,
uKey: string,
msgInfo: any,
ipv4s: any[],
sha1: Uint8Array | Uint8Array[],
fileIndex = 0,
): Uint8Array {
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
const first = msgInfoBody[0];
const selected = msgInfoBody[fileIndex] ?? msgInfoBody[0];
const networkIpv4s: any[] = [];
for (const ipv4 of ipv4s ?? []) {
const ip = ipv4.outIp ?? 0;
@@ -110,14 +114,14 @@ export function buildHighwayExtend(
}
return protoEncode({
fileUuid: first?.index?.fileUuid ?? '',
fileUuid: selected?.index?.fileUuid ?? '',
uKey,
network: { ipv4s: networkIpv4s },
msgInfoBody: msgInfoBody.map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
})),
blockSize: HIGHWAY_BLOCK_SIZE,
hash: { fileSha1: [sha1] },
hash: { fileSha1: Array.isArray(sha1) ? sha1 : [sha1] },
}, NTV2RichMediaHighwayExtSchema);
}

View File

@@ -21,7 +21,7 @@ import {
NTV2UploadRichMediaRespSchema,
EncodableMediaMsgInfoSchema,
} from '../proto/highway';
import { loadBinarySource, computeHashes } from './utils';
import { loadBinarySource, computeHashes, resolveLocalFilePath } from './utils';
import {
fetchHighwaySession,
uploadHighwayHttp,
@@ -49,23 +49,6 @@ interface PttPayload {
cleanups: Array<() => void>;
}
/**
* Decide whether `source` looks like a local filesystem path. The shape
* matches the heuristics used inside `loadBinarySource`: we only reuse the
* caller-supplied path verbatim for things the addon can read directly.
*/
function asLocalFilePath(source: string): string | null {
if (!source) return null;
if (source.startsWith('base64://')) return null;
if (source.startsWith('http://') || source.startsWith('https://')) return null;
let filePath = source;
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
return filePath;
}
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
const source = element.url || element.fileId || '';
if (!source) throw new Error('record source is empty');
@@ -87,7 +70,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
// Resolve the on-disk path the addon should read. Anything that isn't
// already a local file (base64, HTTP) gets staged into the temp dir.
let inputPath: string;
const local = asLocalFilePath(source);
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
inputPath = local;
} else {

View File

@@ -4,6 +4,7 @@
import { createHash } from 'crypto';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
export interface LoadedBinary {
bytes: Uint8Array;
@@ -25,14 +26,42 @@ export interface ImageFormat {
// --- Binary source loading ---
export function resolveLocalFilePath(source: string): string | null {
if (!source) return null;
if (/^base64:\/\//i.test(source)) return null;
if (/^https?:\/\//i.test(source)) return null;
let filePath = source;
if (/^file:\/\//i.test(source)) {
try {
filePath = fileURLToPath(source);
} catch {
filePath = source.replace(/^file:\/+/i, '/');
try {
filePath = decodeURIComponent(filePath);
} catch {
// Keep the original fallback path when percent decoding fails.
}
}
if (process.platform !== 'win32' && filePath.startsWith('//')) {
filePath = filePath.replace(/^\/+/, '/');
}
}
// Windows-style paths can arrive from file:///C:/... as /C:/...
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
return filePath;
}
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
if (!source) throw new Error(`${resourceName} source is empty`);
if (source.startsWith('base64://')) {
if (/^base64:\/\//i.test(source)) {
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
}
if (source.startsWith('http://') || source.startsWith('https://')) {
if (/^https?:\/\//i.test(source)) {
const resp = await fetch(source);
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
const bytes = new Uint8Array(await resp.arrayBuffer());
@@ -40,11 +69,8 @@ export async function loadBinarySource(source: string, resourceName: string): Pr
return { bytes, fileName };
}
// File path (strip file:// prefix)
let filePath = source;
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
// Windows: strip leading / before drive letter
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
const filePath = resolveLocalFilePath(source);
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
const bytes = fs.readFileSync(filePath);
const fileName = path.basename(filePath);

View File

@@ -0,0 +1,520 @@
// Video upload pipeline:
// 1. resolve / fetch the source video and optional thumbnail,
// 2. generate a thumbnail via ffmpegAddon when needed,
// 3. NTV2 OIDB upload request - 0x11EA (group) / 0x11E9 (private),
// 4. highway HTTP upload for video + thumbnail,
// 5. return the encoded `MsgInfo` bytes ready for the commonElem.
//
// Port of NapCat's UploadGroupVideo / UploadPrivateVideo transformers and
// the uploadGroupVideo / uploadC2CVideo paths in PacketHighwayContext.
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { protoEncode, protoDecode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import {
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
EncodableMediaMsgInfoSchema,
} from '../proto/highway';
import {
loadBinarySource,
computeHashes,
detectImageFormat,
resolveLocalFilePath,
} from './utils';
import {
fetchHighwaySession,
uploadHighwayHttp,
buildHighwayExtend,
} from './highway-client';
import { getFFmpegAddon } from './ffmpeg-addon';
import { createLogger } from '../../utils/logger';
const log = createLogger('Video');
export const PRIVATE_VIDEO_CMD_ID = 1001;
export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
export const GROUP_VIDEO_CMD_ID = 1005;
export const GROUP_VIDEO_THUMB_CMD_ID = 1006;
const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
const FALLBACK_THUMB = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
'base64',
);
interface VideoPayload {
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
sha1Blocks: Uint8Array[];
md5Hex: string;
sha1Hex: string;
fileName: string;
filePath: string;
width: number;
height: number;
duration: number;
thumb: ThumbPayload;
cleanups: Array<() => void>;
}
interface ThumbPayload {
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
width: number;
height: number;
}
class Sha1StreamState {
readonly blockSize = 64;
private readonly padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]);
private readonly state = new Uint32Array(5);
private readonly count = new Uint32Array(2);
private readonly buffer = Buffer.allocUnsafe(this.blockSize);
private readonly w = new Uint32Array(80);
constructor() {
this.reset();
}
private reset(): void {
this.state[0] = 0x67452301;
this.state[1] = 0xEFCDAB89;
this.state[2] = 0x98BADCFE;
this.state[3] = 0x10325476;
this.state[4] = 0xC3D2E1F0;
this.count[0] = 0;
this.count[1] = 0;
this.buffer.fill(0);
}
private rotateLeft(value: number, offset: number): number {
return ((value << offset) | (value >>> (32 - offset))) >>> 0;
}
private transform(chunk: Uint8Array, offset: number): void {
const view = new DataView(chunk.buffer, chunk.byteOffset + offset, this.blockSize);
for (let i = 0; i < 16; i++) {
this.w[i] = view.getUint32(i * 4, false);
}
for (let i = 16; i < 80; i++) {
this.w[i] = this.rotateLeft(this.w[i - 3] ^ this.w[i - 8] ^ this.w[i - 14] ^ this.w[i - 16], 1);
}
let a = this.state[0];
let b = this.state[1];
let c = this.state[2];
let d = this.state[3];
let e = this.state[4];
for (let i = 0; i < 80; i++) {
let temp: number;
if (i < 20) {
temp = ((b & c) | (~b & d)) + 0x5A827999;
} else if (i < 40) {
temp = (b ^ c ^ d) + 0x6ED9EBA1;
} else if (i < 60) {
temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC;
} else {
temp = (b ^ c ^ d) + 0xCA62C1D6;
}
temp += (this.rotateLeft(a, 5) + e + this.w[i]) >>> 0;
e = d;
d = c;
c = this.rotateLeft(b, 30);
b = a;
a = temp >>> 0;
}
this.state[0] = (this.state[0] + a) >>> 0;
this.state[1] = (this.state[1] + b) >>> 0;
this.state[2] = (this.state[2] + c) >>> 0;
this.state[3] = (this.state[3] + d) >>> 0;
this.state[4] = (this.state[4] + e) >>> 0;
}
update(data: Uint8Array): void {
let index = (this.count[0] >>> 3) & 0x3F;
const dataLen = data.length;
this.count[0] = (this.count[0] + (dataLen << 3)) >>> 0;
if (this.count[0] < (dataLen << 3)) this.count[1] = (this.count[1] + 1) >>> 0;
this.count[1] = (this.count[1] + (dataLen >>> 29)) >>> 0;
const partLen = this.blockSize - index;
let i = 0;
if (dataLen >= partLen) {
this.buffer.set(data.subarray(0, partLen), index);
this.transform(this.buffer, 0);
for (i = partLen; i + this.blockSize <= dataLen; i += this.blockSize) {
this.transform(data, i);
}
index = 0;
}
if (i < dataLen) {
this.buffer.set(data.subarray(i, dataLen), index);
}
}
hash(bigEndian = true): Uint8Array {
const digest = Buffer.allocUnsafe(20);
for (let i = 0; i < 5; i++) {
if (bigEndian) digest.writeUInt32BE(this.state[i], i * 4);
else digest.writeUInt32LE(this.state[i], i * 4);
}
return new Uint8Array(digest);
}
final(): Uint8Array {
const bits = Buffer.allocUnsafe(8);
bits.writeUInt32BE(this.count[1], 0);
bits.writeUInt32BE(this.count[0], 4);
const index = (this.count[0] >>> 3) & 0x3F;
const padLen = index < 56 ? 56 - index : 120 - index;
this.update(this.padding.subarray(0, padLen));
this.update(bits);
return this.hash(true);
}
}
function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
const sha1 = new Sha1StreamState();
const blocks: Uint8Array[] = [];
let bytesRead = 0;
let offset = 0;
while (offset + sha1.blockSize <= bytes.length) {
const block = bytes.subarray(offset, offset + sha1.blockSize);
sha1.update(block);
offset += sha1.blockSize;
bytesRead += sha1.blockSize;
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
blocks.push(sha1.hash(false));
}
}
if (offset < bytes.length) sha1.update(bytes.subarray(offset));
blocks.push(sha1.final());
return blocks;
}
function defaultVideoTempDir(): string {
return path.join(os.tmpdir(), 'snowluma-video');
}
function sourceExtension(fileName: string, source: string): string {
const fromName = path.extname(fileName);
if (fromName) return fromName;
const local = resolveLocalFilePath(source);
const fromSource = local ? path.extname(local) : '';
return fromSource || '.mp4';
}
function makeClientRandomId(): bigint {
const buf = crypto.randomBytes(8);
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
}
async function stageVideoSource(element: MessageElement, tempDir: string, cleanups: Array<() => void>): Promise<{
bytes: Uint8Array;
filePath: string;
fileName: string;
}> {
const source = element.url || element.fileId || '';
if (!source) throw new Error('video source is empty');
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
return {
bytes: new Uint8Array(fs.readFileSync(local)),
filePath: local,
fileName: element.fileName || path.basename(local),
};
}
const loaded = await loadBinarySource(source, 'video');
const fileName = element.fileName || loaded.fileName || '';
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
cleanups.push(() => { try { fs.unlinkSync(stagedPath); } catch { /* ignore */ } });
return {
bytes: loaded.bytes,
filePath: stagedPath,
fileName,
};
}
async function loadThumb(element: MessageElement, videoPath: string): Promise<{
thumb: ThumbPayload;
width: number;
height: number;
duration: number;
}> {
let width = element.width ?? 0;
let height = element.height ?? 0;
let duration = element.duration ?? 0;
let thumbBytes: Uint8Array | null = null;
if (element.thumbUrl) {
try {
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
} catch (err) {
log.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
}
}
if (!thumbBytes) {
try {
const info = await getFFmpegAddon().getVideoInfo(videoPath);
width = width || info.width || 0;
height = height || info.height || 0;
duration = duration || Math.max(1, Math.round(info.duration || 0));
if (info.image && info.image.length > 0) {
thumbBytes = new Uint8Array(info.image);
}
} catch (err) {
log.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
}
}
if (!thumbBytes) {
thumbBytes = new Uint8Array(FALLBACK_THUMB);
}
const fmt = detectImageFormat(thumbBytes);
width = width || fmt.width || 1;
height = height || fmt.height || 1;
duration = duration || 1;
const hashes = computeHashes(thumbBytes);
return {
width,
height,
duration,
thumb: {
bytes: thumbBytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
width,
height,
},
};
}
async function loadVideo(element: MessageElement): Promise<VideoPayload> {
const tempDir = defaultVideoTempDir();
const cleanups: Array<() => void> = [];
fs.mkdirSync(tempDir, { recursive: true });
try {
const staged = await stageVideoSource(element, tempDir, cleanups);
if (staged.bytes.length === 0) throw new Error('video file is empty');
if (staged.bytes.length > MAX_VIDEO_SIZE) {
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB`);
}
const hashes = computeHashes(staged.bytes);
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
return {
bytes: staged.bytes,
md5: hashes.md5,
sha1: hashes.sha1,
sha1Blocks: computeVideoSha1Blocks(staged.bytes),
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: staged.fileName || `${hashes.md5Hex}.mp4`,
filePath: staged.filePath,
width,
height,
duration,
thumb,
cleanups: [...cleanups],
};
} catch (err) {
for (const fn of cleanups.reverse()) {
try { fn(); } catch { /* best-effort cleanup */ }
}
throw err;
}
}
async function startVideoUpload(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
video: VideoPayload,
): Promise<any> {
const body: any = {
reqHead: {
common: { requestId: 3, command: 100 },
scene: {
requestType: 2,
businessType: 2,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
},
client: { agentType: 2 },
},
upload: {
uploadInfo: [
{
fileInfo: {
fileSize: video.bytes.length,
fileHash: video.md5Hex,
fileSha1: video.sha1Hex,
fileName: 'nya.mp4',
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
height: 0,
width: 0,
time: 0,
original: 0,
},
subFileType: 0,
},
{
fileInfo: {
fileSize: video.thumb.bytes.length,
fileHash: video.thumb.md5Hex,
fileSha1: video.thumb.sha1Hex,
fileName: 'nya.jpg',
type: { type: 1, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
height: video.thumb.height,
width: video.thumb.width,
time: 0,
original: 0,
},
subFileType: 100,
},
],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: makeClientRandomId(),
compatQmsgSceneType: 2,
extBizInfo: {
pic: { bizType: 0, textSummary: 'Nya~' },
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
ptt: {
bytesPbReserve: new Uint8Array(0),
bytesReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
};
const oidbCmd = isGroup ? 0x11EA : 0x11E9;
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x11ea_100' : 'OidbSvcTrpcTcp.0x11e9_100';
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'video upload request failed');
}
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
if (!resp) throw new Error('failed to decode video upload response');
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error('video upload response body missing');
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? 'video upload failed');
}
return uploadBody.upload;
}
function finalizeVideoMsgInfo(upload: any): Uint8Array {
if (!upload?.msgInfo) throw new Error('video upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) extBizInfo.pic = upload.msgInfo.extBizInfo.pic;
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
}
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
}
/**
* Upload a video and return the encoded `MsgInfo` bytes that go inside
* a `commonElem { serviceType: 48, businessType: 21 }`.
*/
export async function uploadVideoMsgInfo(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const video = await loadVideo(element);
try {
const upload = await startVideoUpload(bridge, isGroup, targetIdOrUid, video);
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
const getSession = async () => {
session ??= await fetchHighwaySession(bridge);
return session;
};
const uKey = upload?.uKey ?? '';
if (uKey && upload?.msgInfo) {
log.debug('highway video upload: bytes=%d md5=%s scene=%s', video.bytes.length, video.md5Hex, isGroup ? 'group' : 'c2c');
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], video.sha1Blocks, 0);
const commandId = isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID;
await uploadHighwayHttp(bridge, await getSession(), commandId, video.bytes, video.md5, extend);
} else {
log.debug('video fast-uploaded (server already has md5=%s)', video.md5Hex);
}
const subFile = upload?.subFileInfos?.[0];
if (subFile?.uKey && upload?.msgInfo) {
log.debug('highway video thumb upload: bytes=%d md5=%s scene=%s', video.thumb.bytes.length, video.thumb.md5Hex, isGroup ? 'group' : 'c2c');
const extend = buildHighwayExtend(subFile.uKey, upload.msgInfo, subFile.ipv4s ?? [], video.thumb.sha1, 1);
const commandId = isGroup ? GROUP_VIDEO_THUMB_CMD_ID : PRIVATE_VIDEO_THUMB_CMD_ID;
await uploadHighwayHttp(bridge, await getSession(), commandId, video.thumb.bytes, video.thumb.md5, extend);
} else {
log.debug('video thumb fast-uploaded (server already has md5=%s)', video.thumb.md5Hex);
}
return finalizeVideoMsgInfo(upload);
} finally {
for (const fn of video.cleanups) {
try { fn(); } catch { /* best-effort cleanup */ }
}
}
}

View File

@@ -0,0 +1,758 @@
import fs from 'fs';
import path from 'path';
import { DatabaseSync } from 'node:sqlite';
import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { QQInfo } from './qq-info';
import { createLogger } from '../utils/logger';
const log = createLogger('Identity');
interface UserInput {
uid?: string;
uin?: number;
nickname?: string;
remark?: string;
isFriend?: boolean;
source?: string;
}
interface GroupInput {
groupId: number;
groupName?: string;
remark?: string;
memberCount?: number;
memberMax?: number;
}
interface MemberInput {
groupId: number;
uid?: string;
uin?: number;
nickname?: string;
card?: string;
role?: string;
level?: number;
title?: string;
joinTime?: number;
lastSentTime?: number;
shutUpTime?: number;
active?: boolean;
}
interface UserRow {
id: number;
uid: string | null;
uin: number | null;
nickname: string;
remark: string;
is_friend: number;
source: string;
}
interface MemberRow {
id: number;
group_id: number;
uid: string | null;
uin: number | null;
nickname: string;
card: string;
role: string;
level: number;
title: string;
join_time: number;
last_sent_time: number;
shut_up_time: number;
active: number;
}
export class IdentityService {
private readonly db: DatabaseSync | null;
private readonly uinByUid = new Map<string, number>();
private readonly uidByUin = new Map<number, string>();
private inTransaction = false;
private writeFailed = false;
constructor(
private readonly qqInfo: QQInfo,
dbPath: string | null,
) {
if (!dbPath) {
this.db = null;
return;
}
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.initSchema();
this.loadSnapshot();
}
static openForUin(qqInfo: QQInfo, dataRoot = 'data'): IdentityService {
return new IdentityService(qqInfo, path.join(dataRoot, qqInfo.uin, 'snowluma_identity.db'));
}
static memory(qqInfo: QQInfo): IdentityService {
return new IdentityService(qqInfo, null);
}
close(): void {
this.db?.close();
}
get persistent(): boolean {
return this.db !== null;
}
get hasWriteFailure(): boolean {
return this.writeFailed;
}
rememberFriends(friends: FriendInfo[]): void {
this.qqInfo.setFriends(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')
.run(nowSeconds());
for (const friend of friends) {
this.upsertUser({
uid: friend.uid,
uin: friend.uin,
nickname: friend.nickname,
remark: friend.remark,
isFriend: true,
source: 'friend',
});
}
}));
}
rememberGroups(groups: QQGroupInfo[]): void {
this.qqInfo.setGroups(groups);
this.runWrite('groups', () => this.transaction(() => {
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
.run(nowSeconds());
for (const group of groups) {
this.upsertGroup({
groupId: group.groupId,
groupName: group.groupName,
remark: group.remark,
memberCount: group.memberCount,
memberMax: group.memberMax,
});
}
}));
this.hydrateActiveMembersForGroups(groups.map((group) => group.groupId));
}
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
this.qqInfo.setGroupMembers(groupId, members);
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 = ?')
.run(nowSeconds(), groupId);
for (const member of members) {
this.upsertGroupMember({
groupId,
uid: member.uid,
uin: member.uin,
nickname: member.nickname,
card: member.card,
role: member.role,
level: member.level,
title: member.title,
joinTime: member.joinTime,
lastSentTime: member.lastSentTime,
shutUpTime: member.shutUpTime,
active: true,
});
}
}));
}
rememberUserProfile(info: UserProfileInfo): void {
this.qqInfo.setUserProfile(info);
const selfUin = parseInt(this.qqInfo.uin, 10) || 0;
if (info.uin === selfUin) this.qqInfo.setSelfProfile(info);
this.rememberUidUin(info.uid, info.uin);
this.runWrite('user profile', () => this.transaction(() => this.upsertUser({
uid: info.uid,
uin: info.uin,
nickname: info.nickname,
remark: info.remark,
source: 'profile',
})));
}
rememberGroupRequests(requests: GroupRequestInfo[]): void {
for (const request of requests) {
this.rememberUidUin(request.targetUid, request.targetUin);
this.rememberUidUin(request.invitorUid, request.invitorUin);
this.rememberUidUin(request.operatorUid, request.operatorUin);
}
this.runWrite('group requests', () => this.transaction(() => {
for (const request of requests) {
this.upsertGroup({ groupId: request.groupId, groupName: request.groupName });
this.upsertUser({
uid: request.targetUid,
uin: request.targetUin,
nickname: request.targetName,
source: 'group_request',
});
this.upsertUser({
uid: request.invitorUid,
uin: request.invitorUin,
nickname: request.invitorName,
source: 'group_request',
});
this.upsertUser({
uid: request.operatorUid,
uin: request.operatorUin,
nickname: request.operatorName,
source: 'group_request',
});
}
}));
}
rememberRequestIdentity(
identity: { groupId?: number; uid?: string; uin?: number; nickname?: string; source?: string },
): void {
this.rememberUidUin(identity.uid, identity.uin);
this.runWrite('request identity', () => this.transaction(() => {
if (identity.groupId !== undefined) this.upsertGroup({ groupId: identity.groupId });
this.upsertUser({
uid: identity.uid,
uin: identity.uin,
nickname: identity.nickname,
source: identity.source || 'request',
});
}));
}
rememberGroupMemberIdentity(
groupId: number,
identity: { uid?: string; uin?: number; nickname?: string; card?: string },
): void {
this.rememberUidUin(identity.uid, identity.uin);
this.runWrite('group member identity', () => this.transaction(() => this.upsertGroupMember({
groupId,
uid: identity.uid,
uin: identity.uin,
nickname: identity.nickname,
card: identity.card,
active: true,
})));
}
markGroupMemberInactive(groupId: number, identity: { uid?: string; uin?: number }): void {
this.runWrite('group member inactive', () => {
const uid = normalizeUid(identity.uid);
const uin = normalizeUin(identity.uin);
if (!uid && uin === null) return;
const rows = this.findMemberRows(groupId, uid, uin);
const updatedAt = nowSeconds();
this.transaction(() => {
for (const row of rows) {
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
.run(updatedAt, row.id);
}
});
});
}
findUinByUid(uid: string, groupId?: number): number | null {
const normalized = normalizeUid(uid);
if (!normalized) return null;
if (groupId !== undefined) {
const cached = this.qqInfo.resolveGroupMemberUid(groupId, normalized);
if (cached !== null) return cached;
}
const globalCached = this.qqInfo.resolveUid(normalized);
if (globalCached !== null) return globalCached;
const mapped = this.uinByUid.get(normalized);
if (mapped !== undefined) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uin FROM group_members
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uin: number | null } | undefined;
const uin = normalizeUin(row?.uin);
if (uin !== null) return uin;
}
const row = this.db.prepare(
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
).get(normalized) as { uin: number | null } | undefined;
return normalizeUin(row?.uin);
}
findUidByUin(uin: number, groupId?: number): string | null {
const normalized = normalizeUin(uin);
if (normalized === null) return null;
if (groupId !== undefined) {
const cached = this.qqInfo.findUidByUinInGroup(groupId, normalized);
if (cached) return cached;
}
const globalCached = this.qqInfo.findUidByUin(normalized);
if (globalCached) return globalCached;
const mapped = this.uidByUin.get(normalized);
if (mapped) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uid FROM group_members
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uid: string | null } | undefined;
const uid = normalizeUid(row?.uid);
if (uid) return uid;
}
const row = this.db.prepare(
'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;
}
private rememberUidUin(uid: unknown, uin: unknown): void {
const normalizedUid = normalizeUid(uid);
const normalizedUin = normalizeUin(uin);
if (!normalizedUid || normalizedUin === null) return;
this.uinByUid.set(normalizedUid, normalizedUin);
this.uidByUin.set(normalizedUin, normalizedUid);
}
private initSchema(): void {
this.db!.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uid TEXT UNIQUE,
uin INTEGER UNIQUE,
nickname TEXT NOT NULL DEFAULT '',
remark TEXT NOT NULL DEFAULT '',
is_friend INTEGER NOT NULL DEFAULT 0,
source TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_identity_users_uid ON users(uid);
CREATE INDEX IF NOT EXISTS idx_identity_users_uin ON users(uin);
CREATE TABLE IF NOT EXISTS groups (
group_id INTEGER PRIMARY KEY,
group_name TEXT NOT NULL DEFAULT '',
remark TEXT NOT NULL DEFAULT '',
member_count INTEGER NOT NULL DEFAULT 0,
member_max INTEGER NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 1,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS group_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
group_id INTEGER NOT NULL,
uid TEXT,
uin INTEGER,
nickname TEXT NOT NULL DEFAULT '',
card TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT 'member',
level INTEGER NOT NULL DEFAULT 0,
title TEXT NOT NULL DEFAULT '',
join_time INTEGER NOT NULL DEFAULT 0,
last_sent_time INTEGER NOT NULL DEFAULT 0,
shut_up_time INTEGER NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 1,
updated_at INTEGER NOT NULL,
UNIQUE(group_id, uid),
UNIQUE(group_id, uin)
);
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_active
ON group_members(group_id, active);
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_uid
ON group_members(group_id, uid);
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_uin
ON group_members(group_id, uin);
`);
}
private loadSnapshot(): void {
const friendRows = this.db!.prepare(
`SELECT uid, uin, nickname, remark
FROM users
WHERE is_friend = 1 AND uin IS NOT NULL`,
).all() as Array<{ uid: string | null; uin: number | null; nickname: string; remark: string }>;
this.qqInfo.setFriends(friendRows.map((row) => ({
uid: row.uid ?? '',
uin: row.uin ?? 0,
nickname: row.nickname,
remark: row.remark,
})));
const groups = this.db!.prepare(
`SELECT group_id, group_name, remark, member_count, member_max
FROM groups
WHERE active = 1`,
).all() as Array<{
group_id: number;
group_name: string;
remark: string;
member_count: number;
member_max: number;
}>;
this.qqInfo.setGroups(groups.map((row) => ({
groupId: row.group_id,
groupName: row.group_name,
remark: row.remark,
memberCount: row.member_count,
memberMax: row.member_max,
members: new Map(),
})));
this.hydrateActiveMembersForGroups(groups.map((row) => row.group_id));
}
private hydrateActiveMembersForGroups(groupIds: number[]): void {
if (!this.db || groupIds.length === 0) return;
const membersByGroup = new Map<number, GroupMemberInfo[]>();
const select = this.db.prepare(
`SELECT group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time
FROM group_members
WHERE group_id = ? AND active = 1`,
);
for (const groupId of groupIds) {
const rows = select.all(groupId) as Array<{
group_id: number;
uid: string | null;
uin: number | null;
nickname: string;
card: string;
role: string;
level: number;
title: string;
join_time: number;
last_sent_time: number;
shut_up_time: number;
}>;
membersByGroup.set(groupId, rows.map(rowToMemberInfo));
}
for (const [groupId, members] of membersByGroup) {
this.qqInfo.setGroupMembers(groupId, members);
}
}
private upsertUser(input: UserInput): void {
if (!this.db) return;
const uid = normalizeUid(input.uid);
const uin = normalizeUin(input.uin);
if (!uid && uin === null) return;
const rows = this.findUserRows(uid, uin);
const primary = rows[0];
const merged = {
uid: uid || primary?.uid || null,
uin: uin ?? primary?.uin ?? null,
nickname: normalizeText(input.nickname) || primary?.nickname || '',
remark: normalizeText(input.remark) || primary?.remark || '',
isFriend: input.isFriend === true ? 1 : (primary?.is_friend ?? 0),
source: normalizeText(input.source) || primary?.source || '',
updatedAt: nowSeconds(),
};
if (primary) {
for (const duplicate of rows.slice(1)) {
this.db.prepare('DELETE FROM users WHERE id = ?').run(duplicate.id);
}
this.db.prepare(
`UPDATE users
SET uid = ?, uin = ?, nickname = ?, remark = ?, is_friend = ?, source = ?, updated_at = ?
WHERE id = ?`,
).run(
merged.uid,
merged.uin,
merged.nickname,
merged.remark,
merged.isFriend,
merged.source,
merged.updatedAt,
primary.id,
);
return;
}
this.db.prepare(
`INSERT INTO users (uid, uin, nickname, remark, is_friend, source, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
).run(
merged.uid,
merged.uin,
merged.nickname,
merged.remark,
merged.isFriend,
merged.source,
merged.updatedAt,
);
}
private upsertGroup(input: GroupInput): void {
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
const existing = this.db.prepare(
'SELECT group_name, remark, member_count, member_max FROM groups WHERE group_id = ?',
).get(input.groupId) as {
group_name: string;
remark: string;
member_count: number;
member_max: number;
} | undefined;
this.db.prepare(
`INSERT INTO groups (group_id, group_name, remark, member_count, member_max, active, updated_at)
VALUES (?, ?, ?, ?, ?, 1, ?)
ON CONFLICT(group_id) DO UPDATE SET
group_name = excluded.group_name,
remark = excluded.remark,
member_count = excluded.member_count,
member_max = excluded.member_max,
active = 1,
updated_at = excluded.updated_at`,
).run(
input.groupId,
normalizeText(input.groupName) || existing?.group_name || '',
normalizeText(input.remark) || existing?.remark || '',
normalizeNonNegative(input.memberCount, existing?.member_count ?? 0),
normalizeNonNegative(input.memberMax, existing?.member_max ?? 0),
nowSeconds(),
);
}
private upsertGroupMember(input: MemberInput): void {
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
const uid = normalizeUid(input.uid);
const uin = normalizeUin(input.uin);
if (!uid && uin === null) return;
this.upsertGroup({ groupId: input.groupId });
this.upsertUser({
uid,
uin: uin ?? undefined,
nickname: input.nickname,
source: 'group_member',
});
const rows = this.findMemberRows(input.groupId, uid, uin);
const primary = rows[0];
const merged = {
uid: uid || primary?.uid || null,
uin: uin ?? primary?.uin ?? null,
nickname: normalizeText(input.nickname) || primary?.nickname || '',
card: normalizeText(input.card) || primary?.card || '',
role: normalizeText(input.role) || primary?.role || 'member',
level: normalizeNonNegative(input.level, primary?.level ?? 0),
title: normalizeText(input.title) || primary?.title || '',
joinTime: normalizeNonNegative(input.joinTime, primary?.join_time ?? 0),
lastSentTime: normalizeNonNegative(input.lastSentTime, primary?.last_sent_time ?? 0),
shutUpTime: normalizeNonNegative(input.shutUpTime, primary?.shut_up_time ?? 0),
active: input.active === false ? 0 : input.active === true ? 1 : (primary?.active ?? 1),
updatedAt: nowSeconds(),
};
if (primary) {
for (const duplicate of rows.slice(1)) {
this.db.prepare('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
}
this.db.prepare(
`UPDATE group_members
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ?
WHERE id = ?`,
).run(
merged.uid,
merged.uin,
merged.nickname,
merged.card,
merged.role,
merged.level,
merged.title,
merged.joinTime,
merged.lastSentTime,
merged.shutUpTime,
merged.active,
merged.updatedAt,
primary.id,
);
return;
}
this.db.prepare(
`INSERT INTO group_members
(group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
input.groupId,
merged.uid,
merged.uin,
merged.nickname,
merged.card,
merged.role,
merged.level,
merged.title,
merged.joinTime,
merged.lastSentTime,
merged.shutUpTime,
merged.active,
merged.updatedAt,
);
}
private findUserRows(uid: string, uin: number | null): UserRow[] {
if (!this.db) return [];
if (uid && uin !== null) {
return this.db.prepare(
'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(
'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(
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uin = ? ORDER BY id',
).all(uin) as unknown as UserRow[];
}
return [];
}
private findMemberRows(groupId: number, uid: string, uin: number | null): MemberRow[] {
if (!this.db) return [];
if (uid && uin !== null) {
return this.db.prepare(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
FROM group_members
WHERE group_id = ? AND (uid = ? OR uin = ?)
ORDER BY id`,
).all(groupId, uid, uin) as unknown as MemberRow[];
}
if (uid) {
return this.db.prepare(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
FROM group_members
WHERE group_id = ? AND uid = ?
ORDER BY id`,
).all(groupId, uid) as unknown as MemberRow[];
}
if (uin !== null) {
return this.db.prepare(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
FROM group_members
WHERE group_id = ? AND uin = ?
ORDER BY id`,
).all(groupId, uin) as unknown as MemberRow[];
}
return [];
}
private transaction<T>(fn: () => T): T {
if (!this.db || this.inTransaction) return fn();
this.inTransaction = true;
this.db.exec('BEGIN');
try {
const result = fn();
this.db.exec('COMMIT');
return result;
} catch (err) {
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
throw err;
} finally {
this.inTransaction = false;
}
}
private runWrite(label: string, fn: () => void): void {
if (!this.db) return;
try {
fn();
} catch (err) {
this.writeFailed = true;
log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
}
}
}
function rowToMemberInfo(row: {
uid: string | null;
uin: number | null;
nickname: string;
card: string;
role: string;
level: number;
title: string;
join_time: number;
last_sent_time: number;
shut_up_time: number;
}): GroupMemberInfo {
return {
uid: row.uid ?? '',
uin: row.uin ?? 0,
nickname: row.nickname,
card: row.card,
role: row.role || 'member',
level: row.level,
title: row.title,
joinTime: row.join_time,
lastSentTime: row.last_sent_time,
shutUpTime: row.shut_up_time,
};
}
function normalizeUid(uid: unknown): string {
return typeof uid === 'string' ? uid.trim() : '';
}
function normalizeUin(uin: unknown): number | null {
if (typeof uin === 'number' && Number.isFinite(uin)) {
const n = Math.trunc(uin);
return n > 0 ? n : null;
}
if (typeof uin === 'string' && uin.trim()) {
const parsed = Number(uin);
if (Number.isFinite(parsed)) {
const n = Math.trunc(parsed);
return n > 0 ? n : null;
}
}
return null;
}
function normalizeText(value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
}
function normalizeNonNegative(value: unknown, fallback: number): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
return fallback;
}
function nowSeconds(): number {
return Math.floor(Date.now() / 1000);
}

View File

@@ -5,6 +5,7 @@
import type { NtqqHandler } from '../protocol/ntqq-handler';
import type { PacketInfo } from '../protocol/types';
import { Bridge } from './bridge';
import { IdentityService } from './identity-service';
import { QQInfo } from './qq-info';
import type { PacketSender } from '../protocol/packet-sender';
import { createLogger } from '../utils/logger';
@@ -48,6 +49,7 @@ export class BridgeManager {
this.sessions_.delete(uin);
log.debug('session closed: UIN=%s', uin);
if (this.onSessionClosed_) this.onSessionClosed_(uin);
session.bridge.dispose();
}
}
@@ -107,7 +109,7 @@ export class BridgeManager {
if (session) return { session, created: false };
const qqInfo = new QQInfo(uin);
const bridge = new Bridge(qqInfo);
const bridge = new Bridge(qqInfo, IdentityService.openForUin(qqInfo));
session = { qqInfo, bridge };
this.sessions_.set(uin, session);

View File

@@ -28,6 +28,26 @@ export const OidbMuteAllSchema = {
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 = {
@@ -862,4 +882,242 @@ 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;
} 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;

View File

@@ -12,7 +12,7 @@ import {
import { RequestUtil } from './web/request-util';
import { getHonorListWebAPI, WebHonorType } from './web/group-honor';
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from './web/group-essence';
import { setGroupNoticeWebAPI, getGroupNoticeWebAPI } from './web/group-notice';
import { setGroupNoticeWebAPI, getGroupNoticeWebAPI, uploadGroupNoticeImage, deleteGroupNotice } from './web/group-notice';
export async function forceFetchClientKey(bridge: Bridge) {
const resp = await sendOidbAndDecode<any>(
@@ -189,15 +189,25 @@ export async function sendGroupNotice(
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);
}
// if (options?.image) {
// const picInfo = await bridge.uploadGroupBulletinPic(groupCode, options.image);
// picId = picInfo.id;
// imgWidth = picInfo.width;
// imgHeight = picInfo.height;
// }
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
if (picInfo) {
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
@@ -261,6 +271,12 @@ export async function getGroupNotice(bridge: Bridge, groupId: number) {
return retNotices;
}
export async function deleteGroupNoticeByFid(bridge: Bridge, groupId: number, fid: string): Promise<boolean> {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNotice(cookieObject, groupCode, fid);
}
/**
* 提取的公共算法:根据 skey/p_skey 计算 bkn (也就是 token / csrf_token)
*/

View File

@@ -1,4 +1,7 @@
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
import { RequestUtil, cookieToString } from './request-util';
import https from 'node:https';
// import { readFileSync } from 'node:fs';
// import * as console from "node:console";
export interface SetNoticeRetSuccess {
ec?: number;
@@ -6,6 +9,12 @@ export interface SetNoticeRetSuccess {
[key: string]: any;
}
export interface UploadImageRetSuccess {
ec?: number;
id?: string;
[key: string]: any;
}
export interface WebApiGroupNoticeFeed {
fid: string;
u: number;
@@ -26,6 +35,14 @@ export interface WebApiGroupNoticeRet {
[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
@@ -44,33 +61,54 @@ export async function setGroupNoticeWebAPI(
imgHeight: number = 300
): Promise<SetNoticeRetSuccess | undefined> {
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 externalParam = {
pic: picId,
imgWidth: imgWidth.toString(),
imgHeight: imgHeight.toString(),
};
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?${new URLSearchParams({
bkn: getBknFromCookie(cookieObject),
const bodyParams: Record<string, string> = {
qid: groupCode,
bkn: bodyBkn,
text: content,
pinned: pinned.toString(),
type: type.toString(),
settings,
...(picId === '' ? {} : externalParam),
}).toString()}`;
};
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<SetNoticeRetSuccess>(
url,
'POST', // 注意这里必须是 POST
'',
{ Cookie: cookieToString(cookieObject) }
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret;
} catch (e) {
@@ -78,35 +116,151 @@ export async function setGroupNoticeWebAPI(
}
}
/**
* 获取群公告列表 Web API
*/
export async function getGroupNoticeWebAPI(
cookieObject: Record<string, string>,
groupCode: string
groupCode: string,
start: number = -1, // -1 表示第一页
count: number = 20 // 抓包中是 10,你可以根据需要调整
): Promise<WebApiGroupNoticeRet | undefined> {
const bkn = getBknFromCookie(cookieObject);
const params = new URLSearchParams({
bkn: bkn,
qid: groupCode,
ft: '23',
ni: '1',
i: '1',
log_read: '1',
platform: '1',
s: '-1',
}).toString();
const url = `https://web.qun.qq.com/cgi-bin/announce/get_t_list?${params}&n=20`;
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<WebApiGroupNoticeRet>(
url,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
'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 {
return undefined;
}
}
/**
* 上传群公告图片 Web API
*/
export async function uploadGroupNoticeImage(
cookieObject: Record<string, string>,
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(/&quot;/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', () => resolve(undefined));
req.write(body);
req.end();
});
} catch {
return undefined;
}
}
/**
* 删除群公告 Web API
*/
export async function deleteGroupNotice(
cookieObject: Record<string, string>,
groupCode: string,
fid: string
): Promise<boolean> {
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<SetNoticeRetSuccess>(
url,
'POST',
params,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret?.ec === 0;
} catch {
return false;
}
}

View File

@@ -76,9 +76,7 @@ export class HookManager {
async listProcesses(): Promise<HookProcessInfo[]> {
const processes = listHookProcesses();
const seen = new Set<number>();
for (const proc of processes) {
seen.add(proc.pid);
const state = this.ensureState(proc.pid);
state.name = proc.name || state.name;
state.path = proc.path || state.path;
@@ -87,11 +85,6 @@ export class HookManager {
for (const proc of processes) {
result.push(this.toPublicInfo(this.ensureState(proc.pid)));
}
for (const state of this.states.values()) {
if (!seen.has(state.pid) && (state.injected || state.client)) {
result.push(this.toPublicInfo(state));
}
}
return result.sort((a, b) => a.pid - b.pid);
}
@@ -316,6 +309,7 @@ export class HookManager {
try {
const livePipes = await QqHookClient.listLivePipes();
const processes = listHookProcesses();
const runningSet = new Set(processes.map(p => p.pid));
// Refresh metadata + ensure a state entry exists for each known PID.
for (const proc of processes) {
@@ -325,6 +319,7 @@ export class HookManager {
}
// Auto-detect hooks that survived a SnowLuma restart or failed unload.
for (const pid of livePipes) {
if (!runningSet.has(pid)) continue;
const state = this.ensureState(pid);
if (!state.injected) {
state.injected = true;
@@ -334,14 +329,15 @@ export class HookManager {
}
}
const runningSet = new Set(processes.map(p => p.pid));
const tasks: Promise<unknown>[] = [];
for (const state of [...this.states.values()]) {
const alivePipe = livePipes.has(state.pid);
const aliveProc = runningSet.has(state.pid);
// Reap stale state entries that have nothing left to do.
if (!aliveProc && !alivePipe && !state.injected && !state.client) {
if (!aliveProc) {
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(state.pid);
this.states.delete(state.pid);
continue;
}

View File

@@ -9,6 +9,7 @@ export const PIPE_VERSION = 1;
export const HEADER_SIZE = 40;
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
export enum PipeOp {
hello = 1,
@@ -102,6 +103,63 @@ function mojoPipeName(pid: number, suffix: string): string {
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
}
type LinuxPipeProbe = (socketPath: string) => Promise<boolean>;
async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
try {
const stat = await fs.stat(socketPath);
if (!stat.isSocket()) return false;
} catch {
return false;
}
return new Promise<boolean>((resolve) => {
let socket: net.Socket;
try {
socket = net.createConnection(socketPath);
} catch {
resolve(false);
return;
}
let done = false;
let timer: NodeJS.Timeout;
const finish = (ok: boolean) => {
if (done) return;
done = true;
clearTimeout(timer);
socket.removeAllListeners();
socket.destroy();
resolve(ok);
};
timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS);
socket.once('connect', () => finish(true));
socket.once('error', () => finish(false));
});
}
export async function listLiveLinuxPipePids(
runtimeDir = linuxRuntimeDir(),
probe: LinuxPipeProbe = isConnectableUnixSocket,
): Promise<Set<number>> {
const result = new Set<number>();
let names: string[];
try {
names = await fs.readdir(runtimeDir);
} catch {
return result;
}
await Promise.all(names.map(async (name) => {
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
if (!m) return;
const pid = Number(m[1]);
if (!Number.isInteger(pid) || pid <= 0) return;
if (await probe(path.join(runtimeDir, name))) result.add(pid);
}));
return result;
}
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
if (Buffer.isBuffer(body)) return body;
if (body instanceof Uint8Array) return Buffer.from(body);
@@ -312,11 +370,7 @@ export class QqHookClient extends EventEmitter {
if (m) result.add(Number(m[1]));
}
} else {
const names = await fs.readdir(linuxRuntimeDir());
for (const name of names) {
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
if (m) result.add(Number(m[1]));
}
return await listLiveLinuxPipePids();
}
} catch {
/* directory missing or inaccessible — treat as no live pipes */

View File

@@ -239,16 +239,13 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and content are required');
}
if (image) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented: image upload for group notice is not supported yet');
}
if (!ctx.sendGroupNotice) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const options = {
image: image || undefined,
pinned: params.pinned !== undefined ? Number(params.pinned) : 0,
type: params.type !== undefined ? Number(params.type) : 1,
confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1,
@@ -277,8 +274,28 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
});
h.registerAction('_del_group_notice', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('_del_group_notice', async (params) => {
const groupId = asNumber(params.group_id);
const fid = asString(params.fid) || asString(params.notice_id);
if (!groupId || !fid) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and fid/notice_id are required');
}
if (!ctx.deleteGroupNotice) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const success = await ctx.deleteGroupNotice(groupId, fid);
if (success) {
return okResponse();
} else {
return failedResponse(RETCODE.ACTION_FAILED, 'delete failed');
}
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
// --- Forward messages ---
@@ -477,6 +494,15 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
h.registerAction('set_group_remark', async (params) => {
const groupId = asNumber(params.group_id);
const remark = asString(params.remark) ?? '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.setGroupRemark) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupRemark(groupId, remark);
return okResponse();
});
h.registerAction('set_msg_emoji_like', async (params) => {
const messageId = asNumber(params.message_id);
const emojiId = asString(params.emoji_id);
@@ -605,12 +631,79 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
// todo 我的建议是引入数据库api 纯协议我不知道这种api怎么实现,ntQQ在实现这个方法的时候只进行了数据库查询,完全没碰网络
h.registerAction('get_recent_contact', async () => {
return okResponse([]);
});
h.registerAction('get_profile_like', async () => {
return okResponse({});
h.registerAction('get_profile_like', async (params) => {
const userId = asNumber(params.user_id);
const start = asNumber(params.start) || 0;
const count = asNumber(params.count) || 10;
if (!ctx.getProfileLike) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getProfileLike(userId, start, count);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('fetch_custom_face', async (params) => {
const count = asNumber(params.count) || 10;
if (!ctx.fetchCustomFace) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const urls = await ctx.fetchCustomFace(count);
return okResponse(urls);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_emoji_likes', async (params) => {
const messageId = asNumber(params.message_id);
const emojiId = asString(params.emoji_id) || '';
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
if (!ctx.getEmojiLikes) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
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.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));
}
});
h.registerAction('fetch_emoji_like', async (params) => {
const messageId = asNumber(params.message_id);
const emojiId = asString(params.emojiId) || '';
const emojiType = asNumber(params.emojiType) || 1;
const count = asNumber(params.count) || 10;
const cookie = asString(params.cookie) || '';
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emojiId are required');
if (!ctx.getEmojiLikes) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
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.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie);
return okResponse({
result: 0,
errMsg: '',
emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })),
cookie: result.cookie,
isLastPage: result.isLast,
isFirstPage: !cookie,
});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_friends_with_category', async () => {
@@ -622,6 +715,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
// --- Additional NapCat-compatible stubs ---
///napcat 似乎也用不了??,暂时不管了
h.registerAction('get_online_clients', async () => {
return okResponse({ clients: [] });
});
@@ -638,16 +732,55 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_group_at_all_remain', async () => {
return okResponse({ can_at_all: false, remain_at_all_count_for_group: 0, remain_at_all_count_for_uin: 0 });
h.registerAction('get_group_at_all_remain', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id');
}
if (!ctx.getGroupAtAllRemain) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getGroupAtAllRemain(groupId);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_unidirectional_friend_list', async () => {
return okResponse([]);
if (!ctx.getUnidirectionalFriendList) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getUnidirectionalFriendList();
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('set_self_longnick', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('set_self_longnick', async (params) => {
const longNick = params.longNick || params.long_nick;
if (typeof longNick !== 'string') {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick');
}
if (!ctx.setSelfLongNick) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setSelfLongNick(longNick);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_collection_list', async () => {
@@ -658,16 +791,66 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('set_qq_avatar', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('set_qq_avatar', async (params) => {
const file = asString(params.file);
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
if (!ctx.setAvatar) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setAvatar(file);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('set_input_status', async () => {
return okResponse();
h.registerAction('set_input_status', async (params) => {
const userId = asNumber(params.user_id);
const eventType = asNumber(params.event_type);
if (!userId) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid user_id');
}
// event_type 有可能是 0 (取消输入状态),所以这里严格判断 undefined 或 isNaN
if (eventType === undefined || isNaN(eventType)) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid event_type');
}
if (!ctx.setInputStatus) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setInputStatus(userId, eventType);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('translate_en2zh', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('translate_en2zh', async (params) => {
const rawWords = params.words;
if (!Array.isArray(rawWords)) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array');
}
const words = rawWords.map(w => String(w));
if (!ctx.translateEn2Zh) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const translated = await ctx.translateEn2Zh(words);
return okResponse({ words: translated });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_clientkey', async () => {
@@ -681,21 +864,81 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse(clientKeyInfo);
});
h.registerAction('get_mini_app_ark', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('get_mini_app_ark', async (params) => {
const type = params.type || 'bili';
const title = params.title || '';
const desc = params.desc || '';
const picUrl = params.picUrl || params.pic_url || '';
const jumpUrl = params.jumpUrl || params.jump_url || '';
if (!ctx.getMiniAppArk) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getMiniAppArk(
String(type),
String(title),
String(desc),
String(picUrl),
String(jumpUrl)
);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('click_inline_keyboard_button', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('click_inline_keyboard_button', async (params) => {
const groupId = asNumber(params.group_id);
const botAppid = asNumber(params.bot_appid);
const buttonId = params.button_id;
const callbackData = params.callback_data || '';
const msgSeq = asNumber(params.msg_seq);
if (!groupId || !botAppid || !buttonId || !msgSeq) {
return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters');
}
if (!ctx.clickInlineKeyboardButton) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.clickInlineKeyboardButton(
groupId,
botAppid,
String(buttonId),
String(callbackData),
msgSeq
);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('set_group_sign', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
const handleGroupSign = async (params: any) => {
const groupId = asNumber(params.group_id);
h.registerAction('send_group_sign', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id');
}
if (!ctx.sendGroupSign) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.sendGroupSign(groupId);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
};
h.registerAction('set_group_sign', handleGroupSign);
h.registerAction('send_group_sign', handleGroupSign);
h.registerAction('get_group_info_ex', async (params) => {
const groupId = asNumber(params.group_id);

View File

@@ -13,6 +13,16 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
h.registerAction('set_group_kick_members', async (params) => {
const groupId = asNumber(params.group_id);
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');
if (!ctx.setGroupKickMembers) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupKickMembers(groupId, userIds, reject);
return okResponse();
});
h.registerAction('set_group_ban', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
@@ -32,6 +42,23 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
h.registerAction('set_group_add_option', async (params) => {
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');
if (!ctx.setGroupAddOption) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupAddOption(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');
if (!ctx.setGroupSearch) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupSearch(groupId);
return okResponse();
});
h.registerAction('set_group_admin', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);

View File

@@ -48,13 +48,17 @@ export interface ApiActionContext {
getStrangerInfo?: (userId: number) => Promise<JsonObject | null>;
// Group admin
setGroupKick?: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
setGroupKickMembers?: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>;
setGroupBan?: (groupId: number, userId: number, duration: number) => Promise<void>;
setGroupWholeBan?: (groupId: number, enable: boolean) => Promise<void>;
setGroupAddOption?: (groupId: number, addType: number) => Promise<void>;
setGroupSearch?: (groupId: number) => Promise<void>;
setGroupAdmin?: (groupId: number, userId: number, enable: boolean) => Promise<void>;
setGroupCard?: (groupId: number, userId: number, card: string) => Promise<void>;
setGroupName?: (groupId: number, name: string) => Promise<void>;
setGroupLeave?: (groupId: number) => Promise<void>;
setGroupSpecialTitle?: (groupId: number, userId: number, title: string) => Promise<void>;
getGroupAtAllRemain?: (groupId: number) => Promise<any>;
// Group file
uploadGroupFile?: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
uploadPrivateFile?: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
@@ -78,6 +82,13 @@ export interface ApiActionContext {
forceFetchClientKey? : () => Promise<{clientKey: string, keyIndex: string, expireTime: string}>;
setOnlineStatus?: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile?: (nickname?: string, personalNote?: string) => Promise<void>;
getUnidirectionalFriendList?: () => Promise<any>;
setSelfLongNick?: (longNick: string) => Promise<void>;
setInputStatus?: (userId: number, eventType: number) => Promise<void>;
translateEn2Zh?: (words: string[]) => Promise<string[]>;
getMiniAppArk?: (type: string, title: string, desc: string, picUrl: string, jumpUrl: string) => Promise<any>;
clickInlineKeyboardButton?: (groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) => Promise<any>;
sendGroupSign?: (groupId: number) => Promise<void>;
// New context methods
setGroupReaction?: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
handleDeleteFriend?: (userId: number, block?: boolean) => Promise<void>;
@@ -92,22 +103,29 @@ export interface ApiActionContext {
getForwardMsg?: (resId: string) => Promise<JsonObject[]>;
// Extended NapCat-compatible
setFriendRemark?: (userId: number, remark: string) => Promise<void>;
setGroupRemark?: (groupId: number, remark: string) => Promise<void>;
getGroupFileCount?: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
markGroupMsgAsRead?: (groupId: number, sequence: number) => Promise<void>;
markPrivateMsgAsRead?: (userId: number, sequence: number) => Promise<void>;
getProfileLike?: (userId?: number, start?: number, limit?: number) => Promise<any>;
fetchCustomFace?: (count?: number) => Promise<string[]>;
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<any>;
getGroupEssence?: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
getGroupEssenceAll?: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
sendGroupNotice?: (groupId: number, content: string, options?: any) => Promise<any>;
getGroupNotice?: (groupId: number) => Promise<any[]>;
deleteGroupNotice?: (groupId: number, fid: string) => Promise<boolean>;
getCookiesStr?: (domain: string) => Promise<string>;
getCsrfToken?: () => Promise<number>;
getCredentials?: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
// Media lookup (populated from previously dispatched message segments)
getImageInfo?: (file: string) => Promise<JsonObject | null>;
getRecordInfo?: (file: string) => Promise<JsonObject | null>;
// Avatar
setAvatar?: (source: string) => Promise<void>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;

View File

@@ -135,7 +135,7 @@ export class EventConverter {
self_id: selfId,
post_type: 'notice',
notice_type: 'group_increase',
sub_type: event.operatorUin === event.userUin ? 'approve' : 'invite',
sub_type: isSameActor(event.operatorUin, event.operatorUid, event.userUin, event.userUid) ? 'approve' : 'invite',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
@@ -330,6 +330,11 @@ function parseSelfId(instanceUin: string): number {
return Number.isNaN(parsed) ? 0 : parsed;
}
function isSameActor(leftUin: number, leftUid: string | undefined, rightUin: number, rightUid: string | undefined): boolean {
if (leftUin > 0 && rightUin > 0) return leftUin === rightUin;
return Boolean(leftUid) && leftUid === rightUid;
}
async function elementsToJson(
elements: MessageElement[],
isGroup: boolean,

View File

@@ -72,13 +72,17 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getStrangerInfo: (userId) => handleGetStrangerInfo(bridge, qqInfo, userId),
// Group admin
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
setGroupKickMembers: (groupId, userIds, reject) => bridge.kickGroupMembers(groupId, userIds, reject),
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable),
setGroupAddOption: (groupId, addType) => bridge.setGroupAddOption(groupId, addType),
setGroupSearch: (groupId) => bridge.setGroupSearch(groupId),
setGroupAdmin: (groupId, userId, enable) => bridge.setGroupAdmin(groupId, userId, enable),
setGroupCard: (groupId, userId, card) => bridge.setGroupCard(groupId, userId, card),
setGroupName: (groupId, name) => bridge.setGroupName(groupId, name),
setGroupLeave: (groupId) => bridge.leaveGroup(groupId),
setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title),
getGroupAtAllRemain: (groupId) => bridge.getGroupAtAllRemain(groupId),
// Group file
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
@@ -105,6 +109,16 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
setEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, false),
getProfileLike: (userId?: number, start: number = 0, limit: number = 10) => bridge.getProfileLike(userId, start, limit),
fetchCustomFace: (count?: number) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
getUnidirectionalFriendList: () => bridge.getUnidirectionalFriendList(),
setSelfLongNick: (longNick) => bridge.setSelfLongNick(longNick),
setInputStatus: (userId, eventType) => bridge.setInputStatus(userId, eventType),
translateEn2Zh: (words) => bridge.translateEn2Zh(words),
getMiniAppArk: (type, title, desc, picUrl, jumpUrl) => bridge.getMiniAppArk(type, title, desc, picUrl, jumpUrl),
clickInlineKeyboardButton: (groupId, botAppid, buttonId, callbackData, msgSeq) => bridge.clickInlineKeyboardButton(groupId, botAppid, buttonId, callbackData, msgSeq),
sendGroupSign: (groupId) => bridge.sendGroupSign(groupId),
// New extended
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
@@ -145,6 +159,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
// Extended NapCat-compatible
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark),
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
setMsgEmojiLike: async (messageId, emojiId, set) => {
const meta = messageStore.findMeta(messageId);
@@ -161,12 +176,15 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getGroupEssenceAll: (groupId: number) => bridge.getGroupEssenceAll(groupId),
sendGroupNotice: (groupId: number, content: string, options?: any) => bridge.sendGroupNotice(groupId, content, options),
getGroupNotice: (groupId: number) => bridge.getGroupNotice(groupId),
deleteGroupNotice: (groupId: number, fid: string) => bridge.deleteGroupNotice(groupId, fid),
getCookiesStr: (domain: string) => bridge.getCookiesStr(domain),
getCsrfToken: () => bridge.getCsrfToken(),
getCredentials: (domain: string) => bridge.getCredentials(domain),
// Media lookup
getImageInfo: (file) => handleGetImageInfo(mediaStore, file),
getRecordInfo: (file) => handleGetRecordInfo(bridge, mediaStore, file),
// Avatar
setAvatar: (source: string) => bridge.setAvatar(source),
};
}

View File

@@ -14,7 +14,7 @@ export interface ParseMessageOptions {
// --- CQ Code parsing ---
const CQ_REGEX = /\[CQ:([a-z]+)(?:,([^\]]*))?\]/g;
const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
@@ -71,6 +71,7 @@ async function parseFromCQString(message: string, options?: ParseMessageOptions)
interface MessageSegment {
type: string;
data?: Record<string, unknown>;
[key: string]: unknown;
}
function isSegmentArray(val: unknown): val is MessageSegment[] {
@@ -80,7 +81,8 @@ function isSegmentArray(val: unknown): val is MessageSegment[] {
}
async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
switch (type) {
const normalizedType = type.toLowerCase();
switch (normalizedType) {
case 'text': {
const text = String(data.text ?? '');
return text ? { type: 'text', text } : null;
@@ -143,14 +145,14 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
case 'image': {
return {
type: 'image',
url: String(data.file ?? data.url ?? ''),
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
flash: data.type === 'flash',
subType: parseInt(String(data.subType ?? '0'), 10),
summary: data.summary ? String(data.summary) : undefined,
};
}
case 'record': {
const source = String(data.file ?? data.url ?? data.path ?? '');
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
if (!source) return null;
return {
type: 'record',
@@ -158,9 +160,12 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
};
}
case 'video': {
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
if (!source) return null;
return {
type: 'video',
url: String(data.file ?? data.url ?? ''),
url: source,
thumbUrl: data.thumb ? String(data.thumb) : undefined,
};
}
case 'json': {
@@ -317,6 +322,16 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
}
}
function segmentPayload(seg: MessageSegment): Record<string, unknown> {
const topLevel = { ...seg } as Record<string, unknown>;
delete topLevel.type;
delete topLevel.data;
const nested = (seg.data && typeof seg.data === 'object' && !Array.isArray(seg.data))
? seg.data
: {};
return { ...topLevel, ...nested };
}
// --- Public API ---
/**
@@ -338,7 +353,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti
if (isSegmentArray(message)) {
const elements: MessageElement[] = [];
for (const seg of message) {
const data = (seg.data ?? {}) as Record<string, unknown>;
const data = segmentPayload(seg);
const elem = await segmentToElement(seg.type, data, options);
if (elem) elements.push(elem);
}
@@ -349,7 +364,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
const seg = message as unknown as MessageSegment;
if (seg.type) {
const data = (seg.data ?? {}) as Record<string, unknown>;
const data = segmentPayload(seg);
const elem = await segmentToElement(seg.type, data, options);
return elem ? [elem] : [];
}

View File

@@ -0,0 +1,143 @@
import { describe, expect, it } from 'vitest';
import { Bridge } from '../src/bridge/bridge';
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
import type { GroupMemberJoin, QQEventVariant } from '../src/bridge/events';
import type { PacketInfo } from '../src/protocol/types';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
function makeGroupMember(uin: number, uid: string): GroupMemberInfo {
return {
uin,
uid,
nickname: '',
card: '',
role: 'member',
level: 0,
title: '',
joinTime: 0,
lastSentTime: 0,
shutUpTime: 0,
};
}
function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
return {
groupId: GROUP_ID,
groupName: '',
remark: '',
memberCount: members.length,
memberMax: 500,
members: new Map(members.map((member) => [member.uin, member])),
};
}
class RefreshingBridge extends Bridge {
readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
constructor(qqInfo: QQInfo, private readonly refreshedMembers: GroupMemberInfo[]) {
super(qqInfo);
}
override async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> {
this.memberFetches.push({ groupId, force: Boolean(options.force) });
for (const member of this.refreshedMembers) {
this.qqInfo.updateGroupMember(groupId, member);
}
return this.refreshedMembers;
}
}
function makePacket(): PacketInfo {
return {
pid: 1,
uin: SELF_UIN,
serviceCmd: 'test.member_join',
seqId: 1,
retCode: 0,
fromClient: false,
body: new Uint8Array(0),
};
}
function makeRequestPacket(): PacketInfo {
return {
...makePacket(),
serviceCmd: 'test.request_identity',
};
}
async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin> {
for (let i = 0; i < 10; i++) {
if (events[0]) return events[0];
await new Promise((resolve) => setTimeout(resolve, 0));
}
throw new Error('timed out waiting for group_member_join');
}
describe('Bridge group member identity refresh', () => {
it('forces a fresh member list before dispatching an unresolved join event', async () => {
const member = makeGroupMember(22222, 'u_new_member');
const qqInfo = new QQInfo(SELF_UIN);
qqInfo.setGroups([makeGroup()]);
const bridge = new RefreshingBridge(qqInfo, [member]);
const seen: GroupMemberJoin[] = [];
bridge.registerCmd('test.member_join', () => [{
kind: 'group_member_join',
time: 1710000000,
selfUin: Number(SELF_UIN),
groupId: GROUP_ID,
userUin: 0,
operatorUin: 0,
userUid: member.uid,
operatorUid: member.uid,
}]);
bridge.events.on('group_member_join', (event) => {
seen.push(event);
});
bridge.onPacket(makePacket());
const event = await waitForEvent(seen);
expect(bridge.memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(member.uin);
});
it('remembers UID mappings from realtime request events', () => {
const qqInfo = new QQInfo(SELF_UIN);
const bridge = new Bridge(qqInfo);
const events: QQEventVariant[] = [
{
kind: 'friend_request',
time: 1710000000,
selfUin: Number(SELF_UIN),
fromUin: 55555,
fromUid: 'u_friend_request',
message: '',
flag: 'u_friend_request',
},
{
kind: 'group_invite',
time: 1710000000,
selfUin: Number(SELF_UIN),
groupId: GROUP_ID,
fromUin: 66666,
fromUid: 'u_group_request',
subType: 'add',
message: '',
flag: 'add:123456789:u_group_request',
},
];
bridge.registerCmd('test.request_identity', () => events);
bridge.onPacket(makeRequestPacket());
expect(bridge.identity.findUidByUin(55555)).toBe('u_friend_request');
expect(bridge.identity.findUidByUin(66666)).toBe('u_group_request');
expect(bridge.identity.findUinByUid('u_friend_request')).toBe(55555);
expect(bridge.identity.findUinByUid('u_group_request')).toBe(66666);
});
});

View File

@@ -0,0 +1,50 @@
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';
vi.mock('../src/bridge/builders/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 { QQInfo } = await import('../src/bridge/qq-info');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
override async resolveUserUid(uin: number): Promise<string> {
expect(uin).toBe(12345);
return 'u_peer_12345';
}
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
expect(serviceCmd).toBe('MessageSvc.PbSendMsg');
this.capturedBody = body;
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protoEncode({
result: 0,
privateSequence: 88,
timestamp1: 1710000000,
}, SendMessageResponseSchema)),
};
}
}
const bridge = new TestBridge(new QQInfo('10000'));
await bridge.sendPrivateMessage(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
const request = protoDecode(bridge.capturedBody as Uint8Array, SendMessageRequestSchema);
expect(request?.routingHead?.c2c).toMatchObject({
uin: 12345,
uid: 'u_peer_12345',
});
});
});

View File

@@ -0,0 +1,28 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { pathToFileURL } from 'url';
import { describe, expect, it } from 'vitest';
import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils';
describe('highway source paths', () => {
it('normalizes file URLs with an extra leading slash on POSIX', () => {
if (process.platform === 'win32') return;
expect(resolveLocalFilePath('file:////AstrBot/data/plugin/cache/BV-test.mp4'))
.toBe('/AstrBot/data/plugin/cache/BV-test.mp4');
});
it('loads encoded file URLs from the local filesystem', async () => {
const filePath = path.join(os.tmpdir(), `snowluma video ${process.pid}-${Date.now()}.txt`);
fs.writeFileSync(filePath, 'ok');
try {
const source = pathToFileURL(filePath).href;
const loaded = await loadBinarySource(source, 'test file');
expect(Buffer.from(loaded.bytes).toString('utf8')).toBe('ok');
expect(loaded.fileName).toBe(path.basename(filePath));
} finally {
try { fs.unlinkSync(filePath); } catch { /* ignore */ }
}
});
});

View File

@@ -0,0 +1,197 @@
import { afterEach, describe, expect, it } from 'vitest';
import fs from 'fs';
import path from 'path';
import { IdentityService } from '../src/bridge/identity-service';
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
const dbs: string[] = [];
function tempDbPath(label: string): string {
const dbPath = path.join(
'data',
'test',
`snowluma-identity-${label}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.db`,
);
dbs.push(dbPath);
return dbPath;
}
function cleanupDb(dbPath: string): void {
for (const ext of ['', '-wal', '-shm']) {
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
}
}
function makeGroup(): QQGroupInfo {
return {
groupId: GROUP_ID,
groupName: 'group',
remark: '',
memberCount: 0,
memberMax: 500,
members: new Map(),
};
}
function makeMember(uin: number, uid: string, card = ''): GroupMemberInfo {
return {
uin,
uid,
nickname: `nick-${uin}`,
card,
role: 'member',
level: 1,
title: '',
joinTime: 10,
lastSentTime: 20,
shutUpTime: 0,
};
}
afterEach(() => {
for (const dbPath of dbs.splice(0)) cleanupDb(dbPath);
});
describe('IdentityService', () => {
it('persists friends, groups, and active group members', () => {
const dbPath = tempDbPath('persist');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: 'remark' }]);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_member', 'card')]);
identity.close();
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
expect(qqInfo.findFriend(22222)?.uid).toBe('u_friend');
expect(qqInfo.findGroup(GROUP_ID)?.groupName).toBe('group');
expect(qqInfo.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
expect(identity.findUidByUin(33333, GROUP_ID)).toBe('u_member');
expect(identity.findUinByUid('u_member', GROUP_ID)).toBe(33333);
identity.close();
}
});
it('marks missing members inactive only after a successful full refresh', () => {
const dbPath = tempDbPath('inactive-refresh');
const first = makeMember(33333, 'u_first');
const second = makeMember(44444, 'u_second');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [first, second]);
identity.rememberGroupMembers(GROUP_ID, [second]);
identity.close();
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
expect(qqInfo.findGroupMember(GROUP_ID, first.uin)).toBeNull();
expect(qqInfo.findGroupMember(GROUP_ID, second.uin)?.uid).toBe(second.uid);
// Historical identity remains available for UID/UIN resolution.
expect(identity.findUidByUin(first.uin, GROUP_ID)).toBe(first.uid);
identity.close();
}
});
it('marks missing friends and groups inactive after successful full refreshes', () => {
const dbPath = tempDbPath('inactive-lists');
const member = makeMember(33333, 'u_member');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: '' }]);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.rememberFriends([]);
identity.rememberGroups([]);
identity.close();
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
expect(qqInfo.findFriend(22222)).toBeNull();
expect(qqInfo.findGroup(GROUP_ID)).toBeNull();
// Identity mappings remain useful for historical events/actions.
expect(identity.findUidByUin(22222)).toBe('u_friend');
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
}
});
it('can mark one member inactive without losing the identity mapping', () => {
const dbPath = tempDbPath('inactive-event');
const member = makeMember(33333, 'u_member');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
identity.close();
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
expect(qqInfo.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUinByUid(member.uid, GROUP_ID)).toBe(member.uin);
identity.close();
}
});
it('persists identities learned from request events', () => {
const dbPath = tempDbPath('request-events');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
identity.rememberRequestIdentity({
uid: 'u_friend_request',
uin: 55555,
source: 'friend_request',
});
identity.rememberRequestIdentity({
groupId: GROUP_ID,
uid: 'u_group_request',
uin: 66666,
source: 'group_request',
});
identity.close();
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
expect(identity.findUidByUin(55555)).toBe('u_friend_request');
expect(identity.findUinByUid('u_friend_request')).toBe(55555);
expect(qqInfo.findGroup(GROUP_ID)?.groupId).toBe(GROUP_ID);
expect(identity.findUidByUin(66666)).toBe('u_group_request');
identity.close();
}
});
});

View File

@@ -1,8 +1,13 @@
import { describe, it, expect } from 'vitest';
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/builders/element-builder';
import { MentionExtraSendSchema } from '../src/bridge/proto/action';
import { protoDecode } from '../src/protobuf/decode';
import { makeOidbBaseSchema } from '../src/bridge/proto/oidb';
import { NTV2UploadRichMediaRespSchema } from '../src/bridge/proto/highway';
import { protoDecode, protoEncode } from '../src/protobuf/decode';
describe('parseMessage', () => {
describe('plain text', () => {
@@ -95,6 +100,30 @@ describe('parseMessage', () => {
expect(result).toEqual([{ type: 'record', url: 'file:///tmp/voice.amr' }]);
});
it('parses video segment from data.path and preserves thumb', async () => {
const result = await parseMessage(
[{ type: 'video', data: { path: '/tmp/clip.mp4', thumb: '/tmp/clip.png' } }] as any,
false,
);
expect(result).toEqual([{ type: 'video', url: '/tmp/clip.mp4', thumbUrl: '/tmp/clip.png' }]);
});
it('parses AstrBot-style Video segment with top-level media', async () => {
const result = await parseMessage(
[{ type: 'Video', media: 'file:////AstrBot/data/cache/BV-test.mp4' }] as any,
false,
);
expect(result).toEqual([{ type: 'video', url: 'file:////AstrBot/data/cache/BV-test.mp4', thumbUrl: undefined }]);
});
it('drops video segment with empty source', async () => {
const result = await parseMessage(
[{ type: 'video', data: {} }] as any,
false,
);
expect(result).toEqual([]);
});
it('parses record segment from data.path (NapCat parity)', async () => {
const result = await parseMessage(
[{ type: 'record', data: { path: 'C:\\voices\\hi.silk' } }] as any,
@@ -186,6 +215,77 @@ describe('parseMessage', () => {
expect(protoElems[0].text?.str).toBe('hi ');
});
it('skips video send when SendContext is absent (graceful no-bridge path)', async () => {
const elements = await parseMessage(
[
{ type: 'text', data: { text: 'hi ' } },
{ type: 'video', data: { file: '/tmp/x.mp4' } },
] as any,
false,
);
const protoElems = await buildSendElems(elements);
expect(protoElems).toHaveLength(1);
expect(protoElems[0].text?.str).toBe('hi ');
});
it('builds video commonElem through NTV2 fast-upload response', async () => {
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({
command: 0x11EA,
subCommand: 100,
errorCode: 0,
body: {
respHead: { retCode: 0, message: '' },
upload: {
uKey: '',
msgInfo: {
msgInfoBody: [
{ index: { fileUuid: 'video-uuid' }, fileExist: true },
{ index: { fileUuid: 'thumb-uuid' }, fileExist: true },
],
extBizInfo: {
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
},
},
subFileInfos: [{ uKey: '' }],
},
},
errorMsg: '',
reserved: 1,
}, respSchema);
const bridge = {
qqInfo: { uin: '10000' },
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData,
})),
} as any;
try {
const protoElems = await buildSendElems([{
type: 'video',
url: videoPath,
thumbUrl: 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
}], { bridge, groupId: 123456 });
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
expect(bridge.sendRawPacket).toHaveBeenCalledWith('OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array));
expect(protoElems).toHaveLength(1);
expect(protoElems[0].commonElem?.serviceType).toBe(48);
expect(protoElems[0].commonElem?.businessType).toBe(21);
expect(protoElems[0].commonElem?.pbElem).toBeInstanceOf(Uint8Array);
} finally {
try { fs.unlinkSync(videoPath); } catch { /* ignore */ }
}
});
it('parses multiple segments', async () => {
const result = await parseMessage(
[

View File

@@ -0,0 +1,95 @@
import { describe, expect, it } from 'vitest';
import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/handlers/msg-push-handler';
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
import { PushMsgSchema } from '../src/bridge/proto/message';
import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify';
import type { GroupMemberJoin } from '../src/bridge/events';
import type { PacketInfo } from '../src/protocol/types';
import { protoEncode } from '../src/protobuf/decode';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
function makeGroupMember(uin: number, uid: string): GroupMemberInfo {
return {
uin,
uid,
nickname: '',
card: '',
role: 'member',
level: 0,
title: '',
joinTime: 0,
lastSentTime: 0,
shutUpTime: 0,
};
}
function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
return {
groupId: GROUP_ID,
groupName: '',
remark: '',
memberCount: members.length,
memberMax: 500,
members: new Map(members.map((member) => [member.uin, member])),
};
}
function makeQqInfo(members: GroupMemberInfo[] = []): QQInfo {
const qqInfo = new QQInfo(SELF_UIN);
qqInfo.setGroups([makeGroup(members)]);
return qqInfo;
}
function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = GROUP_ID): PacketInfo {
const operatorBytes = operatorUid
? protoEncode({ operatorField: { uid: operatorUid } } as any, OperatorInfoSchema)
: new Uint8Array(0);
const content = protoEncode({
groupUin: GROUP_ID,
memberUid,
operatorBytes,
} as any, GroupChangeSchema);
const body = protoEncode({
message: {
responseHead: { fromUin },
contentHead: { msgType: 33, 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,
};
}
describe('parseMsgPush group member increase', () => {
it('does not fall back to the group id when a joining uid is unresolved', () => {
const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeQqInfo()) as GroupMemberJoin[];
expect(event.kind).toBe('group_member_join');
expect(event.groupId).toBe(GROUP_ID);
expect(event.userUin).toBe(0);
expect(event.operatorUin).toBe(0);
expect(event.userUid).toBe('u_new_member');
});
it('resolves joining uid and operator uid from the member cache when available', () => {
const member = makeGroupMember(22222, 'u_member');
const operator = makeGroupMember(33333, 'u_operator');
const [event] = parseMsgPush(makeGroupIncreasePacket(member.uid, operator.uid), makeQqInfo([member, operator])) as GroupMemberJoin[];
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(operator.uin);
expect(event.userUid).toBe(member.uid);
expect(event.operatorUid).toBe(operator.uid);
});
});

View File

@@ -0,0 +1,44 @@
import { mkdtemp, rm, writeFile } from 'fs/promises';
import os from 'os';
import path from 'path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { listLiveLinuxPipePids } from '../src/hook/qq-hook-client';
let tmpDir: string | null = null;
async function makeRuntimeDir(): Promise<string> {
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-'));
return tmpDir;
}
afterEach(async () => {
if (!tmpDir) return;
await rm(tmpDir, { recursive: true, force: true });
tmpDir = null;
});
describe('listLiveLinuxPipePids', () => {
it('ignores stale-looking control socket names when the probe rejects them', async () => {
const runtimeDir = await makeRuntimeDir();
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), '');
const pids = await listLiveLinuxPipePids(runtimeDir, async () => false);
expect([...pids]).toEqual([]);
});
it('returns only connectable control sockets', async () => {
const runtimeDir = await makeRuntimeDir();
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), '');
await writeFile(path.join(runtimeDir, 'mojo.56.recv.sock'), '');
await writeFile(path.join(runtimeDir, 'mojo.not-a-pid.control.sock'), '');
const probe = vi.fn(async (socketPath: string) => socketPath.endsWith('mojo.56.control.sock'));
const pids = await listLiveLinuxPipePids(runtimeDir, probe);
expect([...pids]).toEqual([56]);
expect(probe).toHaveBeenCalledTimes(2);
});
});

View File

@@ -0,0 +1,8 @@
# Changelog
## 0.1.0
- Initial SnowLuma TypeScript SDK package.
- Added HTTP and WebSocket clients for OneBot APIs.
- Added event middleware, command matching, request context helpers, and message chain builders.
- Added structured SDK error classes and per-request `AbortSignal` support.

259
packages/sdk/README.md Normal file
View File

@@ -0,0 +1,259 @@
# @snowluma/sdk
SnowLuma 的 TypeScript SDK,提供 OneBot HTTP / WebSocket 客户端、事件中间件、命令匹配和消息链式构造器。
## 导航
- [安装](#安装)
- [快速开始](#快速开始)
- [HTTP Client](#http-client)
- [WebSocket Client](#websocket-client)
- [事件中间件与命令](#事件中间件与命令)
- [Raw Action](#raw-action)
- [Message Builder](#message-builder)
- [请求控制](#请求控制)
- [错误处理](#错误处理)
- [测试建议](#测试建议)
- [子路径导入](#子路径导入)
- [Action 同步](#action-同步)
- [项目结构](#项目结构)
- [版本策略](#版本策略)
## 安装
在本 monorepo 内直接通过 workspace 引用:
```bash
pnpm add @snowluma/sdk --workspace
```
发布到 npm 后可直接安装:
```bash
pnpm add @snowluma/sdk
```
## 快速开始
```ts
import { SnowLumaHttpClient, text } from '@snowluma/sdk';
const bot = new SnowLumaHttpClient({
baseUrl: 'http://127.0.0.1:3000/',
accessToken: process.env.SNOWLUMA_TOKEN,
});
const login = await bot.getLoginInfo();
await bot.sendGroupMessage(123456, text(`Hello from ${login.nickname}`).at('all'));
```
SnowLuma 的 OneBot HTTP / WebSocket 端口和 `accessToken` 来自 `config/onebot_<uin>.json`。
## HTTP Client
```ts
import { SnowLumaHttpClient, message, text } from '@snowluma/sdk';
const bot = new SnowLumaHttpClient({
baseUrl: 'http://127.0.0.1:3000/',
accessToken: process.env.SNOWLUMA_TOKEN,
requestTimeoutMs: 30_000,
});
await bot.sendPrivateMessage(10001, text('pong'));
await bot.sendGroupMessage(123456, [
message.text('Hello'),
message.at('all'),
]);
```
## WebSocket Client
WebSocket 客户端会用 `echo` 关联 API 响应,并把无 `echo` 的包作为事件分发。
```ts
import { SnowLumaWebSocketClient, text } from '@snowluma/sdk';
const bot = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
accessToken: process.env.SNOWLUMA_TOKEN,
reconnect: true,
});
bot.onGroupMessage(async (event, ctx) => {
if (event.raw_message === '/ping') {
await ctx.reply(text('pong').at(event.user_id));
}
});
bot.onRequest('friend', async (_event, ctx) => {
await ctx.approve();
});
await bot.connect();
await bot.sendPrivateMessage(10001, text('ready'));
```
## 事件中间件与命令
```ts
bot.use(async (event, ctx, next) => {
console.log(event.post_type);
await next();
});
bot.command('echo', async (_event, ctx, match) => {
await ctx.reply(text(match.rest || 'empty'));
});
bot.when(
(event) => event.post_type === 'notice',
async (event) => console.log(event),
);
```
事件上下文内置快捷操作:
- `ctx.reply(message)`:按私聊/群聊自动回复。
- `ctx.approve()` / `ctx.reject(reason)`:处理好友或群请求。
- `ctx.quickOperation(operation)`:调用 `.handle_quick_operation`。
- `ctx.stopPropagation()`:停止后续中间件和普通 `onEvent` 分发。
## Raw Action
高频接口提供 camelCase 方法;其它 SnowLuma action 可以用 `raw` 或 `rawResponse`:
```ts
const data = await bot.raw('get_group_file_system_info', {
group_id: 123456,
});
const response = await bot.rawResponse('get_status');
```
`raw` 会在 SnowLuma 返回 `status: "failed"` 或非零 `retcode` 时抛出 `SnowLumaApiError`;`rawResponse` 会保留完整响应。
## Message Builder
```ts
import { fromCQString, message, text, toCQString } from '@snowluma/sdk';
const segments = [
message.reply(42),
message.text('收到 '),
message.image('https://example.com/a.png'),
];
const chained = text('收到 ')
.at(10001)
.image('https://example.com/a.png');
const cq = toCQString(segments);
const chainedCq = toCQString(chained);
const parsed = fromCQString('hi[CQ:at,qq=all]');
```
链式入口返回 `MessageChain`,可以直接传给发送接口,也可以用 `build()` / `toSegments()` 转成 OneBot segment 数组:
```ts
await bot.sendGroupMessage(123456, text('hi').at(10001).image('/tmp/a.png'));
const segments = text('hi').at('all').build();
await text('hi').atAll().br().face(14).sendToGroup(bot, 123456);
```
`reply()` 在一条链中只能出现一次;TypeScript 会阻止 `text('a').reply(1).reply(2)`,运行时也会做同样检查。
已内置常用段:`text`、`br`、`face`、`at`、`atAll`、`reply`、`image`、`record`、`video`、`json`、`xml`、`poke`、`forward`、`node`、`share`、`music`、`location`、`contact` 和 `raw`。
## 请求控制
每次请求都支持覆盖 `echo`、超时和 `AbortSignal`:
```ts
const controller = new AbortController();
const status = bot.getStatus({
echo: 'healthcheck',
timeoutMs: 5_000,
signal: controller.signal,
});
controller.abort();
await status;
```
`timeoutMs: 0` 表示关闭该请求的超时控制。
## 错误处理
SDK 暴露统一错误基类和更具体的错误类型:
- `SnowLumaApiError`:OneBot 响应失败或 `retcode !== 0`。
- `SnowLumaAuthError`:鉴权相关 retcode,例如 `1401`、`401`、`403`。
- `SnowLumaTransportError`:连接、解析、超时、取消等传输层错误基类。
- `SnowLumaConnectionError`:HTTP fetch / WebSocket 连接或发送失败。
- `SnowLumaParseError`:响应不是合法 JSON 或不符合 OneBot 响应结构。
- `SnowLumaTimeoutError`:请求超过 `timeoutMs`。
- `SnowLumaAbortError`:调用方通过 `AbortSignal` 主动取消。
```ts
import {
SnowLumaApiError,
SnowLumaAuthError,
SnowLumaTimeoutError,
} from '@snowluma/sdk';
try {
await bot.getStatus({ timeoutMs: 1000 });
} catch (error) {
if (error instanceof SnowLumaAuthError) {
throw new Error('SnowLuma access token is invalid');
}
if (error instanceof SnowLumaTimeoutError) {
console.warn(`SnowLuma did not respond in ${error.timeoutMs}ms`);
}
if (error instanceof SnowLumaApiError) {
console.warn(error.retcode, error.wording);
}
}
```
## 测试建议
- SDK 自身使用 Vitest 覆盖消息构造、事件上下文、WebSocket 响应关联、错误模型和取消逻辑。
- 对接真实 SnowLuma 时建议使用单独测试账号和测试群,避免把自动化消息发到生产环境。
- 集成测试里优先显式设置 `echo` 和较短 `timeoutMs`,这样失败时更容易定位是哪一次 action。
- 发布前运行 `pnpm --filter @snowluma/sdk typecheck`、`pnpm --filter @snowluma/sdk test`、`pnpm --filter @snowluma/sdk build`。
## 子路径导入
```ts
import { SnowLumaHttpClient } from '@snowluma/sdk/client';
import { text } from '@snowluma/sdk/messages';
import { isMessageEvent } from '@snowluma/sdk/events';
import { SnowLumaApiError } from '@snowluma/sdk/errors';
```
根入口 `@snowluma/sdk` 仍导出正式公开 API;不再保留旧的根级兼容 barrel 或别名 API。
## Action 同步
SDK 导出 `SNOWLUMA_ACTIONS` 和 `isSnowLumaAction()`。测试会扫描 `packages/core/src/onebot/actions/*.ts` 的 `registerAction()`,确保 SDK action 列表没有落后。
## 项目结构
```text
src/
client/ HTTP / WebSocket client 与 API facade
events/ 事件上下文、类型守卫、中间件和命令匹配
messages/ segment 工厂、MessageChain、CQ 编解码
types/ JSON、消息、事件、action 参数和返回类型
internal/ SDK 内部工具
```
## 版本策略
当前包版本为 `0.1.0`。版本规则、发布检查清单和破坏性变更边界见 [VERSIONING.md](./VERSIONING.md)。

View File

@@ -0,0 +1,43 @@
# @snowluma/sdk Versioning
The SDK follows SemVer for its public package surface:
- Exported runtime values and classes from `@snowluma/sdk`.
- Exported types from `@snowluma/sdk` and `@snowluma/sdk/types`.
- Supported subpath exports: `client`, `messages`, `events`, `errors`, `actions`, and `types`.
- Runtime behavior of typed client helpers, message builders, event helpers, and SDK error classes.
## Current 0.x Policy
While the SDK is below `1.0.0`, breaking changes should use a minor release and include a migration note. Patch releases should remain bug fixes only.
Examples:
- `0.1.1`: bug fix, doc fix, type refinement that does not break consumers.
- `0.2.0`: new client helper, new event helper, new action typing, or documented breaking change before 1.0.
- `1.0.0`: first stable release where breaking changes move to major versions.
## After 1.0
- Major: removes or changes a public export, changes runtime behavior incompatibly, changes supported Node version, or changes package subpaths.
- Minor: adds new public API, supports new SnowLuma actions, adds optional parameters, or adds error subclasses.
- Patch: fixes bugs, improves docs, narrows implementation details without breaking public types, or updates action metadata without changing call signatures.
## Release Checklist
1. Update `packages/sdk/package.json` version.
2. Update `packages/sdk/CHANGELOG.md`.
3. Run `pnpm --filter @snowluma/sdk typecheck`.
4. Run `pnpm --filter @snowluma/sdk test`.
5. Run `pnpm --filter @snowluma/sdk build`.
6. Run `pnpm --filter @snowluma/sdk pack --dry-run` to inspect published files.
## Automated npm Publish
`.github/workflows/sdk-npm-publish.yml` publishes `@snowluma/sdk` when SDK-related files reach `main`, including the automated `dev` to `main` promotion flow. The publish job uses the GitHub Environment named `SnowLuma` and expects an environment secret named `NPM_TOKEN`.
If the package version already exists on npm, the workflow skips publishing that run. Bump `packages/sdk/package.json` before merging SDK changes that should create a new npm release.
## Action Compatibility
SnowLuma action coverage is synchronized from `packages/core/src/onebot/actions/*.ts`. Adding an action type is a minor change unless it changes an existing method signature or return type.

95
packages/sdk/package.json Normal file
View File

@@ -0,0 +1,95 @@
{
"name": "@snowluma/sdk",
"author": {
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "0.1.0",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
"onebot",
"onebot11",
"qq",
"bot",
"sdk"
],
"homepage": "https://github.com/SnowLuma/SnowLuma#readme",
"bugs": {
"url": "https://github.com/SnowLuma/SnowLuma/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/SnowLuma/SnowLuma.git",
"directory": "packages/sdk"
},
"license": "UNLICENSED",
"type": "module",
"sideEffects": false,
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./client": {
"types": "./dist/client/index.d.ts",
"import": "./dist/client/index.js"
},
"./messages": {
"types": "./dist/messages/index.d.ts",
"import": "./dist/messages/index.js"
},
"./events": {
"types": "./dist/events/index.d.ts",
"import": "./dist/events/index.js"
},
"./types": {
"types": "./dist/types/index.d.ts",
"import": "./dist/types/index.js"
},
"./errors": {
"types": "./dist/errors.d.ts",
"import": "./dist/errors.js"
},
"./actions": {
"types": "./dist/actions.d.ts",
"import": "./dist/actions.js"
},
"./package.json": "./package.json"
},
"files": [
"dist/actions.*",
"dist/client",
"dist/emitter.*",
"dist/errors.*",
"dist/events",
"dist/index.*",
"dist/internal",
"dist/messages",
"dist/types",
"README.md",
"CHANGELOG.md",
"VERSIONING.md"
],
"scripts": {
"clean": "node -e \"const fs = require('node:fs'); fs.rmSync('dist', { recursive: true, force: true })\"",
"prebuild": "pnpm run clean",
"build": "tsc -p tsconfig.json",
"prepack": "pnpm run build",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"publishConfig": {
"access": "public"
},
"engines": {
"node": ">=22"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vitest": "^4.1.4"
}
}

126
packages/sdk/src/actions.ts Normal file
View File

@@ -0,0 +1,126 @@
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_ban',
'set_group_whole_ban',
'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_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',
'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',
] as const satisfies readonly (keyof SnowLumaActionMap)[];
export type SnowLumaKnownAction = typeof SNOWLUMA_ACTIONS[number];
const ACTION_SET = new Set<string>(SNOWLUMA_ACTIONS);
export function isSnowLumaAction(action: string): action is SnowLumaKnownAction {
return ACTION_SET.has(action);
}

View File

@@ -0,0 +1,470 @@
import { createSnowLumaApiError } from '../errors';
import { normalizeMessage } from '../messages/index';
import type {
ActionParams,
ActionResult,
ApiResponse,
DomainParams,
DownloadFileParams,
ForwardMessageParams,
GetForwardMsgParams,
GetFriendMessageHistoryParams,
GetGroupHonorInfoParams,
GetGroupMessageHistoryParams,
GetMediaParams,
JsonObject,
JsonValue,
OutgoingMessage,
PrivateForwardMessageParams,
RequestOptions,
SendMsgParams,
SetGroupReactionParams,
SnowLumaAction,
} from '../types/index';
/**
* Base class for SnowLuma API clients.
*
* Concrete transports implement request(); this facade adds typed OneBot actions,
* message normalization, and failed-response error handling.
*/
export abstract class SnowLumaApiClient {
/** Sends a raw OneBot action and returns the complete API response. */
abstract request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>>;
/** Sends a OneBot action and returns data, throwing SnowLumaApiError on failed responses. */
async call<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ActionResult<TAction>> {
const response = await this.request(action, params, options);
if (response.status !== 'ok' || response.retcode !== 0) {
throw createSnowLumaApiError(response);
}
return response.data;
}
getLoginInfo(options?: RequestOptions) {
return this.call('get_login_info', {}, options);
}
getStatus(options?: RequestOptions) {
return this.call('get_status', {}, options);
}
getVersionInfo(options?: RequestOptions) {
return this.call('get_version_info', {}, options);
}
canSendImage(options?: RequestOptions) {
return this.call('can_send_image', {}, options);
}
canSendRecord(options?: RequestOptions) {
return this.call('can_send_record', {}, options);
}
sendMsg(params: Omit<SendMsgParams, 'message'> & { message: OutgoingMessage }, options?: RequestOptions) {
return this.call('send_msg', { ...params, message: normalizeMessage(params.message) as JsonValue }, options);
}
sendPrivateMessage(userId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }) {
return this.call('send_private_msg', {
user_id: userId,
message: normalizeMessage(message) as JsonValue,
auto_escape: options?.autoEscape,
}, options);
}
sendGroupMessage(groupId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }) {
return this.call('send_group_msg', {
group_id: groupId,
message: normalizeMessage(message) as JsonValue,
auto_escape: options?.autoEscape,
}, options);
}
getMessage(messageId: number, options?: RequestOptions) {
return this.call('get_msg', { message_id: messageId }, options);
}
deleteMessage(messageId: number, options?: RequestOptions) {
return this.call('delete_msg', { message_id: messageId }, options);
}
getFriendList(options?: RequestOptions) {
return this.call('get_friend_list', {}, options);
}
getStrangerInfo(userId: number, options?: RequestOptions) {
return this.call('get_stranger_info', { user_id: userId }, options);
}
deleteFriend(userId: number, options?: RequestOptions & { block?: boolean }) {
return this.call('delete_friend', { user_id: userId, block: options?.block }, options);
}
getGroupList(options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_list', { no_cache: options?.noCache }, options);
}
getGroupInfo(groupId: number, options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_info', { group_id: groupId, no_cache: options?.noCache }, options);
}
getGroupMemberList(groupId: number, options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_member_list', { group_id: groupId, no_cache: options?.noCache }, options);
}
getGroupMemberInfo(groupId: number, userId: number, options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_member_info', {
group_id: groupId,
user_id: userId,
no_cache: options?.noCache,
}, options);
}
getGroupHonorInfo(params: GetGroupHonorInfoParams, options?: RequestOptions) {
return this.call('get_group_honor_info', params, options);
}
getGroupSystemMessages(options?: RequestOptions) {
return this.call('get_group_system_msg', {}, options);
}
setGroupKick(groupId: number, userId: number, options?: RequestOptions & { rejectAddRequest?: boolean }) {
return this.call('set_group_kick', {
group_id: groupId,
user_id: userId,
reject_add_request: options?.rejectAddRequest,
}, options);
}
setGroupBan(groupId: number, userId: number, duration?: number, options?: RequestOptions) {
return this.call('set_group_ban', { group_id: groupId, user_id: userId, duration }, options);
}
setGroupWholeBan(groupId: number, enable = true, options?: RequestOptions) {
return this.call('set_group_whole_ban', { group_id: groupId, enable }, options);
}
setGroupAdmin(groupId: number, userId: number, enable = true, options?: RequestOptions) {
return this.call('set_group_admin', { group_id: groupId, user_id: userId, enable }, options);
}
setGroupCard(groupId: number, userId: number, card = '', options?: RequestOptions) {
return this.call('set_group_card', { group_id: groupId, user_id: userId, card }, options);
}
setGroupName(groupId: number, name: string, options?: RequestOptions) {
return this.call('set_group_name', { group_id: groupId, group_name: name }, options);
}
setGroupLeave(groupId: number, options?: RequestOptions) {
return this.call('set_group_leave', { group_id: groupId }, options);
}
setGroupSpecialTitle(groupId: number, userId: number, title = '', options?: RequestOptions) {
return this.call('set_group_special_title', {
group_id: groupId,
user_id: userId,
special_title: title,
}, options);
}
uploadGroupFile(groupId: number, file: string, options: RequestOptions & {
name?: string;
folder?: string;
folderId?: string;
uploadFile?: boolean;
} = {}) {
return this.call('upload_group_file', {
group_id: groupId,
file,
name: options.name,
folder: options.folder,
folder_id: options.folderId,
upload_file: options.uploadFile,
}, options);
}
uploadPrivateFile(userId: number, file: string, options: RequestOptions & {
name?: string;
uploadFile?: boolean;
} = {}) {
return this.call('upload_private_file', {
user_id: userId,
file,
name: options.name,
upload_file: options.uploadFile,
}, options);
}
getGroupFileUrl(groupId: number, fileId: string, options?: RequestOptions & { busid?: number }) {
return this.call('get_group_file_url', { group_id: groupId, file_id: fileId, busid: options?.busid }, options);
}
getGroupRootFiles(groupId: number, options?: RequestOptions) {
return this.call('get_group_root_files', { group_id: groupId }, options);
}
getGroupFilesByFolder(groupId: number, folderId = '/', options?: RequestOptions) {
return this.call('get_group_files_by_folder', { group_id: groupId, folder_id: folderId }, options);
}
deleteGroupFile(groupId: number, fileId: string, options?: RequestOptions) {
return this.call('delete_group_file', { group_id: groupId, file_id: fileId }, options);
}
moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string, options?: RequestOptions) {
return this.call('move_group_file', {
group_id: groupId,
file_id: fileId,
parent_directory: parentDirectory,
target_directory: targetDirectory,
}, options);
}
createGroupFileFolder(groupId: number, name: string, parentId = '/', options?: RequestOptions) {
return this.call('create_group_file_folder', { group_id: groupId, name, parent_id: parentId }, options);
}
deleteGroupFileFolder(groupId: number, folderId: string, options?: RequestOptions) {
return this.call('delete_group_file_folder', { group_id: groupId, folder_id: folderId }, options);
}
renameGroupFileFolder(groupId: number, folderId: string, newName: string, options?: RequestOptions) {
return this.call('rename_group_file_folder', {
group_id: groupId,
folder_id: folderId,
new_folder_name: newName,
}, options);
}
getPrivateFileUrl(userId: number, fileId: string, fileHash: string, options?: RequestOptions) {
return this.call('get_private_file_url', { user_id: userId, file_id: fileId, file_hash: fileHash }, options);
}
setFriendAddRequest(flag: string, approve = true, options?: RequestOptions) {
return this.call('set_friend_add_request', { flag, approve }, options);
}
setGroupAddRequest(flag: string, params: RequestOptions & {
subType?: string;
type?: string;
approve?: boolean;
reason?: string;
} = {}) {
return this.call('set_group_add_request', {
flag,
sub_type: params.subType,
type: params.type,
approve: params.approve,
reason: params.reason,
}, params);
}
sendLike(userId: number, times = 1, options?: RequestOptions) {
return this.call('send_like', { user_id: userId, times }, options);
}
friendPoke(userId: number, options?: RequestOptions & { targetId?: number }) {
return this.call('friend_poke', { user_id: userId, target_id: options?.targetId }, options);
}
groupPoke(groupId: number, userId: number, options?: RequestOptions) {
return this.call('group_poke', { group_id: groupId, user_id: userId }, options);
}
sendPoke(userId: number, options?: RequestOptions & { groupId?: number }) {
return this.call('send_poke', { user_id: userId, group_id: options?.groupId }, options);
}
setEssenceMessage(messageId: number, options?: RequestOptions) {
return this.call('set_essence_msg', { message_id: messageId }, options);
}
deleteEssenceMessage(messageId: number, options?: RequestOptions) {
return this.call('delete_essence_msg', { message_id: messageId }, options);
}
getEssenceMessageList(groupId: number, options?: RequestOptions) {
return this.call('get_essence_msg_list', { group_id: groupId }, options);
}
setGroupReaction(params: SetGroupReactionParams, options?: RequestOptions) {
return this.call('set_group_reaction', params, options);
}
getGroupMessageHistory(params: GetGroupMessageHistoryParams, options?: RequestOptions) {
return this.call('get_group_msg_history', params, options);
}
getFriendMessageHistory(params: GetFriendMessageHistoryParams, options?: RequestOptions) {
return this.call('get_friend_msg_history', params, options);
}
markGroupMessageAsRead(messageId: number, groupId?: number, options?: RequestOptions) {
return this.call('mark_group_msg_as_read', { message_id: messageId, group_id: groupId }, options);
}
markPrivateMessageAsRead(messageId: number, userId?: number, options?: RequestOptions) {
return this.call('mark_private_msg_as_read', { message_id: messageId, user_id: userId }, options);
}
markMessageAsRead(messageId: number, targetId?: number, options?: RequestOptions) {
return this.call('mark_msg_as_read', { message_id: messageId, target_id: targetId }, options);
}
getRKey(options?: RequestOptions) {
return this.call('get_rkey', {}, options);
}
sendGroupNotice(groupId: number, content: string, options: RequestOptions & {
image?: string;
pinned?: number;
type?: number;
confirmRequired?: number;
} = {}) {
return this.call('_send_group_notice', {
group_id: groupId,
content,
image: options.image,
pinned: options.pinned,
type: options.type,
confirm_required: options.confirmRequired,
}, options);
}
getGroupNotice(groupId: number, options?: RequestOptions) {
return this.call('_get_group_notice', { group_id: groupId }, options);
}
uploadForwardMessage(params: ForwardMessageParams, options?: RequestOptions) {
return this.call('upload_forward_msg', params, options);
}
sendForwardMessage(params: ForwardMessageParams, options?: RequestOptions) {
return this.call('send_forward_msg', params, options);
}
sendGroupForwardMessage(groupId: number, messages: OutgoingMessage, options?: RequestOptions) {
return this.call('send_group_forward_msg', {
group_id: groupId,
messages: normalizeMessage(messages) as JsonValue,
}, options);
}
sendPrivateForwardMessage(userId: number, messages: OutgoingMessage, options?: RequestOptions) {
return this.call('send_private_forward_msg', {
user_id: userId,
messages: normalizeMessage(messages) as JsonValue,
}, options);
}
getForwardMessage(params: GetForwardMsgParams, options?: RequestOptions) {
return this.call('get_forward_msg', params, options);
}
getImage(params: GetMediaParams, options?: RequestOptions) {
return this.call('get_image', params, options);
}
getRecord(params: GetMediaParams, options?: RequestOptions) {
return this.call('get_record', params, options);
}
getCookies(params: DomainParams = {}, options?: RequestOptions) {
return this.call('get_cookies', params, options);
}
getCsrfToken(options?: RequestOptions) {
return this.call('get_csrf_token', {}, options);
}
getCredentials(params: DomainParams = {}, options?: RequestOptions) {
return this.call('get_credentials', params, options);
}
cleanCache(options?: RequestOptions) {
return this.call('clean_cache', {}, options);
}
setFriendRemark(userId: number, remark: string, options?: RequestOptions) {
return this.call('set_friend_remark', { user_id: userId, remark }, options);
}
setMsgEmojiLike(messageId: number, emojiId: string, set = true, options?: RequestOptions) {
return this.call('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId, set }, options);
}
markAllAsRead(options?: RequestOptions) {
return this.call('_mark_all_as_read', {}, options);
}
getGroupFileSystemInfo(groupId: number, options?: RequestOptions) {
return this.call('get_group_file_system_info', { group_id: groupId }, options);
}
checkUrlSafely(options?: RequestOptions) {
return this.call('check_url_safely', {}, options);
}
downloadFile(params: DownloadFileParams, options?: RequestOptions) {
return this.call('download_file', params, options);
}
setQqProfile(params: { nickname?: string; personalNote?: string }, options?: RequestOptions) {
return this.call('set_qq_profile', {
nickname: params.nickname,
personal_note: params.personalNote,
}, options);
}
setOnlineStatus(status: number, params: RequestOptions & { extStatus?: number; batteryStatus?: number } = {}) {
return this.call('set_online_status', {
status,
ext_status: params.extStatus,
battery_status: params.batteryStatus,
}, params);
}
getClientKey(options?: RequestOptions) {
return this.call('get_clientkey', {}, options);
}
getGroupInfoEx(groupId: number, options?: RequestOptions) {
return this.call('get_group_info_ex', { group_id: groupId }, options);
}
getGroupDetailInfo(groupId: number, options?: RequestOptions) {
return this.call('get_group_detail_info', { group_id: groupId }, options);
}
/** Calls any registered SnowLuma action and returns the response data. */
raw<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
) {
return this.call(action, params, options);
}
/** Calls any registered SnowLuma action and preserves the full OneBot response envelope. */
rawResponse<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
) {
return this.request(action, params, options);
}
}
export function toJsonObject(value: JsonObject | undefined): JsonObject {
return value ?? {};
}

View File

@@ -0,0 +1,115 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError,
} from '../errors';
import { SnowLumaApiClient, toJsonObject } from './api-client';
import { createRequestAbortState, isAbortError } from '../internal/abort';
import { assertApiResponse } from '../internal/json';
import type {
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
RequestOptions,
SnowLumaAction,
SnowLumaClientOptions,
} from '../types/index';
/** Options for the HTTP transport client. */
export interface SnowLumaHttpClientOptions extends SnowLumaClientOptions {
/** OneBot HTTP endpoint. Defaults to http://127.0.0.1:3000/. */
baseUrl?: string;
/** Custom fetch implementation for tests or non-standard runtimes. */
fetch?: typeof fetch;
/** Extra headers sent with every request. Authorization is managed by accessToken. */
headers?: Record<string, string>;
}
/** OneBot HTTP client for SnowLuma. */
export class SnowLumaHttpClient extends SnowLumaApiClient {
readonly baseUrl: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
private readonly fetchImpl: typeof fetch;
private readonly headers: Record<string, string>;
constructor(options: SnowLumaHttpClientOptions = {}) {
super();
this.baseUrl = options.baseUrl ?? 'http://127.0.0.1:3000/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.fetchImpl = options.fetch ?? globalThis.fetch;
this.headers = options.headers ?? {};
if (!this.fetchImpl) {
throw new SnowLumaConnectionError('No fetch implementation is available');
}
}
/** Sends one OneBot action over HTTP and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const abort = createRequestAbortState(timeoutMs, options?.signal);
try {
const response = await this.fetchImpl(this.baseUrl, {
method: 'POST',
headers: this.createHeaders(),
body: JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo: options?.echo,
}),
signal: abort.signal,
});
const text = await response.text();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch (error) {
throw new SnowLumaParseError(`SnowLuma returned non-JSON HTTP ${response.status}`, { cause: error });
}
const apiResponse = assertApiResponse(parsed) as ApiResponse<ActionResult<TAction>>;
return apiResponse;
} catch (error) {
if (error instanceof SnowLumaTransportError) throw error;
if (isAbortError(error) || abort.signal.aborted) {
if (abort.isTimedOut()) {
throw new SnowLumaTimeoutError(`SnowLuma request timed out after ${timeoutMs}ms`, timeoutMs, { cause: error });
}
if (abort.isExternallyAborted()) {
throw new SnowLumaAbortError('SnowLuma request aborted', { cause: error });
}
}
throw new SnowLumaConnectionError('SnowLuma HTTP request failed', { cause: error });
} finally {
abort.cleanup();
}
}
private createHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
...this.headers,
};
if (this.accessToken) {
headers.Authorization = `Bearer ${this.accessToken}`;
}
return headers;
}
}
export function createHttpClient(options?: SnowLumaHttpClientOptions): SnowLumaHttpClient {
return new SnowLumaHttpClient(options);
}

View File

@@ -0,0 +1,12 @@
export { SnowLumaApiClient } from './api-client';
export { SnowLumaHttpClient, createHttpClient } from './http-client';
export { SnowLumaWebSocketClient, createWebSocketClient } from './websocket-client';
export type { SnowLumaHttpClientOptions } from './http-client';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './websocket-client';

View File

@@ -0,0 +1,421 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
} from '../errors';
import { Emitter } from '../emitter';
import {
createEventContext,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
matchCommand,
noticeType,
requestType,
type CommandHandler,
type CommandOptions,
type EventHandler,
type EventMiddleware,
type EventPredicate,
} from '../events/index';
import { SnowLumaApiClient, toJsonObject } from './api-client';
import { raceWithAbort, throwIfAborted } from '../internal/abort';
import { appendAccessToken, assertApiResponse, createEcho, echoKey, isJsonObject } from '../internal/json';
import {
addSocketListener,
closeInfo,
normalizeReconnect,
rawToString,
unwrapEventPayload,
unwrapMessagePayload,
WEBSOCKET_CLOSED,
WEBSOCKET_OPEN,
} from './websocket-utils';
import type {
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
JsonValue,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotRequestEvent,
RequestOptions,
SnowLumaAction,
SnowLumaEvent,
WsRole,
} from '../types/index';
import type {
PendingRequest,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketConstructor,
WebSocketLike,
} from './websocket-types';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './websocket-types';
/** OneBot WebSocket client for SnowLuma APIs and realtime events. */
export class SnowLumaWebSocketClient extends SnowLumaApiClient {
readonly url: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
readonly role: WsRole;
private readonly protocols?: string | string[];
private readonly WebSocketCtor: WebSocketConstructor;
private readonly reconnect: ReconnectOptions | null;
private readonly emitter = new Emitter<SnowLumaWebSocketEvents>();
private readonly pending = new Map<string, PendingRequest>();
private readonly middlewares: EventMiddleware[] = [];
private socket: WebSocketLike | null = null;
private connectPromise: Promise<void> | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempts = 0;
private closedByUser = false;
constructor(options: SnowLumaWebSocketClientOptions = {}) {
super();
this.url = options.url ?? 'ws://127.0.0.1:3001/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.role = options.role ?? 'Universal';
this.protocols = options.protocols;
this.WebSocketCtor = options.webSocket ?? globalThis.WebSocket as unknown as WebSocketConstructor;
this.reconnect = normalizeReconnect(options.reconnect);
if (!this.WebSocketCtor) {
throw new SnowLumaConnectionError('No WebSocket implementation is available');
}
}
/** True when the underlying WebSocket is currently open. */
get isConnected(): boolean {
return this.socket?.readyState === WEBSOCKET_OPEN;
}
/** Subscribes to low-level client events. Returns an unsubscribe function. */
on<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.on(event, listener);
}
/** Subscribes to one low-level client event, then automatically unsubscribes. */
once<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.once(event, listener);
}
/** Removes a previously registered low-level client event listener. */
off<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): void {
this.emitter.off(event, listener);
}
/** Subscribes to every SnowLuma event packet. */
onEvent(listener: (event: SnowLumaEvent) => void): () => void {
return this.on('event', listener);
}
/** Adds event middleware to the dispatch pipeline. */
use(middleware: EventMiddleware): () => void {
this.middlewares.push(middleware);
return () => {
const index = this.middlewares.indexOf(middleware);
if (index >= 0) this.middlewares.splice(index, 1);
};
}
/** Runs a handler when a type guard or predicate matches an event. */
when<TEvent extends SnowLumaEvent>(
predicate: EventPredicate<TEvent>,
handler: EventHandler<TEvent>,
): () => void {
return this.use(async (event, context, next) => {
if (predicate(event)) {
await handler(event, context as never);
}
if (!context.stopped) await next();
});
}
onMessage(handler: EventHandler<OneBotMessageEvent>): () => void {
return this.when(isMessageEvent, handler);
}
onPrivateMessage(handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'private' }>>): () => void {
return this.when(isPrivateMessageEvent, handler);
}
onGroupMessage(handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'group' }>>): () => void {
return this.when(isGroupMessageEvent, handler);
}
onNotice(handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(type: string, handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(typeOrHandler: string | EventHandler<OneBotNoticeEvent>, handler?: EventHandler<OneBotNoticeEvent>): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) throw new TypeError('onNotice(type, handler) requires a handler');
return this.when(noticeType(typeOrHandler), handler);
}
return this.when(isNoticeEvent, typeOrHandler);
}
onRequest(handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(type: string, handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(typeOrHandler: string | EventHandler<OneBotRequestEvent>, handler?: EventHandler<OneBotRequestEvent>): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) throw new TypeError('onRequest(type, handler) requires a handler');
return this.when(requestType(typeOrHandler), handler);
}
return this.when(isRequestEvent, typeOrHandler);
}
onMetaEvent(handler: EventHandler<OneBotMetaEvent>): () => void {
return this.when(isMetaEvent, handler);
}
command(
command: string | RegExp,
handler: CommandHandler,
options?: CommandOptions,
): () => void {
return this.onMessage(async (event, context) => {
const matched = matchCommand(event, command, options);
if (!matched) return;
await handler(event, Object.assign(context, { command: matched }), matched);
});
}
/** Connects to SnowLuma's OneBot WebSocket endpoint. */
async connect(): Promise<void> {
if (this.isConnected) return;
if (this.connectPromise) return this.connectPromise;
this.closedByUser = false;
this.connectPromise = new Promise((resolve, reject) => {
const url = appendAccessToken(this.url, this.accessToken);
const socket = new this.WebSocketCtor(url, this.protocols);
this.socket = socket;
const cleanup = [
addSocketListener(socket, 'open', () => {
cleanup.forEach((off) => off());
this.bindSocket(socket);
this.reconnectAttempts = 0;
this.connectPromise = null;
this.emitter.emit('open', undefined);
resolve();
}),
addSocketListener(socket, 'error', (error) => {
this.emitter.emit('error', unwrapEventPayload(error));
}),
addSocketListener(socket, 'close', (...args) => {
cleanup.forEach((off) => off());
this.connectPromise = null;
this.socket = null;
reject(new SnowLumaConnectionError('SnowLuma WebSocket closed before opening'));
this.handleClose(args);
}),
];
});
return this.connectPromise;
}
/** Closes the socket and rejects all pending API requests. */
close(code = 1000, reason = 'normal'): void {
this.closedByUser = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket client closed'));
if (this.socket && this.socket.readyState !== WEBSOCKET_CLOSED) {
this.socket.close(code, reason);
}
this.socket = null;
this.connectPromise = null;
}
/** Sends one OneBot action over WebSocket and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
throwIfAborted(options?.signal);
await raceWithAbort(this.connect(), options?.signal, 'SnowLuma WebSocket request aborted before connection opened');
throwIfAborted(options?.signal);
const socket = this.socket;
if (!socket || socket.readyState !== WEBSOCKET_OPEN) {
throw new SnowLumaConnectionError('SnowLuma WebSocket is not open');
}
const echo = options?.echo ?? createEcho();
const key = echoKey(echo);
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const promise = new Promise<ApiResponse>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | null = null;
let abortListener: (() => void) | undefined;
const cleanup = (): void => {
if (timer) clearTimeout(timer);
if (abortListener) options?.signal?.removeEventListener('abort', abortListener);
};
timer = timeoutMs > 0
? setTimeout(() => {
this.pending.delete(key);
cleanup();
reject(new SnowLumaTimeoutError(`SnowLuma WebSocket request timed out after ${timeoutMs}ms`, timeoutMs));
}, timeoutMs)
: null;
abortListener = () => {
this.pending.delete(key);
cleanup();
reject(new SnowLumaAbortError('SnowLuma WebSocket request aborted', { cause: options?.signal?.reason }));
};
options?.signal?.addEventListener('abort', abortListener, { once: true });
this.pending.set(key, { resolve, reject, timer, cleanup });
});
try {
socket.send(JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo,
}));
} catch (error) {
const pending = this.pending.get(key);
pending?.cleanup?.();
this.pending.delete(key);
throw new SnowLumaConnectionError('Failed to send SnowLuma WebSocket request', { cause: error });
}
return promise as Promise<ApiResponse<ActionResult<TAction>>>;
}
private bindSocket(socket: WebSocketLike): void {
addSocketListener(socket, 'message', (...args) => this.handleMessage(args));
addSocketListener(socket, 'error', (error) => this.emitter.emit('error', unwrapEventPayload(error)));
addSocketListener(socket, 'close', (...args) => this.handleClose(args));
}
private handleMessage(args: unknown[]): void {
const raw = unwrapMessagePayload(args[0]);
this.emitter.emit('raw', raw);
let parsed: unknown;
try {
parsed = JSON.parse(rawToString(raw));
} catch (error) {
this.emitter.emit('error', new SnowLumaParseError('SnowLuma WebSocket returned non-JSON message', { cause: error }));
return;
}
if (isJsonObject(parsed) && parsed.echo !== undefined) {
const key = echoKey(parsed.echo as JsonValue);
const pending = this.pending.get(key);
if (pending) {
this.pending.delete(key);
pending.cleanup?.();
try {
const response = assertApiResponse(parsed);
pending.resolve(response);
this.emitter.emit('response', response);
} catch (error) {
pending.reject(new SnowLumaParseError('SnowLuma WebSocket response is invalid', { cause: error }));
}
return;
}
}
if (isJsonObject(parsed) && typeof parsed.post_type === 'string') {
void this.dispatchEvent(parsed as SnowLumaEvent).catch((error) => {
this.emitter.emit('error', error);
});
}
}
private async dispatchEvent(event: SnowLumaEvent): Promise<void> {
const context = createEventContext(event, this);
let index = -1;
const next = async (): Promise<void> => {
index += 1;
const middleware = this.middlewares[index];
if (!middleware || context.stopped) return;
await middleware(event, context, next);
};
await next();
if (!context.stopped && index >= this.middlewares.length - 1) {
this.emitter.emit('event', event);
}
}
private handleClose(args: unknown[]): void {
const info = closeInfo(args);
this.socket = null;
this.connectPromise = null;
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket closed'));
this.emitter.emit('close', info);
if (!this.closedByUser && this.reconnect) {
this.scheduleReconnect();
}
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
const reconnect = this.reconnect;
if (!reconnect) return;
const retries = reconnect.retries ?? Number.POSITIVE_INFINITY;
if (this.reconnectAttempts >= retries) return;
const minDelay = reconnect.minDelayMs ?? 1000;
const maxDelay = reconnect.maxDelayMs ?? 30_000;
const delay = Math.min(maxDelay, minDelay * 2 ** this.reconnectAttempts);
this.reconnectAttempts += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
void this.connect().catch((error) => {
this.emitter.emit('error', error);
if (!this.closedByUser) this.scheduleReconnect();
});
}, delay);
}
private rejectPending(error: Error): void {
for (const pending of this.pending.values()) {
pending.cleanup?.();
pending.reject(error);
}
this.pending.clear();
}
}
export function createWebSocketClient(options?: SnowLumaWebSocketClientOptions): SnowLumaWebSocketClient {
return new SnowLumaWebSocketClient(options);
}

View File

@@ -0,0 +1,64 @@
import type {
ApiResponse,
SnowLumaClientOptions,
SnowLumaEvent,
WsRole,
} from '../types/index';
export interface WebSocketLike {
readyState: number;
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
removeEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
on?: (event: string, listener: (...args: unknown[]) => void) => void;
off?: (event: string, listener: (...args: unknown[]) => void) => void;
removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
}
export type WebSocketConstructor = new (url: string, protocols?: string | string[]) => WebSocketLike;
/** Reconnect policy for the WebSocket client. */
export interface ReconnectOptions {
/** Maximum reconnect attempts. Omit for unlimited retries. */
retries?: number;
/** Initial reconnect delay in milliseconds. Defaults to 1000. */
minDelayMs?: number;
/** Maximum reconnect delay in milliseconds. Defaults to 30000. */
maxDelayMs?: number;
}
/** Options for the WebSocket transport client. */
export interface SnowLumaWebSocketClientOptions extends SnowLumaClientOptions {
/** OneBot WebSocket endpoint. Defaults to ws://127.0.0.1:3001/. */
url?: string;
/** OneBot WebSocket role advertised by the client. */
role?: WsRole;
/** Optional WebSocket protocols argument. */
protocols?: string | string[];
/** Custom WebSocket constructor for Node runtimes or tests. */
webSocket?: WebSocketConstructor;
/** Enables or configures automatic reconnect after unexpected close. */
reconnect?: boolean | ReconnectOptions;
}
export interface WebSocketCloseInfo {
code?: number;
reason?: string;
}
export interface SnowLumaWebSocketEvents {
open: undefined;
close: WebSocketCloseInfo;
error: unknown;
event: SnowLumaEvent;
response: ApiResponse;
raw: unknown;
}
export interface PendingRequest {
resolve: (response: ApiResponse) => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout> | null;
cleanup?: () => void;
}

View File

@@ -0,0 +1,77 @@
import { isJsonObject } from '../internal/json';
import type {
ReconnectOptions,
WebSocketCloseInfo,
WebSocketLike,
} from './websocket-types';
export const WEBSOCKET_OPEN = 1;
export const WEBSOCKET_CLOSED = 3;
export function normalizeReconnect(value: boolean | ReconnectOptions | undefined): ReconnectOptions | null {
if (!value) return null;
if (value === true) return {};
return value;
}
export function addSocketListener(
socket: WebSocketLike,
event: string,
listener: (...args: unknown[]) => void,
): () => void {
if (socket.addEventListener) {
socket.addEventListener(event, listener);
return () => socket.removeEventListener?.(event, listener);
}
if (socket.on) {
socket.on(event, listener);
return () => {
if (socket.off) socket.off(event, listener);
else socket.removeListener?.(event, listener);
};
}
return () => undefined;
}
export function unwrapMessagePayload(value: unknown): unknown {
if (isJsonObject(value) && 'data' in value) {
return value.data;
}
return value;
}
export function unwrapEventPayload(value: unknown): unknown {
if (isJsonObject(value) && 'error' in value) {
return value.error;
}
return value;
}
export function rawToString(value: unknown): string {
if (typeof value === 'string') return value;
if (value instanceof ArrayBuffer) return new TextDecoder().decode(value);
if (ArrayBuffer.isView(value)) {
return new TextDecoder().decode(value);
}
if (value instanceof Blob) {
throw new Error('Blob WebSocket messages are not supported synchronously');
}
if (value && typeof value === 'object' && 'toString' in value && typeof value.toString === 'function') {
return value.toString();
}
return String(value);
}
export function closeInfo(args: unknown[]): WebSocketCloseInfo {
const first = args[0];
if (isJsonObject(first)) {
return {
code: typeof first.code === 'number' ? first.code : undefined,
reason: typeof first.reason === 'string' ? first.reason : undefined,
};
}
return {
code: typeof args[0] === 'number' ? args[0] : undefined,
reason: typeof args[1] === 'string' ? args[1] : undefined,
};
}

View File

@@ -0,0 +1,39 @@
type Listener<TPayload> = (payload: TPayload) => void;
export class Emitter<TEvents extends object> {
private readonly listeners = new Map<keyof TEvents, Set<Listener<never>>>();
on<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): () => void {
let set = this.listeners.get(event);
if (!set) {
set = new Set();
this.listeners.set(event, set);
}
set.add(listener as Listener<never>);
return () => this.off(event, listener);
}
once<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): () => void {
const off = this.on(event, (payload) => {
off();
listener(payload);
});
return off;
}
off<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): void {
this.listeners.get(event)?.delete(listener as Listener<never>);
}
emit<TKey extends keyof TEvents>(event: TKey, payload: TEvents[TKey]): void {
const set = this.listeners.get(event);
if (!set) return;
for (const listener of [...set]) {
listener(payload as never);
}
}
clear(): void {
this.listeners.clear();
}
}

View File

@@ -0,0 +1,83 @@
import type { ApiResponse } from './types/index';
/** Base error for every exception intentionally thrown by the SnowLuma SDK. */
export class SnowLumaError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaError';
}
}
/** Transport-layer failures before a valid OneBot API response is available. */
export class SnowLumaTransportError extends SnowLumaError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaTransportError';
}
}
/** The request was cancelled by the caller's AbortSignal. */
export class SnowLumaAbortError extends SnowLumaTransportError {
constructor(message = 'SnowLuma request aborted', options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaAbortError';
}
}
/** The request exceeded the configured timeout. */
export class SnowLumaTimeoutError extends SnowLumaTransportError {
readonly timeoutMs: number;
constructor(message: string, timeoutMs: number, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaTimeoutError';
this.timeoutMs = timeoutMs;
}
}
/** The SDK could not establish or keep a connection to SnowLuma. */
export class SnowLumaConnectionError extends SnowLumaTransportError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaConnectionError';
}
}
/** SnowLuma returned a payload that could not be parsed as the expected protocol shape. */
export class SnowLumaParseError extends SnowLumaTransportError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaParseError';
}
}
/** A OneBot API response with status failed or a non-zero retcode. */
export class SnowLumaApiError<TData = unknown> extends SnowLumaError {
readonly response: ApiResponse<TData>;
readonly retcode: number;
readonly wording?: string;
constructor(response: ApiResponse<TData>) {
super(response.wording || `SnowLuma API failed with retcode ${response.retcode}`);
this.name = 'SnowLumaApiError';
this.response = response;
this.retcode = response.retcode;
this.wording = response.wording;
}
}
/** Authentication or authorization failure returned by SnowLuma. */
export class SnowLumaAuthError<TData = unknown> extends SnowLumaApiError<TData> {
constructor(response: ApiResponse<TData>) {
super(response);
this.name = 'SnowLumaAuthError';
}
}
export function createSnowLumaApiError<TData>(response: ApiResponse<TData>): SnowLumaApiError<TData> {
return isAuthFailure(response) ? new SnowLumaAuthError(response) : new SnowLumaApiError(response);
}
function isAuthFailure(response: ApiResponse<unknown>): boolean {
return response.retcode === 1401 || response.retcode === 401 || response.retcode === 403;
}

View File

@@ -0,0 +1,55 @@
import type { OneBotMessageEvent } from '../types/index';
import type { CommandMatch, CommandOptions } from './types';
export function matchCommand(
event: OneBotMessageEvent,
command: string | RegExp,
options: CommandOptions = {},
): CommandMatch | null {
const trim = options.trim ?? true;
const raw = trim ? event.raw_message.trim() : event.raw_message;
const prefixes = normalizePrefixes(options.prefixes ?? '/');
for (const prefix of prefixes) {
if (prefix && !raw.startsWith(prefix)) continue;
const text = prefix ? raw.slice(prefix.length).trimStart() : raw;
if (!text) continue;
if (command instanceof RegExp) {
const match = text.match(command);
if (!match || match.index !== 0) continue;
const matchedText = match[0] ?? '';
const rest = text.slice(matchedText.length).trim();
return {
command: matchedText,
text,
args: rest ? rest.split(/\s+/) : [],
rest,
prefix,
match,
};
}
const [head = '', ...args] = text.split(/\s+/);
const matches = options.caseSensitive
? head === command
: head.toLowerCase() === command.toLowerCase();
if (!matches) continue;
return {
command: head,
text,
args,
rest: text.slice(head.length).trim(),
prefix,
match: null,
};
}
return null;
}
function normalizePrefixes(prefixes: string | string[]): string[] {
return Array.isArray(prefixes) ? prefixes : [prefixes];
}

View File

@@ -0,0 +1,73 @@
import type { SnowLumaApiClient } from '../client/api-client';
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<TEvent extends SnowLumaEvent>(
event: TEvent,
client: SnowLumaApiClient,
): SnowLumaEventContext<TEvent> {
let stopped = false;
const context: SnowLumaEventContext<TEvent> = {
event,
client,
get stopped() {
return stopped;
},
stopPropagation() {
stopped = true;
},
async reply(message, options) {
if (isGroupMessageEvent(event)) {
return client.sendGroupMessage(event.group_id, message, options);
}
if (isPrivateMessageEvent(event)) {
return client.sendPrivateMessage(event.user_id, message, options);
}
throw new Error('reply() is only available for message events');
},
async approve(options) {
if (!isRequestEvent(event)) {
throw new Error('approve() is only available for request events');
}
if (event.request_type === 'friend') {
return client.setFriendAddRequest(event.flag, true, options);
}
if (event.request_type === 'group') {
return client.setGroupAddRequest(event.flag, {
...options,
subType: options?.subType ?? event.sub_type,
approve: true,
});
}
throw new Error(`approve() does not support request_type=${event.request_type}`);
},
async reject(reason, options) {
if (!isRequestEvent(event)) {
throw new Error('reject() is only available for request events');
}
if (event.request_type === 'friend') {
return client.setFriendAddRequest(event.flag, false, options);
}
if (event.request_type === 'group') {
return client.setGroupAddRequest(event.flag, {
...options,
subType: options?.subType ?? event.sub_type,
approve: false,
reason: reason ?? options?.reason,
});
}
throw new Error(`reject() does not support request_type=${event.request_type}`);
},
async quickOperation(operation, options) {
return client.raw('.handle_quick_operation', {
context: event,
operation,
}, options);
},
};
return context;
}

View File

@@ -0,0 +1,43 @@
import type {
OneBotGroupMessageEvent,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotPrivateMessageEvent,
OneBotRequestEvent,
SnowLumaEvent,
} from '../types/index';
import type { EventPredicate } from './types';
export function isMessageEvent(event: SnowLumaEvent): event is OneBotMessageEvent {
return (event.post_type === 'message' || event.post_type === 'message_sent')
&& (event.message_type === 'private' || event.message_type === 'group');
}
export function isPrivateMessageEvent(event: SnowLumaEvent): event is OneBotPrivateMessageEvent {
return isMessageEvent(event) && event.message_type === 'private';
}
export function isGroupMessageEvent(event: SnowLumaEvent): event is OneBotGroupMessageEvent {
return isMessageEvent(event) && event.message_type === 'group';
}
export function isNoticeEvent(event: SnowLumaEvent): event is OneBotNoticeEvent {
return event.post_type === 'notice' && typeof event.notice_type === 'string';
}
export function isRequestEvent(event: SnowLumaEvent): event is OneBotRequestEvent {
return event.post_type === 'request' && typeof event.request_type === 'string' && typeof event.flag === 'string';
}
export function isMetaEvent(event: SnowLumaEvent): event is OneBotMetaEvent {
return event.post_type === 'meta_event' && typeof event.meta_event_type === 'string';
}
export function noticeType(type: string): EventPredicate<OneBotNoticeEvent> {
return (event): event is OneBotNoticeEvent => isNoticeEvent(event) && event.notice_type === type;
}
export function requestType(type: string): EventPredicate<OneBotRequestEvent> {
return (event): event is OneBotRequestEvent => isRequestEvent(event) && event.request_type === type;
}

View File

@@ -0,0 +1,4 @@
export * from './types';
export * from './guards';
export * from './context';
export * from './command';

View File

@@ -0,0 +1,73 @@
import type { SnowLumaApiClient } from '../client/api-client';
import type {
JsonObject,
OneBotMessageEvent,
OutgoingMessage,
RequestOptions,
SnowLumaEvent,
} from '../types/index';
export type MaybePromise<T = void> = T | Promise<T>;
export type EventNext = () => Promise<void>;
/** Type guard or predicate used by client.when(). */
export type EventPredicate<TEvent extends SnowLumaEvent = SnowLumaEvent> = (event: SnowLumaEvent) => event is TEvent;
/** Handler for one narrowed SnowLuma event. */
export type EventHandler<TEvent extends SnowLumaEvent = SnowLumaEvent> = (
event: TEvent,
context: SnowLumaEventContext<TEvent>,
) => 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<TEvent extends SnowLumaEvent = SnowLumaEvent> {
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<unknown>;
/** Approves a friend or group request event. */
approve(options?: RequestDecisionOptions): Promise<unknown>;
/** Rejects a friend or group request event. */
reject(reason?: string, options?: RequestDecisionOptions): Promise<unknown>;
/** Sends OneBot .handle_quick_operation with the current event as context. */
quickOperation(operation: JsonObject, options?: RequestOptions): Promise<unknown>;
}
/** 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;
args: string[];
rest: string;
prefix: string;
match: RegExpMatchArray | null;
}
export type CommandHandler<TEvent extends OneBotMessageEvent = OneBotMessageEvent> = (
event: TEvent,
context: SnowLumaEventContext<TEvent> & { command: CommandMatch },
match: CommandMatch,
) => MaybePromise;

88
packages/sdk/src/index.ts Normal file
View File

@@ -0,0 +1,88 @@
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 {
SnowLumaAbortError,
SnowLumaApiError,
SnowLumaAuthError,
SnowLumaConnectionError,
SnowLumaError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError,
createSnowLumaApiError,
} from './errors';
export {
MessageChain,
at,
atAll,
br,
chain,
contact,
escapeCqParam,
escapeCqText,
face,
forward,
image,
json,
location,
message,
music,
node,
normalizeMessage,
parseSegments,
poke,
raw,
record,
reply,
share,
text,
toCQString,
video,
xml,
fromCQString,
} 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,
} from './client/websocket-client';
export type {
CommandHandler,
CommandMatch,
CommandOptions,
EventHandler,
EventMiddleware,
EventNext,
EventPredicate,
MaybePromise,
RequestDecisionOptions,
SnowLumaEventContext,
} from './events/index';
export type * from './types/index';

View File

@@ -0,0 +1,82 @@
import { SnowLumaAbortError } from '../errors';
export interface RequestAbortState {
signal: AbortSignal;
cleanup(): void;
isTimedOut(): boolean;
isExternallyAborted(): boolean;
}
export function createRequestAbortState(
timeoutMs: number,
externalSignal?: AbortSignal,
): RequestAbortState {
const controller = new AbortController();
let timedOut = false;
let externallyAborted = false;
const onExternalAbort = (): void => {
externallyAborted = true;
controller.abort(externalSignal?.reason);
};
if (externalSignal?.aborted) {
onExternalAbort();
} else {
externalSignal?.addEventListener('abort', onExternalAbort, { once: true });
}
const timer = timeoutMs > 0
? setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs)
: null;
return {
signal: controller.signal,
cleanup() {
if (timer) clearTimeout(timer);
externalSignal?.removeEventListener('abort', onExternalAbort);
},
isTimedOut() {
return timedOut;
},
isExternallyAborted() {
return externallyAborted || externalSignal?.aborted === true;
},
};
}
export function throwIfAborted(signal?: AbortSignal, message = 'SnowLuma request aborted'): void {
if (signal?.aborted) {
throw new SnowLumaAbortError(message, { cause: signal.reason });
}
}
export function isAbortError(error: unknown): boolean {
return typeof error === 'object'
&& error !== null
&& 'name' in error
&& (error as { name?: unknown }).name === 'AbortError';
}
export function raceWithAbort<T>(
promise: Promise<T>,
signal?: AbortSignal,
message = 'SnowLuma request aborted',
): Promise<T> {
if (!signal) return promise;
throwIfAborted(signal, message);
return new Promise<T>((resolve, reject) => {
const onAbort = (): void => {
reject(new SnowLumaAbortError(message, { cause: signal.reason }));
};
signal.addEventListener('abort', onAbort, { once: true });
promise.then(resolve, reject).finally(() => {
signal.removeEventListener('abort', onAbort);
});
});
}

View File

@@ -0,0 +1,64 @@
import type { ApiResponse, JsonObject, JsonValue } from '../types/index';
export function isJsonObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function asJsonValue(value: unknown): JsonValue {
if (value === null) return null;
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return value;
}
if (Array.isArray(value)) return value.map(asJsonValue);
if (isJsonObject(value)) {
const out: JsonObject = {};
for (const [key, item] of Object.entries(value)) {
if (item === undefined) continue;
out[key] = asJsonValue(item);
}
return out;
}
return String(value);
}
export function assertApiResponse(value: unknown): ApiResponse {
if (!isJsonObject(value)) {
throw new Error('response is not a JSON object');
}
const status = value.status === 'ok' ? 'ok' : value.status === 'failed' ? 'failed' : null;
if (!status) {
throw new Error('response status is missing or invalid');
}
const retcode = typeof value.retcode === 'number' && Number.isFinite(value.retcode)
? value.retcode
: status === 'ok' ? 0 : -1;
return {
status,
retcode,
data: asJsonValue(value.data ?? null),
echo: value.echo === undefined ? undefined : asJsonValue(value.echo),
wording: typeof value.wording === 'string' ? value.wording : undefined,
};
}
export function createEcho(): string {
const random = Math.random().toString(36).slice(2);
return `snowluma-sdk:${Date.now().toString(36)}:${random}`;
}
export function echoKey(value: JsonValue | undefined): string {
if (value === undefined) return '';
return JSON.stringify(value);
}
export function appendAccessToken(urlValue: string, accessToken?: string): string {
if (!accessToken) return urlValue;
const url = new URL(urlValue);
if (!url.searchParams.has('access_token')) {
url.searchParams.set('access_token', accessToken);
}
return url.toString();
}

View File

@@ -0,0 +1,306 @@
import { segments } from './segments';
import { segmentsToCQString } from './cq-format';
import type {
AnyMessageSegment,
ContactSegment,
ImageSegment,
JsonObject,
LocationSegment,
MessageChainLike,
MessageSegment,
MusicSegment,
OutgoingMessage,
RecordSegment,
RequestOptions,
ShareSegment,
VideoSegment,
XmlSegment,
} from '../types/index';
export interface MessageChainSender {
sendGroupMessage(groupId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
sendPrivateMessage(userId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
}
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<THasReply extends boolean = false> implements MessageChainLike {
private readonly replyStateBrand?: THasReply;
private constructor(
private readonly items: AnyMessageSegment[] = [],
private readonly used: ReadonlySet<string> = new Set(),
) {}
static empty(): MessageChain<false> {
return new MessageChain<false>();
}
/** 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<THasReply> {
return this.addSegment(segments.text(text));
}
/** Appends a newline text segment. */
br(): MessageChain<THasReply> {
return this.text('\n');
}
face(id: number | string): MessageChain<THasReply> {
return this.addSegment(segments.face(id));
}
/** Mentions a user or everyone in a group. */
at(qq: number | 'all', options: { name?: string; uid?: string } = {}): MessageChain<THasReply> {
return this.addSegment(segments.at(qq, options));
}
atAll(): MessageChain<THasReply> {
return this.at('all');
}
/** Adds a reply segment. A chain can contain at most one reply segment. */
reply(this: MessageChain<false>, id: number | string): MessageChain<true> {
return this.addSegment(segments.reply(id), 'reply') as MessageChain<true>;
}
/** Appends an image segment from a URL, local path, file id, or base64 URI. */
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.image(file, options));
}
record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.record(file, options));
}
video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.video(file, options));
}
json(data: string | JsonObject): MessageChain<THasReply> {
return this.addSegment(segments.json(data));
}
xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.xml(data, options));
}
poke(type: number | string, id?: number | string): MessageChain<THasReply> {
return this.addSegment(segments.poke(type, id));
}
forward(id: string): MessageChain<THasReply> {
return this.addSegment(segments.forward(id));
}
node(userId: number, nickname: string, content: OutgoingMessage): MessageChain<THasReply> {
return this.addSegment(segments.node(userId, nickname, content));
}
share(options: ShareSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.share(options));
}
music(options: MusicSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.music(options));
}
location(options: LocationSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.location(options));
}
contact(type: ContactSegment['data']['type'], id: number | string): MessageChain<THasReply> {
return this.addSegment(segments.contact(type, id));
}
raw<TType extends string, TData extends JsonObject>(type: TType, data: TData): MessageChain<THasReply> {
return this.addSegment(segments.raw(type, data), type);
}
/** Appends another outgoing message while preserving single-use segment checks. */
append(messageInput: OutgoingMessage): MessageChain<THasReply> {
let next: MessageChain<THasReply> = this;
const normalized = normalizeMessage(messageInput);
if (typeof normalized === 'string') {
return next.text(normalized);
}
for (const segment of normalized) {
next = next.addFromSegment(segment);
}
return next;
}
/** Returns a fresh segment array suitable for OneBot array message format. */
build(): AnyMessageSegment[] {
return this.toSegments();
}
toArray(): AnyMessageSegment[] {
return this.toSegments();
}
toSegments(): AnyMessageSegment[] {
return [...this.items];
}
toJSON(): AnyMessageSegment[] {
return this.toSegments();
}
toString(): string {
return segmentsToCQString(this.items);
}
/** Sends this chain to a group through a compatible SnowLuma client. */
sendToGroup(
client: MessageChainSender,
groupId: number,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown> {
return client.sendGroupMessage(groupId, this, options);
}
/** Sends this chain to a private chat through a compatible SnowLuma client. */
sendToPrivate(
client: MessageChainSender,
userId: number,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown> {
return client.sendPrivateMessage(userId, this, options);
}
[Symbol.iterator](): IterableIterator<AnyMessageSegment> {
return this.items[Symbol.iterator]();
}
private addFromSegment(segment: AnyMessageSegment): MessageChain<THasReply> {
return this.addSegment(segment, segment.type);
}
private addSegment<TNextReply extends boolean = THasReply>(
segment: AnyMessageSegment,
singleUseType?: string,
): MessageChain<TNextReply> {
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType) && this.used.has(singleUseType)) {
throw new Error(`Message segment "${singleUseType}" can only appear once in a chain`);
}
const nextUsed = new Set(this.used);
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType)) {
nextUsed.add(singleUseType);
}
return new MessageChain<TNextReply>([...this.items, segment], nextUsed);
}
}
export function chain(): MessageChain<false> {
return MessageChain.empty();
}
/** Starts a message chain with a text segment. */
export function text(value = ''): MessageChain<false> {
return chain().text(value);
}
export function br(): MessageChain<false> {
return chain().br();
}
export function face(id: number | string): MessageChain<false> {
return chain().face(id);
}
export function at(qq: number | 'all', options: { name?: string; uid?: string } = {}): MessageChain<false> {
return chain().at(qq, options);
}
export function atAll(): MessageChain<false> {
return chain().atAll();
}
export function reply(id: number | string): MessageChain<true> {
return chain().reply(id);
}
/** Starts a message chain with an image segment. */
export function image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().image(file, options);
}
export function record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().record(file, options);
}
export function video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().video(file, options);
}
export function json(data: string | JsonObject): MessageChain<false> {
return chain().json(data);
}
export function xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): MessageChain<false> {
return chain().xml(data, options);
}
export function poke(type: number | string, id?: number | string): MessageChain<false> {
return chain().poke(type, id);
}
export function forward(id: string): MessageChain<false> {
return chain().forward(id);
}
export function node(userId: number, nickname: string, content: OutgoingMessage): MessageChain<false> {
return chain().node(userId, nickname, content);
}
export function share(options: ShareSegment['data']): MessageChain<false> {
return chain().share(options);
}
export function music(options: MusicSegment['data']): MessageChain<false> {
return chain().music(options);
}
export function location(options: LocationSegment['data']): MessageChain<false> {
return chain().location(options);
}
export function contact(type: ContactSegment['data']['type'], id: number | string): MessageChain<false> {
return chain().contact(type, id);
}
export function raw<TType extends string, TData extends JsonObject>(type: TType, data: TData): MessageChain<false> {
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();
return Array.isArray(input) ? input : [input];
}
function isMessageChainLike(value: unknown): value is MessageChainLike {
return typeof value === 'object'
&& value !== null
&& 'toSegments' in value
&& typeof value.toSegments === 'function';
}

View File

@@ -0,0 +1,29 @@
import type { KnownMessageSegment, MessageSegment } from '../types/index';
export function escapeCqText(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/\[/g, '&#91;')
.replace(/\]/g, '&#93;');
}
export function escapeCqParam(text: string): string {
return escapeCqText(text).replace(/,/g, '&#44;');
}
export function segmentsToCQString(segments: Array<KnownMessageSegment | MessageSegment>): string {
return segments.map(segmentToCq).join('');
}
function segmentToCq(segment: KnownMessageSegment | MessageSegment): string {
if (segment.type === 'text') {
return escapeCqText(String(segment.data.text ?? ''));
}
const params = Object.entries(segment.data)
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${key}=${escapeCqParam(String(value))}`)
.join(',');
return params ? `[CQ:${segment.type},${params}]` : `[CQ:${segment.type}]`;
}

View File

@@ -0,0 +1,105 @@
import { normalizeMessage, chain } from './chain';
import { escapeCqText, segmentsToCQString } from './cq-format';
import { segments } from './segments';
import type { AnyMessageSegment, OutgoingMessage } from '../types/index';
const CQ_REGEX = /\[CQ:([a-zA-Z0-9_.-]+)(?:,([^\]]*))?\]/g;
export function toCQString(input: OutgoingMessage): string {
if (typeof input === 'string') return escapeCqText(input);
const normalized = normalizeMessage(input);
return typeof normalized === 'string'
? escapeCqText(normalized)
: segmentsToCQString(normalized);
}
export function fromCQString(input: string) {
let current = chain();
let lastIndex = 0;
for (const match of input.matchAll(CQ_REGEX)) {
const index = match.index ?? 0;
if (index > lastIndex) {
const textValue = cqUnescape(input.slice(lastIndex, index));
if (textValue) current = current.text(textValue);
}
const segment = segmentFromCq(match[1] ?? '', parseCQParams(match[2] ?? ''));
if (segment) current = current.append(segment);
lastIndex = index + match[0].length;
}
if (lastIndex < input.length) {
const textValue = cqUnescape(input.slice(lastIndex));
if (textValue) current = current.text(textValue);
}
return current;
}
export function parseSegments(input: string): AnyMessageSegment[] {
return fromCQString(input).toSegments();
}
function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
if (!raw) return params;
for (const pair of raw.split(',')) {
const eq = pair.indexOf('=');
if (eq <= 0) continue;
params[pair.slice(0, eq)] = cqUnescapeParam(pair.slice(eq + 1));
}
return params;
}
function cqUnescape(text: string): string {
return text
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&amp;/g, '&');
}
function cqUnescapeParam(text: string): string {
return cqUnescape(text).replace(/&#44;/g, ',');
}
function segmentFromCq(type: string, data: Record<string, string>): AnyMessageSegment | null {
switch (type) {
case 'text':
return segments.text(data.text ?? '');
case 'face':
return segments.face(data.id ?? '0');
case 'at':
if (data.qq === 'all') return segments.at('all');
{
const qq = Number(data.qq);
return Number.isFinite(qq) && qq > 0
? segments.at(qq, { name: data.name, uid: data.uid })
: segments.raw(type, data);
}
case 'reply':
return segments.reply(data.id ?? '0');
case 'image':
return segments.image(data.file ?? data.url ?? '', {
url: data.url,
type: data.type === 'flash' ? 'flash' : undefined,
summary: data.summary,
});
case 'record':
return segments.record(data.file ?? data.url ?? '', { url: data.url });
case 'video':
return segments.video(data.file ?? data.url ?? '', { url: data.url, thumb: data.thumb });
case 'json':
return segments.json(data.data ?? '');
case 'xml':
return segments.xml(data.data ?? '', { id: data.id });
case 'poke':
return segments.poke(data.type ?? data.id ?? '0', data.id);
case 'forward':
return segments.forward(data.id ?? data.res_id ?? data.forward_id ?? '');
default:
return segments.raw(type, data);
}
}

View File

@@ -0,0 +1,33 @@
import { segments } from './segments';
export { MessageChain } from './chain';
export {
at,
atAll,
br,
chain,
contact,
face,
forward,
image,
json,
location,
music,
node,
normalizeMessage,
poke,
raw,
record,
reply,
share,
text,
video,
xml,
} from './chain';
export { escapeCqParam, escapeCqText } from './cq-format';
export { fromCQString, parseSegments, toCQString } from './cq';
export { segments };
export const message = {
...segments,
};

View File

@@ -0,0 +1,100 @@
import type {
AtSegment,
ContactSegment,
FaceSegment,
ForwardSegment,
ImageSegment,
JsonObject,
JsonSegment,
LocationSegment,
MessageSegment,
MusicSegment,
NodeSegment,
OutgoingMessage,
PokeSegment,
RecordSegment,
ReplySegment,
ShareSegment,
TextSegment,
VideoSegment,
XmlSegment,
} from '../types/index';
function seg<TType extends string, TData extends Record<string, unknown>>(type: TType, data: TData): MessageSegment<TType, TData> {
return { type, data };
}
export const segments = {
text(text: string): TextSegment {
return seg('text', { text });
},
face(id: number | string): FaceSegment {
return seg('face', { id: String(id) });
},
at(qq: number | 'all', options: { name?: string; uid?: string } = {}): AtSegment {
const data: AtSegment['data'] = { qq: String(qq) };
if (options.name) data.name = options.name;
if (options.uid) data.uid = options.uid;
return seg('at', data);
},
reply(id: number | string): ReplySegment {
return seg('reply', { id: String(id) });
},
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): ImageSegment {
return seg('image', { file, ...options });
},
record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): RecordSegment {
return seg('record', { file, ...options });
},
video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): VideoSegment {
return seg('video', { file, ...options });
},
json(data: string | JsonObject): JsonSegment {
return seg('json', { data: typeof data === 'string' ? data : JSON.stringify(data) });
},
xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): XmlSegment {
return seg('xml', { data, ...options });
},
poke(type: number | string, id?: number | string): PokeSegment {
const data: PokeSegment['data'] = { type };
if (id !== undefined) data.id = id;
return seg('poke', data);
},
forward(id: string): ForwardSegment {
return seg('forward', { id, res_id: id, forward_id: id });
},
node(userId: number, nickname: string, content: OutgoingMessage): NodeSegment {
return seg('node', { user_id: userId, nickname, content });
},
share(options: ShareSegment['data']): ShareSegment {
return seg('share', options);
},
music(options: MusicSegment['data']): MusicSegment {
return seg('music', options);
},
location(options: LocationSegment['data']): LocationSegment {
return seg('location', options);
},
contact(type: ContactSegment['data']['type'], id: number | string): ContactSegment {
return seg('contact', { type, id });
},
raw<TType extends string, TData extends JsonObject>(type: TType, data: TData): MessageSegment<TType, TData> {
return seg(type, data);
},
};

View File

@@ -0,0 +1,208 @@
import type { JsonArray, JsonObject, JsonValue } from './json';
import type {
CreateGroupFileFolderParams,
DeleteFriendParams,
DeleteGroupFileFolderParams,
DeleteGroupFileParams,
DomainParams,
DownloadFileParams,
ForwardMessageParams,
FriendPokeParams,
GetForwardMsgParams,
GetFriendMessageHistoryParams,
GetGroupFilesParams,
GetGroupFileUrlParams,
GetGroupHonorInfoParams,
GetGroupInfoParams,
GetGroupListParams,
GetGroupMemberInfoParams,
GetGroupMemberListParams,
GetGroupMessageHistoryParams,
GetMediaParams,
GetPrivateFileUrlParams,
GroupForwardMessageParams,
GroupIdParams,
GroupNoticeParams,
GroupPokeParams,
MarkGroupMsgAsReadParams,
MarkMsgAsReadParams,
MarkPrivateMsgAsReadParams,
MessageIdParams,
MoveGroupFileParams,
PrivateForwardMessageParams,
RenameGroupFileFolderParams,
SendGroupMsgParams,
SendLikeParams,
SendMsgParams,
SendPokeParams,
SendPrivateMsgParams,
SetFriendAddRequestParams,
SetFriendRemarkParams,
SetGroupAddRequestParams,
SetGroupAdminParams,
SetGroupBanParams,
SetGroupCardParams,
SetGroupKickParams,
SetGroupNameParams,
SetGroupReactionParams,
SetGroupSpecialTitleParams,
SetGroupWholeBanParams,
SetMsgEmojiLikeParams,
SetOnlineStatusParams,
SetQqProfileParams,
UploadGroupFileParams,
UploadPrivateFileParams,
UserIdParams,
QuickOperationParams,
} from './params';
import type {
CapabilityInfo,
ClientKeyInfo,
CookieInfo,
CredentialsInfo,
CsrfInfo,
DownloadFileResult,
EmptyData,
ForwardMessageResult,
FriendMessageHistory,
GroupAtAllRemainInfo,
GroupFileSystemInfo,
GroupFileUrl,
GroupMessageHistory,
LoginInfo,
MediaInfo,
OnlineClientsInfo,
PrivateFileUrl,
SendMessageResult,
StatusInfo,
UploadForwardResult,
UrlSafetyInfo,
VersionInfo,
} from './results';
export type ActionData = JsonValue;
export interface SnowLumaActionMap {
get_login_info: { params: JsonObject; data: LoginInfo };
get_status: { params: JsonObject; data: StatusInfo };
get_version_info: { params: JsonObject; data: VersionInfo };
can_send_image: { params: JsonObject; data: CapabilityInfo };
can_send_record: { params: JsonObject; data: CapabilityInfo };
send_msg: { params: SendMsgParams; data: SendMessageResult };
send_private_msg: { params: SendPrivateMsgParams; data: SendMessageResult };
send_group_msg: { params: SendGroupMsgParams; data: SendMessageResult };
get_msg: { params: MessageIdParams; data: JsonObject };
delete_msg: { params: MessageIdParams; data: EmptyData };
get_friend_list: { params: JsonObject; data: JsonObject[] };
get_stranger_info: { params: UserIdParams; data: JsonObject };
delete_friend: { params: DeleteFriendParams; data: EmptyData };
get_group_list: { params: GetGroupListParams; data: JsonObject[] };
get_group_info: { params: GetGroupInfoParams; data: JsonObject };
get_group_member_list: { params: GetGroupMemberListParams; data: JsonObject[] };
get_group_member_info: { params: GetGroupMemberInfoParams; data: JsonObject };
get_group_honor_info: { params: GetGroupHonorInfoParams; data: JsonValue };
get_group_system_msg: { params: JsonObject; data: JsonObject[] };
set_group_kick: { params: SetGroupKickParams; data: EmptyData };
set_group_ban: { params: SetGroupBanParams; data: EmptyData };
set_group_whole_ban: { params: SetGroupWholeBanParams; data: EmptyData };
set_group_admin: { params: SetGroupAdminParams; data: EmptyData };
set_group_card: { params: SetGroupCardParams; data: EmptyData };
set_group_name: { params: SetGroupNameParams; data: EmptyData };
set_group_leave: { params: GroupIdParams; data: EmptyData };
set_group_special_title: { params: SetGroupSpecialTitleParams; data: EmptyData };
set_group_anonymous: { params: JsonObject; data: EmptyData };
set_group_anonymous_ban: { params: JsonObject; data: EmptyData };
set_group_portrait: { params: JsonObject; data: EmptyData };
upload_group_file: { params: UploadGroupFileParams; data: { file_id: string | null } };
upload_private_file: { params: UploadPrivateFileParams; data: { file_id: string | null } };
get_group_file_url: { params: GetGroupFileUrlParams; data: GroupFileUrl };
get_group_root_files: { params: GroupIdParams; data: JsonObject };
get_group_files_by_folder: { params: GetGroupFilesParams; data: JsonObject };
delete_group_file: { params: DeleteGroupFileParams; data: EmptyData };
move_group_file: { params: MoveGroupFileParams; data: EmptyData };
create_group_file_folder: { params: CreateGroupFileFolderParams; data: EmptyData };
delete_group_file_folder: { params: DeleteGroupFileFolderParams; data: EmptyData };
rename_group_file_folder: { params: RenameGroupFileFolderParams; data: EmptyData };
get_private_file_url: { params: GetPrivateFileUrlParams; data: PrivateFileUrl };
set_friend_add_request: { params: SetFriendAddRequestParams; data: EmptyData };
set_group_add_request: { params: SetGroupAddRequestParams; data: EmptyData };
send_like: { params: SendLikeParams; data: EmptyData };
friend_poke: { params: FriendPokeParams; data: EmptyData };
group_poke: { params: GroupPokeParams; data: EmptyData };
send_poke: { params: SendPokeParams; data: EmptyData };
set_essence_msg: { params: MessageIdParams; data: EmptyData };
delete_essence_msg: { params: MessageIdParams; data: EmptyData };
get_essence_msg_list: { params: GroupIdParams; data: JsonArray };
set_group_reaction: { params: SetGroupReactionParams; data: EmptyData };
get_group_msg_history: { params: GetGroupMessageHistoryParams; data: GroupMessageHistory };
get_friend_msg_history: { params: GetFriendMessageHistoryParams; data: FriendMessageHistory };
mark_group_msg_as_read: { params: MarkGroupMsgAsReadParams; data: EmptyData };
mark_private_msg_as_read: { params: MarkPrivateMsgAsReadParams; data: EmptyData };
mark_msg_as_read: { params: MarkMsgAsReadParams; data: EmptyData };
get_rkey: { params: JsonObject; data: JsonObject[] };
ocr_image: { params: JsonObject; data: JsonValue };
'.ocr_image': { params: JsonObject; data: JsonValue };
_send_group_notice: { params: GroupNoticeParams; data: EmptyData };
_get_group_notice: { params: GroupIdParams; data: JsonArray };
_del_group_notice: { params: JsonObject; data: EmptyData };
upload_forward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
upload_foward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
send_forward_msg: { params: ForwardMessageParams; data: ForwardMessageResult };
send_group_forward_msg: { params: GroupForwardMessageParams; data: ForwardMessageResult };
send_private_forward_msg: { params: PrivateForwardMessageParams; data: ForwardMessageResult };
get_forward_msg: { params: GetForwardMsgParams; data: { messages: JsonObject[] } };
get_image: { params: GetMediaParams; data: MediaInfo };
get_record: { params: GetMediaParams; data: MediaInfo };
get_cookies: { params: DomainParams; data: CookieInfo };
get_csrf_token: { params: JsonObject; data: CsrfInfo };
get_credentials: { params: DomainParams; data: CredentialsInfo };
set_restart: { params: JsonObject; data: EmptyData };
clean_cache: { params: JsonObject; data: EmptyData };
'.handle_quick_operation': { params: QuickOperationParams; data: EmptyData };
set_friend_remark: { params: SetFriendRemarkParams; data: EmptyData };
set_msg_emoji_like: { params: SetMsgEmojiLikeParams; data: EmptyData };
_mark_all_as_read: { params: JsonObject; data: EmptyData };
get_group_file_system_info: { params: GroupIdParams; data: GroupFileSystemInfo };
check_url_safely: { params: JsonObject; data: UrlSafetyInfo };
download_file: { params: DownloadFileParams; data: DownloadFileResult };
set_qq_profile: { params: SetQqProfileParams; data: EmptyData };
set_online_status: { params: SetOnlineStatusParams; data: EmptyData };
get_group_ignored_notifies: { params: JsonObject; data: JsonArray };
get_group_shut_list: { params: JsonObject; data: JsonArray };
forward_friend_single_msg: { params: JsonObject; data: JsonValue };
forward_group_single_msg: { params: JsonObject; data: JsonValue };
get_recent_contact: { params: JsonObject; data: JsonArray };
get_profile_like: { params: JsonObject; data: JsonObject };
get_friends_with_category: { params: JsonObject; data: JsonObject[] };
get_online_clients: { params: JsonObject; data: OnlineClientsInfo };
_get_model_show: { params: JsonObject; data: { variants: JsonArray } };
_set_model_show: { params: JsonObject; data: EmptyData };
'.get_word_slices': { params: JsonObject; data: JsonValue };
get_group_at_all_remain: { params: JsonObject; data: GroupAtAllRemainInfo };
get_unidirectional_friend_list: { params: JsonObject; data: JsonArray };
set_self_longnick: { params: JsonObject; data: EmptyData };
get_collection_list: { params: JsonObject; data: JsonArray };
create_collection: { params: JsonObject; data: JsonValue };
set_qq_avatar: { params: JsonObject; data: EmptyData };
set_input_status: { params: JsonObject; data: EmptyData };
translate_en2zh: { params: JsonObject; data: JsonValue };
get_clientkey: { params: JsonObject; data: ClientKeyInfo };
get_mini_app_ark: { params: JsonObject; data: JsonValue };
click_inline_keyboard_button: { params: JsonObject; data: JsonValue };
set_group_sign: { params: JsonObject; data: EmptyData };
send_group_sign: { params: JsonObject; data: EmptyData };
get_group_info_ex: { params: GroupIdParams; data: JsonObject };
get_group_detail_info: { params: GroupIdParams; data: JsonObject };
trans_group_file: { params: JsonObject; data: JsonValue };
rename_group_file: { params: JsonObject; data: JsonValue };
get_file: { params: GetMediaParams; data: JsonValue };
'.send_packet': { params: JsonObject; data: JsonValue };
}
export type SnowLumaAction = keyof SnowLumaActionMap | (string & {});
export type ActionParams<TAction extends string> =
TAction extends keyof SnowLumaActionMap ? SnowLumaActionMap[TAction]['params'] : JsonObject;
export type ActionResult<TAction extends string> =
TAction extends keyof SnowLumaActionMap ? SnowLumaActionMap[TAction]['data'] : ActionData;

View File

@@ -0,0 +1,73 @@
import type { JsonObject, JsonValue } from './json';
export interface OneBotBaseEvent extends JsonObject {
time: number;
self_id: number;
post_type: string;
}
export interface OneBotSender extends JsonObject {
user_id: number;
nickname: string;
sex?: string;
age?: number;
card?: string;
role?: string;
}
export interface OneBotPrivateMessageEvent extends OneBotBaseEvent {
post_type: 'message' | 'message_sent';
message_type: 'private';
sub_type: string;
message_id: number;
message_seq?: number;
user_id: number;
message: JsonValue;
raw_message: string;
font: number;
sender: OneBotSender;
}
export interface OneBotGroupMessageEvent extends OneBotBaseEvent {
post_type: 'message' | 'message_sent';
message_type: 'group';
sub_type: string;
message_id: number;
message_seq?: number;
group_id: number;
user_id: number;
message: JsonValue;
raw_message: string;
font: number;
sender: OneBotSender;
anonymous?: JsonValue;
}
export type OneBotMessageEvent = OneBotPrivateMessageEvent | OneBotGroupMessageEvent;
export interface OneBotNoticeEvent extends OneBotBaseEvent {
post_type: 'notice';
notice_type: string;
}
export interface OneBotRequestEvent extends OneBotBaseEvent {
post_type: 'request';
request_type: string;
flag: string;
sub_type?: string;
group_id?: number;
user_id?: number;
comment?: string;
}
export interface OneBotMetaEvent extends OneBotBaseEvent {
post_type: 'meta_event';
meta_event_type: string;
}
export type SnowLumaEvent =
| OneBotMessageEvent
| OneBotNoticeEvent
| OneBotRequestEvent
| OneBotMetaEvent
| OneBotBaseEvent;

View File

@@ -0,0 +1,6 @@
export * from './json';
export * from './messages';
export * from './results';
export * from './params';
export * from './actions';
export * from './events';

View File

@@ -0,0 +1,43 @@
export type JsonPrimitive = string | number | boolean | null;
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
export interface JsonObject {
[key: string]: JsonValue | undefined;
}
export type JsonArray = JsonValue[];
export interface ApiResponse<TData = JsonValue> {
status: 'ok' | 'failed';
retcode: number;
data: TData;
echo?: JsonValue;
wording?: string;
}
export interface OneBotRequest<TParams extends JsonObject = JsonObject> {
action: string;
params?: TParams;
echo?: JsonValue;
}
export type WsRole = 'Api' | 'Event' | 'Universal';
export type MessageFormat = 'array' | 'string';
/** Per-request controls shared by HTTP and WebSocket clients. */
export interface RequestOptions {
/** Echo value used to correlate OneBot request and response packets. */
echo?: JsonValue;
/** Override the client's default timeout for this request. Set to 0 to disable timeout. */
timeoutMs?: number;
/** Cancels the request before a SnowLuma response arrives. */
signal?: AbortSignal;
}
/** Shared options accepted by concrete SnowLuma clients. */
export interface SnowLumaClientOptions {
/** Access token configured in SnowLuma's OneBot settings. */
accessToken?: string;
/** Default timeout for API calls in milliseconds. Defaults to 30000. */
requestTimeoutMs?: number;
}

View File

@@ -0,0 +1,85 @@
import type { JsonObject } from './json';
export interface MessageSegment<
TType extends string = string,
TData extends Record<string, unknown> = JsonObject,
> {
type: TType;
data: TData;
}
export type TextSegment = MessageSegment<'text', { text: string }>;
export type FaceSegment = MessageSegment<'face', { id: string }>;
export type AtSegment = MessageSegment<'at', { qq: string; name?: string; uid?: string }>;
export type ReplySegment = MessageSegment<'reply', { id: string }>;
export type ImageSegment = MessageSegment<'image', {
file: string;
type?: 'flash';
subType?: number;
summary?: string;
url?: string;
}>;
export type RecordSegment = MessageSegment<'record', { file: string; url?: string }>;
export type VideoSegment = MessageSegment<'video', { file: string; url?: string; thumb?: string }>;
export type JsonSegment = MessageSegment<'json', { data: string }>;
export type XmlSegment = MessageSegment<'xml', { data: string; id?: string }>;
export type PokeSegment = MessageSegment<'poke', { type: string | number; id?: string | number }>;
export type ForwardSegment = MessageSegment<'forward', { id: string; res_id?: string; forward_id?: string }>;
export type NodeSegment = MessageSegment<'node', {
user_id: number;
nickname: string;
content: OutgoingMessage;
}>;
export type ShareSegment = MessageSegment<'share', {
url: string;
title: string;
content?: string;
image?: string;
}>;
export type MusicSegment = MessageSegment<'music', {
type: string;
id?: string;
url?: string;
audio?: string;
title?: string;
image?: string;
content?: string;
}>;
export type LocationSegment = MessageSegment<'location', {
lat: string | number;
lon: string | number;
title?: string;
content?: string;
}>;
export type ContactSegment = MessageSegment<'contact', {
type: 'qq' | 'group' | string;
id: string | number;
}>;
export type KnownMessageSegment =
| TextSegment
| FaceSegment
| AtSegment
| ReplySegment
| ImageSegment
| RecordSegment
| VideoSegment
| JsonSegment
| XmlSegment
| PokeSegment
| ForwardSegment
| NodeSegment
| ShareSegment
| MusicSegment
| LocationSegment
| ContactSegment;
export type AnyMessageSegment = KnownMessageSegment | MessageSegment;
export interface MessageChainLike {
readonly length: number;
toSegments(): AnyMessageSegment[];
toJSON(): AnyMessageSegment[];
}
export type OutgoingMessage = string | MessageChainLike | AnyMessageSegment | AnyMessageSegment[];

View File

@@ -0,0 +1,279 @@
import type { JsonObject, JsonValue } from './json';
export interface SendMsgParams extends JsonObject {
message_type?: 'private' | 'group' | string;
user_id?: number;
group_id?: number;
message: JsonValue;
auto_escape?: boolean;
}
export interface SendPrivateMsgParams extends JsonObject {
user_id: number;
message: JsonValue;
auto_escape?: boolean;
}
export interface SendGroupMsgParams extends JsonObject {
group_id: number;
message: JsonValue;
auto_escape?: boolean;
}
export interface MessageIdParams extends JsonObject {
message_id: number;
}
export interface GroupIdParams extends JsonObject {
group_id: number;
}
export interface UserIdParams extends JsonObject {
user_id: number;
}
export interface NoCacheParams extends JsonObject {
no_cache?: boolean;
}
export interface GetGroupListParams extends NoCacheParams {}
export interface GetGroupInfoParams extends GroupIdParams {
no_cache?: boolean;
}
export interface GetGroupMemberListParams extends GroupIdParams {
no_cache?: boolean;
}
export interface GetGroupMemberInfoParams extends GroupIdParams {
user_id: number;
no_cache?: boolean;
}
export interface GetGroupHonorInfoParams extends GroupIdParams {
type?: 'talkative' | 'performer' | 'legend' | 'strong_newbie' | 'emotion' | 'all' | string;
}
export interface DeleteFriendParams extends UserIdParams {
block?: boolean;
}
export interface SetGroupKickParams extends GroupIdParams {
user_id: number;
reject_add_request?: boolean;
}
export interface SetGroupBanParams extends GroupIdParams {
user_id: number;
duration?: number;
}
export interface SetGroupWholeBanParams extends GroupIdParams {
enable?: boolean;
}
export interface SetGroupAdminParams extends GroupIdParams {
user_id: number;
enable?: boolean;
}
export interface SetGroupCardParams extends GroupIdParams {
user_id: number;
card?: string;
}
export interface SetGroupNameParams extends GroupIdParams {
group_name: string;
}
export interface SetGroupSpecialTitleParams extends GroupIdParams {
user_id: number;
special_title?: string;
}
export interface UploadGroupFileParams extends GroupIdParams {
file: string;
name?: string;
folder?: string;
folder_id?: string;
upload_file?: boolean;
}
export interface UploadPrivateFileParams extends UserIdParams {
file: string;
name?: string;
upload_file?: boolean;
}
export interface GetGroupFileUrlParams extends GroupIdParams {
file_id: string;
busid?: number;
}
export interface GetGroupFilesParams extends GroupIdParams {
folder_id?: string;
folder?: string;
}
export interface DeleteGroupFileParams extends GroupIdParams {
file_id: string;
}
export interface MoveGroupFileParams extends GroupIdParams {
file_id: string;
parent_directory: string;
target_directory: string;
}
export interface CreateGroupFileFolderParams extends GroupIdParams {
name: string;
parent_id?: string;
}
export interface DeleteGroupFileFolderParams extends GroupIdParams {
folder_id: string;
}
export interface RenameGroupFileFolderParams extends GroupIdParams {
folder_id: string;
new_folder_name?: string;
name?: string;
}
export interface GetPrivateFileUrlParams extends UserIdParams {
file_id: string;
file_hash: string;
}
export interface SetFriendAddRequestParams extends JsonObject {
flag: string;
approve?: boolean;
}
export interface SetGroupAddRequestParams extends JsonObject {
flag: string;
sub_type?: string;
type?: string;
approve?: boolean;
reason?: string;
}
export interface SendLikeParams extends UserIdParams {
times?: number;
}
export interface FriendPokeParams extends UserIdParams {
target_id?: number;
}
export interface GroupPokeParams extends GroupIdParams {
user_id: number;
}
export interface SendPokeParams extends UserIdParams {
group_id?: number;
}
export interface SetGroupReactionParams extends JsonObject {
message_id: number;
code: string;
group_id?: number;
is_set?: boolean;
}
export interface GetMessageHistoryParams extends JsonObject {
message_id?: number;
count?: number;
}
export interface GetGroupMessageHistoryParams extends GroupIdParams, GetMessageHistoryParams {}
export interface GetFriendMessageHistoryParams extends UserIdParams, GetMessageHistoryParams {}
export interface MarkGroupMsgAsReadParams extends JsonObject {
message_id: number;
group_id?: number;
}
export interface MarkPrivateMsgAsReadParams extends JsonObject {
message_id: number;
user_id?: number;
}
export interface MarkMsgAsReadParams extends JsonObject {
message_id: number;
target_id?: number;
}
export interface GroupNoticeParams extends GroupIdParams {
content: string;
image?: string;
pinned?: number;
type?: number;
confirm_required?: number;
}
export interface ForwardMessageParams extends JsonObject {
message_type?: 'private' | 'group' | string;
user_id?: number;
group_id?: number;
message?: JsonValue;
messages?: JsonValue;
}
export interface GroupForwardMessageParams extends GroupIdParams {
message?: JsonValue;
messages?: JsonValue;
}
export interface PrivateForwardMessageParams extends UserIdParams {
message?: JsonValue;
messages?: JsonValue;
}
export interface GetForwardMsgParams extends JsonObject {
id?: string;
message_id?: number | string;
}
export interface GetMediaParams extends JsonObject {
file?: string;
file_id?: string;
}
export interface DomainParams extends JsonObject {
domain?: string;
}
export interface QuickOperationParams extends JsonObject {
context: JsonObject;
operation: JsonObject;
}
export interface SetFriendRemarkParams extends UserIdParams {
remark: string;
}
export interface SetMsgEmojiLikeParams extends JsonObject {
message_id: number;
emoji_id: string;
set?: boolean;
}
export interface DownloadFileParams extends JsonObject {
url?: string;
base64?: string;
name?: string;
headers?: string | string[];
}
export interface SetQqProfileParams extends JsonObject {
nickname?: string;
personal_note?: string;
}
export interface SetOnlineStatusParams extends JsonObject {
status: number;
ext_status?: number;
battery_status?: number;
}

View File

@@ -0,0 +1,103 @@
import type { JsonArray, JsonObject } from './json';
export interface SendMessageResult {
message_id: number;
}
export interface ForwardMessageResult {
message_id: number;
res_id: string;
forward_id: string;
}
export interface UploadForwardResult {
message_id: number;
res_id: string;
forward_id: string;
group_id?: number;
}
export interface LoginInfo {
user_id: number;
nickname: string;
}
export interface StatusInfo {
online: boolean;
good: boolean;
}
export interface VersionInfo {
app_name: string;
app_version: string;
protocol_version: string;
}
export interface CapabilityInfo {
yes: boolean;
}
export interface GroupFileUrl {
url: string;
}
export interface PrivateFileUrl {
url: string;
}
export interface GroupFileSystemInfo {
file_count: number;
limit_count: number;
used_space: number;
total_space: number;
}
export interface GroupMessageHistory {
messages: JsonObject[];
}
export interface FriendMessageHistory {
messages: JsonObject[];
}
export interface MediaInfo extends JsonObject {}
export interface CookieInfo {
cookies: string;
}
export interface CsrfInfo {
token: number;
}
export interface CredentialsInfo {
cookies: string;
token: number;
csrf_token: number;
}
export interface DownloadFileResult {
file: string;
}
export interface ClientKeyInfo {
clientKey: string;
keyIndex: string;
expireTime: string;
}
export interface OnlineClientsInfo {
clients: JsonArray;
}
export interface UrlSafetyInfo {
level: number;
}
export interface GroupAtAllRemainInfo {
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}
export type EmptyData = null;

View File

@@ -0,0 +1,21 @@
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
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));
const registered = new Set<string>();
for (const file of fs.readdirSync(actionsDir)) {
if (!file.endsWith('.ts')) continue;
const source = fs.readFileSync(new URL(file, `file://${actionsDir}/`), 'utf8');
for (const match of source.matchAll(/registerAction\('([^']+)'/g)) {
registered.add(match[1]!);
}
}
expect([...SNOWLUMA_ACTIONS].sort()).toEqual([...registered].sort());
});
});

View File

@@ -0,0 +1,88 @@
import { describe, expect, it, vi } from 'vitest';
import {
createEventContext,
isGroupMessageEvent,
isPrivateMessageEvent,
matchCommand,
text,
type OneBotPrivateMessageEvent,
type OneBotRequestEvent,
type SnowLumaApiClient,
} from '../src';
const PRIVATE_EVENT: OneBotPrivateMessageEvent = {
time: 1,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
message_seq: 8,
user_id: 10001,
message: [{ type: 'text', data: { text: '/ping a b' } }],
raw_message: '/ping a b',
font: 0,
sender: { user_id: 10001, nickname: 'tester' },
};
function fakeClient(): SnowLumaApiClient {
return {
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 1 }),
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 2 }),
setFriendAddRequest: vi.fn().mockResolvedValue(null),
setGroupAddRequest: vi.fn().mockResolvedValue(null),
raw: vi.fn().mockResolvedValue(null),
} as unknown as SnowLumaApiClient;
}
describe('event helpers', () => {
it('narrows message event types', () => {
expect(isPrivateMessageEvent(PRIVATE_EVENT)).toBe(true);
expect(isGroupMessageEvent(PRIVATE_EVENT)).toBe(false);
});
it('replies to private messages through context', async () => {
const client = fakeClient();
const context = createEventContext(PRIVATE_EVENT, client);
await context.reply(text('pong'));
expect(client.sendPrivateMessage).toHaveBeenCalledWith(10001, text('pong'), undefined);
});
it('approves and rejects request events', async () => {
const client = fakeClient();
const request: OneBotRequestEvent = {
time: 1,
self_id: 10000,
post_type: 'request',
request_type: 'group',
sub_type: 'invite',
flag: 'flag-1',
};
const context = createEventContext(request, client);
await context.approve();
await context.reject('nope');
expect(client.setGroupAddRequest).toHaveBeenNthCalledWith(1, 'flag-1', {
subType: 'invite',
approve: true,
});
expect(client.setGroupAddRequest).toHaveBeenNthCalledWith(2, 'flag-1', {
subType: 'invite',
approve: false,
reason: 'nope',
});
});
it('matches commands with prefixes', () => {
expect(matchCommand(PRIVATE_EVENT, 'ping')).toMatchObject({
command: 'ping',
args: ['a', 'b'],
rest: 'a b',
prefix: '/',
});
expect(matchCommand(PRIVATE_EVENT, 'pong')).toBeNull();
});
});

View File

@@ -0,0 +1,44 @@
import { describe, expect, it, vi } from 'vitest';
import {
SnowLumaAbortError,
SnowLumaAuthError,
SnowLumaHttpClient,
SnowLumaParseError,
} from '../src';
describe('SnowLumaHttpClient', () => {
it('throws SnowLumaAuthError for auth retcodes', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response(JSON.stringify({
status: 'failed',
retcode: 1401,
data: null,
wording: 'unauthorized',
})));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaAuthError);
});
it('throws SnowLumaParseError for non-JSON responses', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response('not json', { status: 200 }));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaParseError);
});
it('supports caller AbortSignal cancellation', async () => {
const fetchImpl = vi.fn((_url: string | URL | Request, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
const signal = init?.signal;
const abort = () => reject(new DOMException('aborted', 'AbortError'));
if (signal?.aborted) abort();
signal?.addEventListener('abort', abort, { once: true });
}));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const controller = new AbortController();
const request = client.getStatus({ signal: controller.signal });
controller.abort();
await expect(request).rejects.toBeInstanceOf(SnowLumaAbortError);
});
});

View File

@@ -0,0 +1,62 @@
import { describe, expect, it, vi } from 'vitest';
import {
atAll,
fromCQString,
message,
parseSegments,
text,
toCQString,
} from '../src';
describe('MessageChain', () => {
it('builds fluent segment chains', () => {
const chain = text('hello').at(10001).br().image('/tmp/a.png');
expect(chain.length).toBe(4);
expect(chain.toSegments()).toEqual([
{ type: 'text', data: { text: 'hello' } },
{ type: 'at', data: { qq: '10001' } },
{ type: 'text', data: { text: '\n' } },
{ type: 'image', data: { file: '/tmp/a.png' } },
]);
});
it('keeps the old segment builder API available', () => {
expect(message.text('hello')).toEqual({ type: 'text', data: { text: 'hello' } });
expect(atAll().toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
});
it('allows reply only once in a chain at runtime', () => {
const chain = text('hello').reply(1);
expect(() => (chain as any).reply(2)).toThrow(/reply/);
expect(() => chain.append(message.reply(2))).toThrow(/reply/);
});
it('appends other messages and converts to CQ string', () => {
const chain = text('hello').append([message.at('all'), message.face(14)]);
expect(toCQString(chain)).toBe('hello[CQ:at,qq=all][CQ:face,id=14]');
});
it('parses CQ strings into chains', () => {
const chain = fromCQString('hi[CQ:at,qq=all][CQ:image,file=a&#44;b]');
expect(chain.toSegments()).toEqual([
{ type: 'text', data: { text: 'hi' } },
{ type: 'at', data: { qq: 'all' } },
{ type: 'image', data: { file: 'a,b', url: undefined, type: undefined, summary: undefined } },
]);
expect(parseSegments('[CQ:reply,id=7]')).toEqual([{ type: 'reply', data: { id: '7' } }]);
});
it('can send itself through a compatible client', async () => {
const client = {
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 1 }),
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 2 }),
};
await text('hi').sendToGroup(client, 123);
await text('yo').sendToPrivate(client, 456);
expect(client.sendGroupMessage).toHaveBeenCalledWith(123, text('hi'), undefined);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(456, text('yo'), undefined);
});
});

View File

@@ -0,0 +1,143 @@
import { describe, expect, it, vi } from 'vitest';
import {
SnowLumaAbortError,
SnowLumaWebSocketClient,
type OneBotPrivateMessageEvent,
} from '../src';
class MockWebSocket {
static instances: MockWebSocket[] = [];
readyState = 0;
sent: string[] = [];
readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>();
constructor(
readonly url: string,
readonly protocols?: string | string[],
) {
MockWebSocket.instances.push(this);
}
addEventListener(event: string, listener: (...args: unknown[]) => void): void {
let listeners = this.listeners.get(event);
if (!listeners) {
listeners = new Set();
this.listeners.set(event, listeners);
}
listeners.add(listener);
}
removeEventListener(event: string, listener: (...args: unknown[]) => void): void {
this.listeners.get(event)?.delete(listener);
}
send(data: string): void {
this.sent.push(data);
}
close(code?: number, reason?: string): void {
this.readyState = 3;
this.emit('close', { code, reason });
}
open(): void {
this.readyState = 1;
this.emit('open');
}
message(data: unknown): void {
this.emit('message', { data });
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) {
listener(...args);
}
}
}
const PRIVATE_EVENT: OneBotPrivateMessageEvent = {
time: 1,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
message_seq: 8,
user_id: 10001,
message: [{ type: 'text', data: { text: '/ping a b' } }],
raw_message: '/ping a b',
font: 0,
sender: { user_id: 10001, nickname: 'tester' },
};
describe('SnowLumaWebSocketClient', () => {
it('matches API responses by echo', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
accessToken: 'token',
webSocket: MockWebSocket,
});
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
expect(socket.url).toContain('access_token=token');
socket.open();
await connecting;
const status = client.getStatus();
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
const request = JSON.parse(socket.sent[0]!) as { echo: string };
socket.message(JSON.stringify({
status: 'ok',
retcode: 0,
data: { online: true, good: true },
echo: request.echo,
}));
await expect(status).resolves.toEqual({ online: true, good: true });
});
it('runs command handlers for matching message events', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
});
const handler = vi.fn();
client.command('ping', handler);
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
socket.message(JSON.stringify(PRIVATE_EVENT));
await vi.waitFor(() => {
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0]![2]).toMatchObject({ args: ['a', 'b'] });
});
});
it('supports caller AbortSignal cancellation for pending requests', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
});
const controller = new AbortController();
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
const request = client.getStatus({ signal: controller.signal });
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
controller.abort();
await expect(request).rejects.toBeInstanceOf(SnowLumaAbortError);
});
});

View File

@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"lib": ["ES2022", "DOM"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

28
pnpm-lock.yaml generated
View File

@@ -35,7 +35,7 @@ importers:
devDependencies:
'@hono/node-server':
specifier: ^1.19.14
version: 1.19.14(hono@4.12.14)
version: 1.19.14(hono@4.12.18)
'@rollup/plugin-node-resolve':
specifier: ^16.0.3
version: 16.0.3
@@ -46,8 +46,8 @@ importers:
specifier: ^10.1.0
version: 10.1.0
hono:
specifier: ^4.12.14
version: 4.12.14
specifier: ^4.12.18
version: 4.12.18
tsx:
specifier: ^4.21.0
version: 4.21.0
@@ -66,6 +66,18 @@ importers:
packages/runtime: {}
packages/sdk:
devDependencies:
'@types/node':
specifier: ^24.12.2
version: 24.12.2
typescript:
specifier: 'catalog:'
version: 6.0.2
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/websocket:
devDependencies:
'@types/node':
@@ -1583,8 +1595,8 @@ packages:
hermes-parser@0.25.1:
resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==}
hono@4.12.14:
resolution: {integrity: sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==}
hono@4.12.18:
resolution: {integrity: sha512-RWzP96k/yv0PQfyXnWjs6zot20TqfpfsNXhOnev8d1InAxubW93L11/oNUc3tQqn2G0bSdAOBpX+2uDFHV7kdQ==}
engines: {node: '>=16.9.0'}
ignore@5.3.2:
@@ -2403,9 +2415,9 @@ snapshots:
'@floating-ui/utils@0.2.11': {}
'@hono/node-server@1.19.14(hono@4.12.14)':
'@hono/node-server@1.19.14(hono@4.12.18)':
dependencies:
hono: 4.12.14
hono: 4.12.18
'@humanfs/core@0.19.1': {}
@@ -3430,7 +3442,7 @@ snapshots:
dependencies:
hermes-estree: 0.25.1
hono@4.12.14: {}
hono@4.12.18: {}
ignore@5.3.2: {}

View File

@@ -5,6 +5,7 @@
"include": [],
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/sdk" },
{ "path": "./packages/webui" }
]
}