Files
SnowLuma/packages/core/tests/bridge-member-identity.test.ts
T
DrSmoothl 6bf53890dc refactor(api): move contacts methods to ContactsApi (#6 commit 2/13)
Second of 13 commits decomposing Bridge. Moves the six "fetch the
roster / a profile / outstanding requests / download rkeys" methods
off Bridge and onto a new `apis.contacts.*`.

Methods moved
-------------
* fetchFriendList       — OIDB 0xfd4_1 + identity.rememberFriends
* fetchGroupList        — OIDB 0xfe5_2 + identity.rememberGroups
* fetchGroupMemberList  — OIDB 0xfe7_3 + identity.rememberGroupMembers
                          (includes the 60s TTL + per-group inflight
                          coalesce cache that prevents Tencent
                          risk-control from triggering)
* fetchUserProfile      — OIDB 0xfe1_2 + identity.rememberUserProfile
* fetchGroupRequests    — OIDB 0x10c0_{1,2}
* fetchDownloadRKeys    — OIDB 0x9067_202

Cache fields moved
------------------
The two member-list throttle maps (`memberListInflight_`,
`memberListLastFetch_`) move from Bridge to `ContactsApi` as private
fields. Same TTL, same semantics — just owned by the Api class that
exposes the method.

Constructor ordering
--------------------
`buildApiHub(this)` now runs BEFORE `identity.setFetcher(...)` in the
Bridge constructor because the `fetchProfile` / `fetchGroupMemberList`
callbacks installed there reach into `this.apis.contacts.*`. With
eager construction this is safe; the alternative (pass a thunk that
forwards once apis is built) was strictly worse for readability.

bridge-contacts.ts removed
--------------------------
The file existed solely as the previous module-function delegate
target; ContactsApi inlines every function body so there's nothing
left to keep.

Caller-site updates
-------------------
* `bridge/actions/friend.ts` — `bridge.fetchFriendList()` →
  `bridge.apis.contacts.fetchFriendList()`.
* `onebot/manager.ts`, `onebot/instance-rkey.ts`,
  `onebot/modules/contact-actions.ts`, `modules/request-actions.ts`,
  `actions/extended.ts` — same shape rewrite (6 method names).

Test plumbing
-------------
* `tests/actions/_helpers.ts` — `mockApiHub()` grows a `contacts`
  field built by `mockContactsApi()`.
* `tests/bridge-member-identity.test.ts::RefreshingBridge` — was
  `override async fetchGroupMemberList()`. After the move the method
  lives on `this.apis.contacts`, not `this`. Switched to patching the
  method on the constructed ContactsApi instance directly.
* `tests/actions/friend.test.ts` — `bridge.fetchFriendList` →
  `bridge.apis.contacts.fetchFriendList`; the "refresh throws" branch
  overrides via `bridge.apis.contacts.fetchFriendList = vi.fn(…)`.
* `tests/onebot/contact-actions.test.ts`, `extended-actions.test.ts`,
  `request-actions.test.ts` — local `fakeBridge` helpers gained an
  auto-promotion shim that rewrites flat method stubs (the pre-#6
  test API) into the new `apis.<area>.method` shape. Keeps existing
  test setup readable while the production code uses the new path.

Tests: 587/587 pass (same baseline; pre-existing network-manager
native-addon failure unchanged).
2026-05-20 22:27:32 +08:00

152 lines
4.6 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import { Bridge } from '../src/bridge/bridge';
import { IdentityService } from '../src/bridge/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info';
import type { GroupMemberJoin, QQEventVariant } from '../src/bridge/events';
import type { PacketInfo } from '../src/protocol/types';
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(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
super(identity);
// `fetchGroupMemberList` moved from Bridge onto `apis.contacts`
// under the #6 refactor — patch the method on the constructed
// ContactsApi instance to intercept calls + record them for
// assertions. (Direct property assignment works because the
// method is just an own property on the Api instance, not on
// its prototype.)
this.apis.contacts.fetchGroupMemberList = async (
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> => {
this.memberFetches.push({ groupId, force: Boolean(options.force) });
for (const member of this.refreshedMembers) {
this.identity.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 identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const bridge = new RefreshingBridge(identity, [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 bridge = new Bridge(IdentityService.memory(SELF_UIN));
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);
});
});