refactor(oidb): thread ctx into serialize/deserialize for self-contained namespaces

The first pass at namespace-per-cmd left a smell: namespaces that
needed identity/uid resolution had to declare `Deps` AND then rewrite
their own spec inside `invoke` via a closure-over-resolved-value:

  // before
  export const serialize = (p: Params, targetUid: string) => ({...});
  export const invoke = async (deps, params) => {
    const targetUid = await deps.resolveUserUid(params.userId);
    return invokeOidb(deps, {
      ...Self,
      serialize: p => serialize(p, targetUid),  // ← escape hatch
    }, params);
  };

Reading "what does this cmd do on the wire?" required reading the
namespace AND the closure rewrite — the namespace wasn't really
self-contained, just a forwarder of two pure functions.

Fix: thread `ctx` (the namespace's full capability surface) into
`serialize` and `deserialize` directly. `serialize` may now return
`Promise<TReq>` so identity / uid lookups happen in place:

  // after
  export const serialize = async (ctx: Deps, p: Params) => ({
    groupUin: p.groupId, type: 1,
    body: {
      targetUid: await ctx.resolveUserUid(p.userId, p.groupId),
      duration: p.duration,
    },
  });
  export const invoke = (deps, params) => invokeOidb(deps, Self, params);

OidbCallSpec gains a `TCtx extends OidbSender` generic; invokeOidb's
first arg becomes `ctx: TCtx` (the sender capability is just a slice
of ctx now). buildOidbRequest / parseOidbResponse follow the same
shape. Async serialize is awaited inside invokeOidb.

17 namespaces had closure rewrites; all 17 collapse to plain
`invokeOidb(deps, Self, params)` invokes. Only one closure remains —
`fetch-user-profile` binds `params.uin` into deserialize as a server-
echo fallback; kept as a documented exception (the rare case where
deserialize wants request context, not ctx).

Wire bytes preserved across all migrations. 326 bridge tests + 302
core tests pass; lint clean.
This commit is contained in:
DrSmoothl committed 2026-05-23 12:27:26 +08:00
1 parent 99772851a7
commit 5724f490b4
80 files changed
+416 -397

No files matched your search

+63 -31
View File
@@ -16,12 +16,12 @@ import {
// Reused minimal spec — encodes a group-reaction-shaped request and
// reads back a void result. Exercises every spec branch.
const reactionSpec: OidbCallSpec<
OidbGroupReaction, OidbEmpty,
OidbSender, OidbGroupReaction, OidbEmpty,
{ groupId: number; sequence: number; code: string; isSet: boolean }, void
> = {
command: 0x9082,
resolveSubCommand: p => p.isSet ? 1 : 2,
serialize: p => ({
serialize: (_ctx, p) => ({
groupUin: p.groupId,
sequence: p.sequence,
code: p.code,
@@ -35,10 +35,10 @@ const reactionSpec: OidbCallSpec<
};
// Static-subCommand variant for the branch test.
const staticSubSpec: OidbCallSpec<OidbGroupReaction, OidbEmpty, { groupId: number }, void> = {
const staticSubSpec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbEmpty, { groupId: number }, void> = {
command: 0xEAC,
subCommand: 1,
serialize: p => ({ groupUin: p.groupId, sequence: 0, code: '', type: 1, field6: false, field7: false }),
serialize: (_ctx, p) => ({ groupUin: p.groupId, sequence: 0, code: '', type: 1, field6: false, field7: false }),
deserialize: () => {},
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
@@ -81,13 +81,9 @@ describe('invokeOidb', () => {
const sender = makeSender();
await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '76', isSet: true });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
// First two top-level varint fields of the envelope should be the
// cmd (0x9082) and the resolved subcmd (1).
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.command).toBe(0x9082);
expect(env.subCommand).toBe(1);
// proto3 default-false bool fields aren't serialized — they come back
// as null/undefined on decode, not the literal `false` we passed.
expect(env.body).toMatchObject({
groupUin: 12345, sequence: 99, code: '76', type: 1,
});
@@ -95,15 +91,14 @@ describe('invokeOidb', () => {
it('passes the body through deserialize for transformation', async () => {
type Echo = { tag: number };
const spec: OidbCallSpec<OidbGroupReaction, OidbGroupReaction, { code: string }, Echo> = {
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbGroupReaction, { code: string }, Echo> = {
command: 0x9082,
subCommand: 1,
serialize: p => ({ code: p.code }),
deserialize: b => ({ tag: b.type ?? 99 }),
serialize: (_ctx, p) => ({ code: p.code }),
deserialize: (_ctx, b) => ({ tag: b.type ?? 99 }),
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbGroupReaction>>(bytes),
};
// Server response: an OidbBase envelope whose body has type=5.
const responseEnvelope = protobuf_encode<OidbBase<OidbGroupReaction>>({
command: 0x9082, subCommand: 1,
body: { type: 5 } as OidbGroupReaction,
@@ -114,21 +109,59 @@ describe('invokeOidb', () => {
});
it('substitutes an empty body when the envelope has no field 4', async () => {
// Envelope with only command + errorCode = 0, no body.
const envBytes = protobuf_encode<OidbBase<OidbEmpty>>({ command: 0x9082, subCommand: 1 });
const sender = makeSender({ responseData: Buffer.from(envBytes) });
const deserialize = vi.fn(() => undefined);
const spec: OidbCallSpec<OidbGroupReaction, OidbEmpty, { code: string }, void> = {
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbEmpty, { code: string }, void> = {
command: 0x9082, subCommand: 1,
serialize: p => ({ code: p.code }),
serialize: (_ctx, p) => ({ code: p.code }),
deserialize,
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
await invokeOidb(sender, spec, { code: 'x' });
// deserialize must still receive a defined object (the substituted {}).
expect(deserialize).toHaveBeenCalledOnce();
expect(deserialize.mock.calls[0]![0]).toEqual({});
// deserialize now receives (ctx, body) — body is the second arg.
expect(deserialize.mock.calls[0]![1]).toEqual({});
});
it('awaits async serialize before sending', async () => {
// ctx-aware serialize may need to resolve a uid first; invokeOidb
// must await it before encoding the envelope.
const sender = makeSender();
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbEmpty, { code: string }, void> = {
command: 0x9082, subCommand: 1,
serialize: async (_ctx, p) => {
await new Promise(r => setTimeout(r, 5));
return { code: p.code, sequence: 42 };
},
deserialize: () => {},
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
await invokeOidb(sender, spec, { code: 'async' });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.body?.code).toBe('async');
expect(env.body?.sequence).toBe(42);
});
it('threads ctx into serialize so namespaces can read identity / resolve uids in place', async () => {
const sender = makeSender();
// Extend the ctx with an arbitrary capability the spec uses.
type Ctx = OidbSender & { tag: string };
const ctx: Ctx = { ...sender, tag: 'from-ctx' };
const spec: OidbCallSpec<Ctx, OidbGroupReaction, OidbEmpty, { code: string }, void> = {
command: 0x9082, subCommand: 1,
serialize: (c, p) => ({ code: `${c.tag}/${p.code}` }),
deserialize: () => {},
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
await invokeOidb(ctx, spec, { code: 'x' });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.body?.code).toBe('from-ctx/x');
});
it('propagates timeoutMs to sendRawPacket', async () => {
@@ -175,16 +208,12 @@ describe('invokeOidb', () => {
});
it('skips OidbError check when response payload is empty', async () => {
// Server returns success=true but with zero-length payload (a
// legitimate "ack-only" response). invokeOidb must NOT try to
// decode envelope meta on empty bytes.
const sender = makeSender({ responseData: Buffer.alloc(0) });
// Should not throw.
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).resolves.toBeUndefined();
});
it('honours uinForm=true by flipping OIDB envelope reserved to 1', async () => {
const spec: OidbCallSpec<OidbGroupReaction, OidbEmpty, { groupId: number }, void> = {
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbEmpty, { groupId: number }, void> = {
...staticSubSpec,
uinForm: true,
};
@@ -200,7 +229,6 @@ describe('invokeOidb', () => {
await invokeOidb(sender, staticSubSpec, { groupId: 1 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
// proto3 default 0 may be omitted on the wire — expect either 0 or undefined.
expect(env.reserved ?? 0).toBe(0);
});
});
@@ -211,38 +239,42 @@ describe('buildOidbRequest', () => {
await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '128516', isSet: true });
const sentBytes = sender.sendRawPacket.mock.calls[0]![1];
const built = buildOidbRequest(reactionSpec, { groupId: 12345, sequence: 99, code: '128516', isSet: true });
const built = await buildOidbRequest(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '128516', isSet: true });
expect(built.wireName).toBe('OidbSvcTrpcTcp.0x9082_1');
expect(Buffer.from(built.bytes).equals(Buffer.from(sentBytes))).toBe(true);
});
it('uses static subCommand when resolveSubCommand is absent', () => {
const built = buildOidbRequest(staticSubSpec, { groupId: 1 });
it('uses static subCommand when resolveSubCommand is absent', async () => {
const sender = makeSender();
const built = await buildOidbRequest(sender, staticSubSpec, { groupId: 1 });
expect(built.wireName).toBe('OidbSvcTrpcTcp.0xeac_1');
});
});
describe('parseOidbResponse', () => {
it('decodes wire bytes via spec.decode and runs spec.deserialize on the body', () => {
const sender = makeSender();
const envBytes = protobuf_encode<OidbBase<OidbGroupReaction>>({
command: 0x9082, subCommand: 1, body: { type: 7 } as OidbGroupReaction,
});
type Echo = { type: number };
const spec: OidbCallSpec<OidbGroupReaction, OidbGroupReaction, void, Echo> = {
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbGroupReaction, void, Echo> = {
command: 0x9082, subCommand: 1,
serialize: () => ({} as OidbGroupReaction),
deserialize: b => ({ type: b.type ?? 0 }),
deserialize: (_ctx, b) => ({ type: b.type ?? 0 }),
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbGroupReaction>>(bytes),
};
expect(parseOidbResponse(spec, envBytes)).toEqual({ type: 7 });
expect(parseOidbResponse(sender, spec, envBytes)).toEqual({ type: 7 });
});
it('substitutes empty body when the envelope lacks one', () => {
const sender = makeSender();
const envBytes = protobuf_encode<OidbBase<OidbEmpty>>({ command: 0x9082, subCommand: 1 });
const deserialize = vi.fn(() => ({ ok: true }));
parseOidbResponse({ ...staticSubSpec, deserialize } as any, envBytes);
expect(deserialize).toHaveBeenCalledWith({});
parseOidbResponse(sender, { ...staticSubSpec, deserialize } as any, envBytes);
// deserialize now receives (ctx, body) — body is the second arg.
expect(deserialize.mock.calls[0]![1]).toEqual({});
});
});
@@ -23,12 +23,12 @@ describe('FetchDownloadRkeys namespace', () => {
describe('serialize', () => {
it('requests the (private=10, group=20, fallback=2) image scopes', () => {
const out = FetchDownloadRkeys.serialize({});
const out = FetchDownloadRkeys.serialize({} as any, {});
expect(out.downloadRkey?.types).toEqual([10, 20, 2]);
});
it('packages the fixed reqHead { common, scene, client }', () => {
const out = FetchDownloadRkeys.serialize({});
const out = FetchDownloadRkeys.serialize({} as any, {});
expect(out.reqHead).toEqual({
common: { requestId: 1, command: 202 },
scene: { requestType: 2, businessType: 1, sceneType: 0 },
@@ -39,18 +39,18 @@ describe('FetchDownloadRkeys namespace', () => {
describe('deserialize', () => {
it('throws when respHead.retCode is non-zero', () => {
expect(() => FetchDownloadRkeys.deserialize({
expect(() => FetchDownloadRkeys.deserialize({} as any, {
respHead: { retCode: 42, message: 'bad' },
} as any)).toThrow('bad');
});
it('passes through on retCode = 0', () => {
const body = { respHead: { retCode: 0 }, downloadRkey: { rkeys: [] } };
expect(FetchDownloadRkeys.deserialize(body as any)).toBe(body);
expect(FetchDownloadRkeys.deserialize({} as any, body as any)).toBe(body);
});
it('falls back to a generic message when none is provided', () => {
expect(() => FetchDownloadRkeys.deserialize({
expect(() => FetchDownloadRkeys.deserialize({} as any, {
respHead: { retCode: 1 },
} as any)).toThrow('fetch download rkey failed');
});
@@ -22,19 +22,19 @@ describe('FetchFriendListPage namespace', () => {
describe('serialize', () => {
it('omits nextUin on the first page', () => {
const out = FetchFriendListPage.serialize({ nextUin: null }) as any;
const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any;
expect(out.nextUin).toBeUndefined();
expect(out.friendCount).toBe(300);
expect(out.field4).toBe(0);
});
it('includes nextUin sub-message on follow-up pages', () => {
const out = FetchFriendListPage.serialize({ nextUin: 10001 }) as any;
const out = FetchFriendListPage.serialize({} as any, { nextUin: 10001 }) as any;
expect(out.nextUin).toEqual({ uin: 10001 });
});
it('emits the verbatim property request list (codes 100/101/102/103/20002/27394)', () => {
const out = FetchFriendListPage.serialize({ nextUin: null }) as any;
const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any;
expect(out.body).toEqual([
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{ type: 4, number: { numbers: [100, 101, 102] } },
@@ -19,18 +19,18 @@ describe('FetchGroupMemberListPage namespace', () => {
describe('serialize', () => {
it('omits the token on the first page', () => {
const out = FetchGroupMemberListPage.serialize({ groupId: 12345, token: '' }) as any;
const out = FetchGroupMemberListPage.serialize({} as any, { groupId: 12345, token: '' }) as any;
expect(out.token).toBeUndefined();
expect(out.groupUin).toBe(12345);
});
it('threads the server-issued token into follow-up pages', () => {
const out = FetchGroupMemberListPage.serialize({ groupId: 12345, token: 'next-cursor' }) as any;
const out = FetchGroupMemberListPage.serialize({} as any, { groupId: 12345, token: 'next-cursor' }) as any;
expect(out.token).toBe('next-cursor');
});
it('always requests the full member-field projection', () => {
const out = FetchGroupMemberListPage.serialize({ groupId: 1, token: '' }) as any;
const out = FetchGroupMemberListPage.serialize({} as any, { groupId: 1, token: '' }) as any;
expect(out.body).toMatchObject({
memberName: true, memberCard: true, level: true,
joinTimestamp: true, lastMsgTimestamp: true, shutUpTimestamp: true,
@@ -27,8 +27,8 @@ describe('FetchGroupRequests namespace', () => {
describe('serialize', () => {
it('always sends count=20 / field2=0', () => {
expect(FetchGroupRequests.serialize({ filtered: false })).toEqual({ count: 20, field2: 0 });
expect(FetchGroupRequests.serialize({ filtered: true })).toEqual({ count: 20, field2: 0 });
expect(FetchGroupRequests.serialize({} as any, { filtered: false })).toEqual({ count: 20, field2: 0 });
expect(FetchGroupRequests.serialize({} as any, { filtered: true })).toEqual({ count: 20, field2: 0 });
});
});
@@ -22,7 +22,7 @@ describe('FetchAiVoiceList namespace', () => {
describe('serialize', () => {
it('passes groupUin / chatType verbatim', () => {
expect(FetchAiVoiceList.serialize({ groupId: 4242, chatType: 1 })).toEqual({
expect(FetchAiVoiceList.serialize({} as any, { groupId: 4242, chatType: 1 })).toEqual({
groupUin: 4242, chatType: 1,
});
});
@@ -30,7 +30,7 @@ describe('FetchAiVoiceList namespace', () => {
describe('deserialize', () => {
it('returns content array verbatim', () => {
const out = FetchAiVoiceList.deserialize({
const out = FetchAiVoiceList.deserialize({} as any, {
content: [
{ category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] },
],
@@ -41,7 +41,7 @@ describe('FetchAiVoiceList namespace', () => {
});
it('returns [] when content is omitted', () => {
expect(FetchAiVoiceList.deserialize({})).toEqual([]);
expect(FetchAiVoiceList.deserialize({} as any, {})).toEqual([]);
});
});
@@ -22,7 +22,7 @@ describe('FetchAiVoice namespace', () => {
describe('serialize', () => {
it('packages every field including sessionId into session sub-message', () => {
const out = FetchAiVoice.serialize({
const out = FetchAiVoice.serialize({} as any, {
groupId: 100, voiceId: 'v', text: 'hi', chatType: 1, sessionId: 0xCAFE,
});
expect(out).toEqual({
@@ -35,15 +35,15 @@ describe('FetchAiVoice namespace', () => {
describe('deserialize', () => {
it('returns the first msgInfoBody index when present', () => {
const node = { fileUuid: 'uuid', subType: 1 };
expect(FetchAiVoice.deserialize({
expect(FetchAiVoice.deserialize({} as any, {
msgInfo: { msgInfoBody: [{ index: node }] },
} as any)).toMatchObject(node);
});
it('returns null when msgInfo is empty / missing', () => {
expect(FetchAiVoice.deserialize({} as any)).toBeNull();
expect(FetchAiVoice.deserialize({ msgInfo: {} } as any)).toBeNull();
expect(FetchAiVoice.deserialize({ msgInfo: { msgInfoBody: [] } } as any)).toBeNull();
expect(FetchAiVoice.deserialize({} as any, {} as any)).toBeNull();
expect(FetchAiVoice.deserialize({} as any, { msgInfo: {} } as any)).toBeNull();
expect(FetchAiVoice.deserialize({} as any, { msgInfo: { msgInfoBody: [] } } as any)).toBeNull();
});
});
@@ -23,27 +23,27 @@ describe('GetStrangerStatus namespace', () => {
describe('serialize', () => {
it('always queries only key 27372 (status property)', () => {
const out = GetStrangerStatus.serialize({ uin: 100200 });
const out = GetStrangerStatus.serialize({} as any, { uin: 100200 });
expect(out).toEqual({ uin: 100200, key: [{ key: 27372 }] });
});
});
describe('deserialize', () => {
it('low-band (≤10) values map to (value*10, 0)', () => {
expect(GetStrangerStatus.deserialize({ data: { status: { value: 7n } } })).toEqual({ status: 70, ext_status: 0 });
expect(GetStrangerStatus.deserialize({ data: { status: { value: 10n } } })).toEqual({ status: 100, ext_status: 0 });
expect(GetStrangerStatus.deserialize({} as any, { data: { status: { value: 7n } } })).toEqual({ status: 70, ext_status: 0 });
expect(GetStrangerStatus.deserialize({} as any, { data: { status: { value: 10n } } })).toEqual({ status: 100, ext_status: 0 });
});
it('high-band values decompose into (0xff00 + (>>16 & 0xff)) ext_status', () => {
// 0x42F100 → bits 8..15 = 0xF1<<8 = 0xF100, bits 16..23 = 0x42 → 0xF142
expect(GetStrangerStatus.deserialize({ data: { status: { value: 0x42F100n } } }))
expect(GetStrangerStatus.deserialize({} as any, { data: { status: { value: 0x42F100n } } }))
.toEqual({ status: 10, ext_status: 0xF142 });
});
it('returns null when status field is missing', () => {
expect(GetStrangerStatus.deserialize({})).toBeNull();
expect(GetStrangerStatus.deserialize({ data: {} })).toBeNull();
expect(GetStrangerStatus.deserialize({ data: { status: {} } })).toBeNull();
expect(GetStrangerStatus.deserialize({} as any, {})).toBeNull();
expect(GetStrangerStatus.deserialize({} as any, { data: {} })).toBeNull();
expect(GetStrangerStatus.deserialize({} as any, { data: { status: {} } })).toBeNull();
});
});
@@ -31,7 +31,7 @@ describe('GroupTodo namespace', () => {
describe('serialize', () => {
it('packages groupUin + msgSeq verbatim regardless of action', () => {
for (const action of ['set', 'complete', 'cancel'] as const) {
const out = GroupTodo.serialize({ groupId: 12345, msgSeq: 9876543210n, action });
const out = GroupTodo.serialize({} as any, { groupId: 12345, msgSeq: 9876543210n, action });
expect(out).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
}
});
@@ -19,7 +19,7 @@ describe('SendLike namespace', () => {
describe('serialize', () => {
it('passes userId / count through verbatim', () => {
expect(SendLike.serialize({ userId: 10001, count: 3 })).toEqual({ targetUin: 10001, count: 3 });
expect(SendLike.serialize({} as any, { userId: 10001, count: 3 })).toEqual({ targetUin: 10001, count: 3 });
});
});
@@ -19,32 +19,32 @@ describe('SendPoke namespace', () => {
describe('serialize', () => {
it('group poke: groupUin = peer, friendUin = 0, uin = targetUin', () => {
expect(SendPoke.serialize({ isGroup: true, peerUin: 12345, targetUin: 67890 })).toEqual({
expect(SendPoke.serialize({} as any, { isGroup: true, peerUin: 12345, targetUin: 67890 })).toEqual({
uin: 67890, groupUin: 12345, friendUin: 0, ext: 0,
});
});
it('group poke without targetUin: uin defaults to peer', () => {
expect(SendPoke.serialize({ isGroup: true, peerUin: 12345 })).toEqual({
expect(SendPoke.serialize({} as any, { isGroup: true, peerUin: 12345 })).toEqual({
uin: 12345, groupUin: 12345, friendUin: 0, ext: 0,
});
});
it('friend poke: friendUin = peer, groupUin = 0, uin = targetUin', () => {
expect(SendPoke.serialize({ isGroup: false, peerUin: 67890, targetUin: 11111 })).toEqual({
expect(SendPoke.serialize({} as any, { isGroup: false, peerUin: 67890, targetUin: 11111 })).toEqual({
uin: 11111, groupUin: 0, friendUin: 67890, ext: 0,
});
});
it('friend poke without targetUin: uin defaults to peer', () => {
expect(SendPoke.serialize({ isGroup: false, peerUin: 67890 })).toEqual({
expect(SendPoke.serialize({} as any, { isGroup: false, peerUin: 67890 })).toEqual({
uin: 67890, groupUin: 0, friendUin: 67890, ext: 0,
});
});
it('always sets ext = 0', () => {
expect(SendPoke.serialize({ isGroup: true, peerUin: 1 }).ext).toBe(0);
expect(SendPoke.serialize({ isGroup: false, peerUin: 1 }).ext).toBe(0);
expect(SendPoke.serialize({} as any, { isGroup: true, peerUin: 1 }).ext).toBe(0);
expect(SendPoke.serialize({} as any, { isGroup: false, peerUin: 1 }).ext).toBe(0);
});
});
@@ -27,7 +27,7 @@ describe('SetEssence namespace', () => {
describe('serialize', () => {
it('passes groupId / sequence / random through verbatim', () => {
expect(SetEssence.serialize({ groupId: 12345, sequence: 99, random: 0xCAFEBABE, enable: true })).toEqual({
expect(SetEssence.serialize({} as any, { groupId: 12345, sequence: 99, random: 0xCAFEBABE, enable: true })).toEqual({
groupUin: 12345, sequence: 99, random: 0xCAFEBABE,
});
});
@@ -22,7 +22,7 @@ describe('ClickInlineKeyboardButton namespace', () => {
describe('serialize', () => {
it('widens numeric ids to BigInt for uint_64 fields', () => {
const out = ClickInlineKeyboardButton.serialize({
const out = ClickInlineKeyboardButton.serialize({} as any, {
groupId: 12345, botAppid: 67890, buttonId: 'btn', callbackData: 'data', msgSeq: 100,
});
expect(out.groupId).toBe(12345n);
@@ -31,7 +31,7 @@ describe('ClickInlineKeyboardButton namespace', () => {
});
it('always sends unknown7=0 / unknown9=1 magic values', () => {
const out = ClickInlineKeyboardButton.serialize({
const out = ClickInlineKeyboardButton.serialize({} as any, {
groupId: 1, botAppid: 1, buttonId: 'x', callbackData: 'y', msgSeq: 1,
});
expect(out.unknown7).toBe(0);
@@ -39,7 +39,7 @@ describe('ClickInlineKeyboardButton namespace', () => {
});
it('coerces buttonId / callbackData to strings (defensive)', () => {
const out = ClickInlineKeyboardButton.serialize({
const out = ClickInlineKeyboardButton.serialize({} as any, {
groupId: 1, botAppid: 1, buttonId: 123 as any, callbackData: null as any, msgSeq: 1,
});
expect(out.buttonId).toBe('123');
@@ -49,7 +49,7 @@ describe('ClickInlineKeyboardButton namespace', () => {
describe('deserialize', () => {
it('shapes the response with status/promptType/promptIcon = 0', () => {
expect(ClickInlineKeyboardButton.deserialize({
expect(ClickInlineKeyboardButton.deserialize({} as any, {
result: 1, errMsg: 'ok', promptText: 'hi',
} as Oidb0x112eResp)).toEqual({
result: 1, errMsg: 'ok', status: 0, promptText: 'hi', promptType: 0, promptIcon: 0,
@@ -57,7 +57,7 @@ describe('ClickInlineKeyboardButton namespace', () => {
});
it('defaults result/errMsg/promptText when omitted', () => {
expect(ClickInlineKeyboardButton.deserialize({} as Oidb0x112eResp)).toEqual({
expect(ClickInlineKeyboardButton.deserialize({} as any, {} as Oidb0x112eResp)).toEqual({
result: 0, errMsg: '', status: 0, promptText: '', promptType: 0, promptIcon: 0,
});
});
@@ -22,7 +22,7 @@ describe('TranslateEnToZh namespace', () => {
describe('serialize', () => {
it('hardcodes en → zh and tag10/12 = 1', () => {
const out = TranslateEnToZh.serialize({ words: ['hello'] });
const out = TranslateEnToZh.serialize({} as any, { words: ['hello'] });
expect(out).toEqual({
translateReq: { srcLang: 'en', dstLang: 'zh', words: ['hello'] },
tag10: 1,
@@ -31,24 +31,24 @@ describe('TranslateEnToZh namespace', () => {
});
it('passes the words array verbatim', () => {
const out = TranslateEnToZh.serialize({ words: ['a', 'b', 'c'] });
const out = TranslateEnToZh.serialize({} as any, { words: ['a', 'b', 'c'] });
expect(out.translateReq?.words).toEqual(['a', 'b', 'c']);
});
});
describe('deserialize', () => {
it('returns dstWords when translateResp is present', () => {
expect(TranslateEnToZh.deserialize({
expect(TranslateEnToZh.deserialize({} as any, {
translateResp: { dstWords: ['你好', '世界'] },
} as Oidb0x990Resp)).toEqual(['你好', '世界']);
});
it('returns [] when dstWords is omitted but translateResp exists', () => {
expect(TranslateEnToZh.deserialize({ translateResp: {} } as Oidb0x990Resp)).toEqual([]);
expect(TranslateEnToZh.deserialize({} as any, { translateResp: {} } as Oidb0x990Resp)).toEqual([]);
});
it('throws when translateResp is missing', () => {
expect(() => TranslateEnToZh.deserialize({} as Oidb0x990Resp))
expect(() => TranslateEnToZh.deserialize({} as any, {} as Oidb0x990Resp))
.toThrow('translate response empty');
});
});
@@ -104,7 +104,7 @@ describe('GetLike namespace', () => {
describe('deserialize', () => {
it('shapes favorite + vote info with the expected key names', () => {
const out = GetLike.deserialize({
const out = GetLike.deserialize({} as any, {
userLikeInfos: [{
uid: 'u', time: 1700000000n,
favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 },
@@ -122,12 +122,12 @@ describe('GetLike namespace', () => {
});
it('throws when there are no userLikeInfos', () => {
expect(() => GetLike.deserialize({})).toThrow('get profile like info empty');
expect(() => GetLike.deserialize({ userLikeInfos: [] })).toThrow('get profile like info empty');
expect(() => GetLike.deserialize({} as any, {})).toThrow('get profile like info empty');
expect(() => GetLike.deserialize({} as any, { userLikeInfos: [] })).toThrow('get profile like info empty');
});
it('defaults all count fields to 0 when omitted', () => {
const out = GetLike.deserialize({ userLikeInfos: [{ uid: 'u', time: 0n }] });
const out = GetLike.deserialize({} as any, { userLikeInfos: [{ uid: 'u', time: 0n }] });
expect(out.favoriteInfo.total_count).toBe(0);
expect(out.voteInfo.total_count).toBe(0);
});
@@ -49,20 +49,20 @@ describe('GetUnidirectionalFriendList namespace', () => {
describe('deserialize', () => {
it('parses the embedded JSON body and returns rpt_block_list', () => {
const out = GetUnidirectionalFriendList.deserialize({
const out = GetUnidirectionalFriendList.deserialize({} as any, {
jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }),
});
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
});
it('returns [] when rpt_block_list is absent', () => {
const out = GetUnidirectionalFriendList.deserialize({ jsonBody: JSON.stringify({}) });
const out = GetUnidirectionalFriendList.deserialize({} as any, { jsonBody: JSON.stringify({}) });
expect(out).toEqual([]);
});
it('throws when jsonBody is empty / missing', () => {
expect(() => GetUnidirectionalFriendList.deserialize({})).toThrow('get unidirectional friend list empty');
expect(() => GetUnidirectionalFriendList.deserialize({ jsonBody: '' })).toThrow('get unidirectional friend list empty');
expect(() => GetUnidirectionalFriendList.deserialize({} as any, {})).toThrow('get unidirectional friend list empty');
expect(() => GetUnidirectionalFriendList.deserialize({} as any, { jsonBody: '' })).toThrow('get unidirectional friend list empty');
});
});
@@ -22,13 +22,13 @@ describe('FetchReactionSummary namespace', () => {
describe('serialize', () => {
it('encodes groupId/sequence as BigInt for uint_64 fields', () => {
const out = FetchReactionSummary.serialize({ groupId: 1022489779, sequence: 1730183 });
const out = FetchReactionSummary.serialize({} as any, { groupId: 1022489779, sequence: 1730183 });
expect(out.groupId).toBe(1022489779n);
expect(out.sequence).toBe(1730183n);
});
it('passes empty / default values for the unused filter fields', () => {
const out = FetchReactionSummary.serialize({ groupId: 1, sequence: 1 });
const out = FetchReactionSummary.serialize({} as any, { groupId: 1, sequence: 1 });
expect(out.emojiId).toBe('');
expect(out.emojiType).toBe(0);
expect(out.count).toBe(0);
@@ -36,7 +36,7 @@ describe('FetchReactionSummary namespace', () => {
});
it('emits a 0-length cookie buffer (no continuation)', () => {
const out = FetchReactionSummary.serialize({ groupId: 1, sequence: 1 });
const out = FetchReactionSummary.serialize({} as any, { groupId: 1, sequence: 1 });
expect(out.cookie).toBeInstanceOf(Uint8Array);
expect(out.cookie!.length).toBe(0);
});
@@ -50,7 +50,7 @@ describe('FetchReactionSummary namespace', () => {
{ lastReactionTime: 1779456962n, count: 1, emojiType: 1, emojiId: '124' },
],
};
expect(FetchReactionSummary.deserialize(body)).toEqual([
expect(FetchReactionSummary.deserialize({} as any, body)).toEqual([
{ emojiId: '76', emojiType: 1, count: 3, lastReactionTime: 1779456439 },
{ emojiId: '124', emojiType: 1, count: 1, lastReactionTime: 1779456962 },
]);
@@ -64,20 +64,20 @@ describe('FetchReactionSummary namespace', () => {
{ emojiType: 1, emojiId: '66' }, // catalog entry
],
};
const out = FetchReactionSummary.deserialize(body);
const out = FetchReactionSummary.deserialize({} as any, body);
expect(out).toHaveLength(1);
expect(out[0]!.emojiId).toBe('76');
});
it('returns an empty array when the response has no entries', () => {
expect(FetchReactionSummary.deserialize({})).toEqual([]);
expect(FetchReactionSummary.deserialize({} as any, {})).toEqual([]);
});
it('defaults emojiId / emojiType to safe values when omitted', () => {
const body: Oidb0x9084Resp = {
entries: [{ count: 5, lastReactionTime: 1700000000n }],
};
const [entry] = FetchReactionSummary.deserialize(body);
const [entry] = FetchReactionSummary.deserialize({} as any, body);
expect(entry).toEqual({
emojiId: '', emojiType: 1, count: 5, lastReactionTime: 1700000000,
});
@@ -85,7 +85,7 @@ describe('FetchReactionSummary namespace', () => {
it('reports lastReactionTime=0 when omitted on a used entry (degenerate but defensive)', () => {
const body: Oidb0x9084Resp = { entries: [{ count: 2, emojiId: 'x', emojiType: 1 }] };
expect(FetchReactionSummary.deserialize(body)[0]!.lastReactionTime).toBe(0);
expect(FetchReactionSummary.deserialize({} as any, body)[0]!.lastReactionTime).toBe(0);
});
});
@@ -22,7 +22,7 @@ describe('GetEmojiLikes namespace', () => {
describe('serialize', () => {
it('encodes groupId/sequence as BigInt for uint_64 fields', () => {
const out = GetEmojiLikes.serialize({
const out = GetEmojiLikes.serialize({} as any, {
groupId: 12345, sequence: 99, emojiId: '76',
});
expect(out.groupId).toBe(12345n);
@@ -30,44 +30,44 @@ describe('GetEmojiLikes namespace', () => {
});
it('passes emojiId through unchanged', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: '128516' });
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: '128516' });
expect(out.emojiId).toBe('128516');
});
it('defaults emojiType to 1 when omitted', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x' });
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.emojiType).toBe(1);
});
it('uses caller-supplied emojiType when present', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x', emojiType: 2 });
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x', emojiType: 2 });
expect(out.emojiType).toBe(2);
});
it('defaults count to 10 when omitted', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x' });
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.count).toBe(10);
});
it('uses caller-supplied count when present', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x', count: 50 });
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x', count: 50 });
expect(out.count).toBe(50);
});
it('decodes base64 cookie into the bytes field for continuation', () => {
const cookie = Buffer.from([0xCA, 0xFE]).toString('base64');
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x', cookie });
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x', cookie });
expect(out.cookie).toBeInstanceOf(Uint8Array);
expect(Buffer.from(out.cookie!).equals(Buffer.from([0xCA, 0xFE]))).toBe(true);
});
it('emits a 0-length cookie buffer for the first page (no cookie supplied)', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x' });
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.cookie!.length).toBe(0);
});
it('sets field7=0 and field12=1 (magic values matching the historic wire shape)', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x' });
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.field7).toBe(0);
expect(out.field12).toBe(1);
});
@@ -75,7 +75,7 @@ describe('GetEmojiLikes namespace', () => {
describe('deserialize', () => {
it('extracts users from inner.userInfo and base64-encodes the cookie', () => {
const result = GetEmojiLikes.deserialize({
const result = GetEmojiLikes.deserialize({} as any, {
inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] },
cookie: new Uint8Array([0xCA, 0xFE]),
});
@@ -85,28 +85,28 @@ describe('GetEmojiLikes namespace', () => {
});
it('filters out users with uin=0 (placeholder / zero-value)', () => {
const result = GetEmojiLikes.deserialize({
const result = GetEmojiLikes.deserialize({} as any, {
inner: { userInfo: [{ uin: 10001n }, { uin: 0n }, { uin: 20002n }] },
});
expect(result.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
});
it('returns empty users + empty cookie + isLast=true when body has nothing', () => {
const result = GetEmojiLikes.deserialize({});
const result = GetEmojiLikes.deserialize({} as any, {});
expect(result.users).toEqual([]);
expect(result.cookie).toBe('');
expect(result.isLast).toBe(true);
});
it('returns isLast=true when cookie is absent (final page)', () => {
const result = GetEmojiLikes.deserialize({
const result = GetEmojiLikes.deserialize({} as any, {
inner: { userInfo: [{ uin: 10001n }] },
});
expect(result.isLast).toBe(true);
});
it('handles missing userInfo entries field', () => {
const result = GetEmojiLikes.deserialize({ inner: {} });
const result = GetEmojiLikes.deserialize({} as any, { inner: {} });
expect(result.users).toEqual([]);
});
});
@@ -26,31 +26,31 @@ describe('SetReaction namespace', () => {
describe('serialize', () => {
it('produces type=1 for short QQ-face codes (≤3 chars)', () => {
const out = SetReaction.serialize({ groupId: 12345, sequence: 99, code: '76', isSet: true });
const out = SetReaction.serialize({} as any, { groupId: 12345, sequence: 99, code: '76', isSet: true });
expect(out).toEqual({
groupUin: 12345, sequence: 99, code: '76', type: 1, field6: false, field7: false,
});
});
it('produces type=1 for exactly 3-character codes (boundary)', () => {
const out = SetReaction.serialize({ groupId: 1, sequence: 1, code: '999', isSet: true });
const out = SetReaction.serialize({} as any, { groupId: 1, sequence: 1, code: '999', isSet: true });
expect(out.type).toBe(1);
});
it('produces type=2 for codes longer than 3 chars (unicode codepoint)', () => {
const out = SetReaction.serialize({ groupId: 1, sequence: 1, code: '128516', isSet: false });
const out = SetReaction.serialize({} as any, { groupId: 1, sequence: 1, code: '128516', isSet: false });
expect(out.type).toBe(2);
});
it('passes through groupId/sequence/code verbatim', () => {
const out = SetReaction.serialize({ groupId: 999, sequence: 42, code: 'abc', isSet: true });
const out = SetReaction.serialize({} as any, { groupId: 999, sequence: 42, code: 'abc', isSet: true });
expect(out.groupUin).toBe(999);
expect(out.sequence).toBe(42);
expect(out.code).toBe('abc');
});
it('always sets field6/field7 to false (deferred behaviour)', () => {
const out = SetReaction.serialize({ groupId: 1, sequence: 1, code: 'x', isSet: true });
const out = SetReaction.serialize({} as any, { groupId: 1, sequence: 1, code: 'x', isSet: true });
expect(out.field6).toBe(false);
expect(out.field7).toBe(false);
});
@@ -58,7 +58,7 @@ describe('SetReaction namespace', () => {
describe('deserialize', () => {
it('always returns void regardless of body content', () => {
expect(SetReaction.deserialize({})).toBeUndefined();
expect(SetReaction.deserialize({} as any, {})).toBeUndefined();
});
});
@@ -22,14 +22,14 @@ describe('GetPskey namespace', () => {
describe('serialize', () => {
it('passes the domainList through verbatim', () => {
const out = GetPskey.serialize({ domainList: ['qun.qq.com', 'qzone.qq.com'] });
const out = GetPskey.serialize({} as any, { domainList: ['qun.qq.com', 'qzone.qq.com'] });
expect(out.domainList).toEqual(['qun.qq.com', 'qzone.qq.com']);
});
});
describe('deserialize', () => {
it('builds a Map from server pskeyItems', () => {
const { domainPskeyMap } = GetPskey.deserialize({
const { domainPskeyMap } = GetPskey.deserialize({} as any, {
pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'pskey-qun' },
{ domain: 'qzone.qq.com', pskey: 'pskey-qzone' },
@@ -40,7 +40,7 @@ describe('GetPskey namespace', () => {
});
it('drops entries with missing domain or pskey', () => {
const { domainPskeyMap } = GetPskey.deserialize({
const { domainPskeyMap } = GetPskey.deserialize({} as any, {
pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'ok' },
{ domain: 'missing-pskey.com' },
@@ -52,7 +52,7 @@ describe('GetPskey namespace', () => {
});
it('returns empty Map when pskeyItems is absent', () => {
const { domainPskeyMap } = GetPskey.deserialize({});
const { domainPskeyMap } = GetPskey.deserialize({} as any, {});
expect(domainPskeyMap.size).toBe(0);
});
});