Files
SnowLuma/packages/core/tests/proton-parity.test.ts
T
DrSmoothl ccc31a760c feat(proton): migrate action.ts schemas + bridge.ts + element-builder.ts
Mirrors all 11 schemas in bridge/proto/action.ts as proton interface
forms and switches the two consumers (element-builder.ts and the
send-message paths in bridge.ts) over to the new compile-time API.

Migrated schemas (proton/action.ts):
  RoutingC2C, RoutingGroup, RoutingHead, SendContentHead,
  MessageControl, SendRichText, SendMessageBody, SendMessageRequest,
  SendMessageResponse, MentionExtraSend, MarkdownData

Consumer switches:
  - element-builder.ts: protobuf_encode<MentionExtraSend> for @ mention
    pbReserve payload; protobuf_encode<MarkdownData> for markdown elem
  - bridge.ts: protobuf_encode<SendMessageRequest> +
    protobuf_decode<SendMessageResponse> for both sendGroupMessage and
    sendPrivateMessage

The `ProtoElem` type alias in element-builder.ts (Partial<ProtoDecoded<typeof
ElemSchema>>) stays as-is — it's a pure TS type used internally for
building elem objects and doesn't affect runtime behaviour. Replacing
it with the proton Elem type is a larger refactor that can come later
when there's a reason to.

Verification:
  - 6 new parity tests for action schemas (RoutingHead c2c+grp,
    SendMessageRequest full shape, SendMessageResponse, MentionExtraSend,
    MarkdownData)
  - 591/591 core test suite passes — the existing send-message and
    element-builder tests implicitly validated wire format equivalence
  - tsc --noEmit clean
2026-05-19 08:19:14 +08:00

503 lines
19 KiB
TypeScript

// Proof-of-concept: verify that codec generated by @snowluma/proton's Vite
// plugin produces wire bytes byte-identical to the legacy runtime schema
// encoder for the same input. If this passes, the migration pattern is sound
// for the schemas covered here.
import { describe, it, expect } from 'vitest';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import { protoEncode, protoDecode } from '../src/protobuf/decode';
import {
SendLongMsgRespSchema,
SendLongMsgReqSchema,
RecvLongMsgReqSchema,
RecvLongMsgRespSchema,
LongMsgSettingsSchema,
LongMsgResultSchema,
} from '../src/bridge/proto/longmsg';
import {
TextElemSchema,
NotOnlineImageSchema,
ExtraInfoSchema,
SrcMsgSchema,
ElemSchema,
MsgInfoSchema,
} from '../src/bridge/proto/element';
import {
ResponseHeadSchema,
PushMsgBodySchema,
PushMsgSchema,
} from '../src/bridge/proto/message';
import {
GroupChangeSchema,
GroupAdminSchema,
NotifyMessageBodySchema,
GroupReactNotifySchema,
FriendRequestSchema,
GroupJoinSchema,
} from '../src/bridge/proto/notify';
import {
RoutingHeadSchema,
SendMessageRequestSchema,
SendMessageResponseSchema,
MentionExtraSendSchema,
MarkdownDataSchema,
} from '../src/bridge/proto/action';
import type {
SendLongMsgResp,
SendLongMsgReq,
RecvLongMsgReq,
RecvLongMsgResp,
LongMsgSettings,
LongMsgResult,
} from '../src/bridge/proto/proton/longmsg';
import type {
TextElem,
NotOnlineImage,
ExtraInfo,
SrcMsg,
Elem,
MsgInfo,
} from '../src/bridge/proto/proton/element';
import type {
ResponseHead,
PushMsgBody,
PushMsg,
} from '../src/bridge/proto/proton/message';
import type {
GroupChange,
GroupAdmin,
NotifyMessageBody,
GroupReactNotify,
FriendRequest as FriendRequestNotify,
GroupJoin,
} from '../src/bridge/proto/proton/notify';
import type {
RoutingHead,
SendMessageRequest,
SendMessageResponse,
MentionExtraSend,
MarkdownData,
} from '../src/bridge/proto/proton/action';
function hex(buf: Uint8Array): string {
return Buffer.from(buf).toString('hex');
}
describe('proton ↔ legacy parity (longmsg subset)', () => {
it('encodes LongMsgSettings identically', () => {
const data: LongMsgSettings = { field1: 1, field2: 2, field3: 3, field4: 4 };
const legacy = protoEncode(data as any, LongMsgSettingsSchema);
const proton = protobuf_encode<LongMsgSettings>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SendLongMsgResp (nested message) identically', () => {
const data: SendLongMsgResp = { result: { resId: 'res-001' } };
const legacy = protoEncode(data as any, SendLongMsgRespSchema);
const proton = protobuf_encode<SendLongMsgResp>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SendLongMsgReq with bytes + nested + settings identically', () => {
// NOTE: all numeric fields are non-zero — proton follows proto3 semantics
// and omits default-valued fields from the wire, whereas the legacy runtime
// encoder always writes them. Parity is therefore only expected when no
// numeric field equals its default. See the explicit divergence test below.
const data: SendLongMsgReq = {
info: {
type: 1,
uid: { uid: 'u_test' },
groupUin: 123456,
payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]),
},
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
};
const legacy = protoEncode(data as any, SendLongMsgReqSchema);
const proton = protobuf_encode<SendLongMsgReq>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes RecvLongMsgReq with bool field identically', () => {
const data: RecvLongMsgReq = {
info: { uid: { uid: 'u_recv' }, resId: 'r-9', acquire: true },
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
};
const legacy = protoEncode(data as any, RecvLongMsgReqSchema);
const proton = protobuf_encode<RecvLongMsgReq>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes RecvLongMsgResp (with bytes payload) identically', () => {
const data: RecvLongMsgResp = {
result: { resId: 'r-1', payload: new Uint8Array([1, 2, 3, 4, 5]) },
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
};
const legacy = protoEncode(data as any, RecvLongMsgRespSchema);
const proton = protobuf_encode<RecvLongMsgResp>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── element.ts coverage ─────────────────────────────────────────────
it('encodes TextElem (only primitive bytes + strings) identically', () => {
const data: TextElem = {
str: 'hello',
link: 'https://example.com',
attr6Buf: new Uint8Array([1, 2, 3]),
buf: new Uint8Array([0xff, 0xee]),
};
const legacy = protoEncode(data as any, TextElemSchema);
const proton = protobuf_encode<TextElem>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes NotOnlineImage with nested PbReserve identically', () => {
const data: NotOnlineImage = {
filePath: 'pic.jpg',
fileLen: 12345,
picMd5: new Uint8Array([0x11, 0x22, 0x33, 0x44]),
picHeight: 600,
picWidth: 800,
resId: 'res-abc',
original: 1,
bigUrl: 'https://q.qq.com/big/abc',
bizType: 5,
pbRes: {
subType: 1,
summary: '[picture]',
field10: 7,
field20: { field1: 1, field2: 'inner', field3: 2, field4: 3, field5: 4, field7: 'tail' },
url: 'https://q.qq.com/abc',
md5Str: 'abc123',
},
};
const legacy = protoEncode(data as any, NotOnlineImageSchema);
const proton = protobuf_encode<NotOnlineImage>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes ExtraInfo (mix of bytes + int32 + uint64) identically', () => {
const data: ExtraInfo = {
nick: new Uint8Array([0x41, 0x42]),
groupCard: new Uint8Array([0x43]),
level: 7,
flags: 1,
groupMask: 2,
msgTailId: 3,
uin: 10001n,
msgStateFlag: 4,
};
const legacy = protoEncode(data as any, ExtraInfoSchema);
const proton = protobuf_encode<ExtraInfo>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SrcMsg with repeated_uint32 + repeated_bytes identically', () => {
const data: SrcMsg = {
origSeqs: [100, 200, 300, 400],
senderUin: 10001n,
time: 1234567890,
flag: 1,
elemsRaw: [new Uint8Array([1, 2]), new Uint8Array([3, 4]), new Uint8Array([5, 6])],
type: 1,
toUin: 20002n,
};
const legacy = protoEncode(data as any, SrcMsgSchema);
const proton = protobuf_encode<SrcMsg>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes Elem (oneOf-style union) identically across multiple shapes', () => {
const textOnly: Elem = { text: { str: 'hi', link: 'lnk' } };
expect(hex(protobuf_encode<Elem>(textOnly))).toBe(hex(protoEncode(textOnly as any, ElemSchema)));
const faceOnly: Elem = { face: { index: 42, buf: new Uint8Array([1, 2, 3]) } };
expect(hex(protobuf_encode<Elem>(faceOnly))).toBe(hex(protoEncode(faceOnly as any, ElemSchema)));
const generalFlags: Elem = { generalFlags: { uin: 10001n, longTextFlag: 1, longTextResId: 'rs' } };
expect(hex(protobuf_encode<Elem>(generalFlags))).toBe(hex(protoEncode(generalFlags as any, ElemSchema)));
});
it('encodes MsgInfo with repeated_message + deeply nested ExtBizInfo identically', () => {
const data: MsgInfo = {
msgInfoBody: [
{
index: {
info: { fileSize: 1024, fileHash: 'sha-1', fileSha1: 'sha-2', fileName: 'a.png', type: { type: 1, picFormat: 2, videoFormat: 3, voiceFormat: 4 }, width: 100, height: 200, time: 99, original: 1 },
fileUuid: 'uuid-1', storeId: 5, uploadTime: 1000, ttl: 86400, subType: 1,
},
picture: {
urlPath: '/p/1',
ext: { originalParameter: 'op', bigParameter: 'bp', thumbParameter: 'tp' },
domain: 'q.qq.com',
},
fileExist: true,
},
],
extBizInfo: {
pic: {
bizType: 5, textSummary: '[pic]',
extData: { subType: 2, textSummary: 'sum' },
fromScene: 1, toScene: 2, oldFileId: 999,
},
busiType: 3,
},
};
const legacy = protoEncode(data as any, MsgInfoSchema);
const proton = protobuf_encode<MsgInfo>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── message.ts coverage ─────────────────────────────────────────────
it('encodes ResponseHead (nested forward + grp) identically', () => {
const data: ResponseHead = {
fromUin: 10001, fromUid: 'u_a', type: 1, sigMap: 2, toUin: 20002, toUid: 'u_b',
forward: { friendName: 'Alice' },
grp: { groupUin: 555, memberName: 'Bob', groupName: 'TestGroup' },
};
const legacy = protoEncode(data as any, ResponseHeadSchema);
const proton = protobuf_encode<ResponseHead>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes PushMsgBody (with RichText holding Elem[]) identically', () => {
const data: PushMsgBody = {
responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 3, fromUid: 'a', toUid: 'b' },
contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 99, sequence: 100, timestamp: 1234567890 },
body: {
richText: {
elems: [
{ text: { str: 'hi ' } },
{ text: { str: 'world', link: 'lnk' } },
],
},
},
};
const legacy = protoEncode(data as any, PushMsgBodySchema);
const proton = protobuf_encode<PushMsgBody>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes PushMsg (top-level) identically', () => {
const data: PushMsg = {
message: {
responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 1, fromUid: 'a', toUid: 'b' },
contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 1, sequence: 1, timestamp: 1 },
body: { richText: { elems: [{ text: { str: 'x' } }] } },
},
status: 1,
};
const legacy = protoEncode(data as any, PushMsgSchema);
const proton = protobuf_encode<PushMsg>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── longmsg.ts: full migration (Content / Action / Result) ─────────
it('encodes LongMsgResult (repeated Action → Content → PushMsgBody[]) identically', () => {
const inner: PushMsgBody = {
responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 1, fromUid: 'a', toUid: 'b' },
contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 1, sequence: 1, timestamp: 1 },
body: { richText: { elems: [{ text: { str: 'forwarded' } }] } },
};
const data: LongMsgResult = {
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [inner, inner] },
},
],
};
const legacy = protoEncode(data as any, LongMsgResultSchema);
const proton = protobuf_encode<LongMsgResult>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── notify.ts coverage ──────────────────────────────────────────────
it('encodes GroupChange identically', () => {
const data: GroupChange = {
groupUin: 555,
flag: 1,
memberUid: 'u_x',
decreaseType: 130,
operatorBytes: new Uint8Array([1, 2, 3]),
increaseType: 1,
};
const legacy = protoEncode(data as any, GroupChangeSchema);
const proton = protobuf_encode<GroupChange>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes GroupAdmin (extraEnable variant) identically', () => {
const data: GroupAdmin = {
groupUin: 777, flag: 1, isPromote: true,
body: { extraEnable: { adminUid: 'u_admin', isPromote: true } },
};
const legacy = protoEncode(data as any, GroupAdminSchema);
const proton = protobuf_encode<GroupAdmin>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes NotifyMessageBody (recall variant with repeated RecallMessage) identically', () => {
const data: NotifyMessageBody = {
type: 17,
groupUin: 555,
recall: {
operatorUid: 'u_op',
recallMessages: [
{ sequence: 1, time: 100, random: 42, type: 1, flag: 1, authorUid: 'u_a' },
{ sequence: 2, time: 200, random: 43, type: 1, flag: 1, authorUid: 'u_a' },
],
groupType: 1, opType: 2,
tipInfo: { tip: 'recalled' },
},
msgSequence: 99,
};
const legacy = protoEncode(data as any, NotifyMessageBodySchema);
const proton = protobuf_encode<NotifyMessageBody>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes GroupReactNotify (deeply nested) identically', () => {
const data: GroupReactNotify = {
groupUin: 555n,
field13: 35,
groupReactionData: {
data: {
data: {
groupReactionTarget: { seq: 12345n },
groupReactionDataContent: { code: '128516', count: 1, operatorUid: 'u_op', type: 1 },
},
},
},
};
const legacy = protoEncode(data as any, GroupReactNotifySchema);
const proton = protobuf_encode<GroupReactNotify>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes FriendRequest identically', () => {
const data: FriendRequestNotify = {
info: { targetUid: 'u_me', sourceUid: 'u_them', newSource: 'qrcode', message: 'hello!', source: 'web' },
};
const legacy = protoEncode(data as any, FriendRequestSchema);
const proton = protobuf_encode<FriendRequestNotify>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes GroupJoin identically', () => {
const data: GroupJoin = {
groupUin: 555, field2: 1, targetUid: 'u_them', field4: 1,
field6: 1, field7: 'reason', field8: 1, field9: new Uint8Array([0xaa]),
};
const legacy = protoEncode(data as any, GroupJoinSchema);
const proton = protobuf_encode<GroupJoin>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── action.ts coverage ─────────────────────────────────────────────
it('encodes RoutingHead (c2c variant) identically', () => {
const data: RoutingHead = { c2c: { uin: 10001, uid: 'u_a' } };
const legacy = protoEncode(data as any, RoutingHeadSchema);
const proton = protobuf_encode<RoutingHead>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes RoutingHead (group variant) identically', () => {
const data: RoutingHead = { grp: { groupCode: 555n } };
const legacy = protoEncode(data as any, RoutingHeadSchema);
const proton = protobuf_encode<RoutingHead>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SendMessageRequest (group with two text elements) identically', () => {
const data: SendMessageRequest = {
routingHead: { grp: { groupCode: 555n } },
contentHead: { type: 1, subType: 1, c2cCmd: 11 },
messageBody: {
richText: {
elems: [
{ text: { str: 'hi ' } },
{ text: { str: 'world', link: 'lnk' } },
],
},
},
clientSequence: 1,
random: 12345,
syncCookie: new Uint8Array([0xaa, 0xbb]),
via: 1,
dataStatist: 1,
multiSendSeq: 1,
};
const legacy = protoEncode(data as any, SendMessageRequestSchema);
const proton = protobuf_encode<SendMessageRequest>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SendMessageResponse identically', () => {
const data: SendMessageResponse = {
result: 1, errMsg: 'ok', timestamp1: 1234567890,
field10: 1, groupSequence: 100, timestamp2: 1234567891, privateSequence: 200,
};
const legacy = protoEncode(data as any, SendMessageResponseSchema);
const proton = protobuf_encode<SendMessageResponse>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes MentionExtraSend identically', () => {
const data: MentionExtraSend = { type: 2, uin: 10001, field5: 1, uid: 'u_a' };
const legacy = protoEncode(data as any, MentionExtraSendSchema);
const proton = protobuf_encode<MentionExtraSend>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes MarkdownData identically', () => {
const data: MarkdownData = { content: '**bold** _italic_' };
const legacy = protoEncode(data as any, MarkdownDataSchema);
const proton = protobuf_encode<MarkdownData>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── Documented divergence: proto3 default-value omission ────────────
it('proton omits default-valued numeric fields (legacy emits them)', () => {
// proto3 wire format says fields equal to their default value MUST NOT be
// emitted. Proton follows that; the legacy runtime encoder always emits.
// Either form is round-trippable through a conforming proto3 reader — the
// missing field decodes as its default. This test pins that behaviour.
const data: LongMsgSettings = { field1: 0, field2: 0, field3: 0, field4: 0 };
const legacy = protoEncode(data as any, LongMsgSettingsSchema);
const proton = protobuf_encode<LongMsgSettings>(data);
expect(hex(proton)).toBe(''); // nothing on the wire
expect(legacy.length).toBeGreaterThan(0); // legacy emits all zeros
// Legacy emits explicit zero values; a proto3-conforming reader sees them
// back when decoding. (Decoding the empty wire returns null because the
// legacy decoder treats an empty buffer as "no message at all" — that's
// also semantically equivalent to "all-default values" in proto3.)
expect(protoDecode(legacy, LongMsgSettingsSchema)).toMatchObject({
field1: 0, field2: 0, field3: 0, field4: 0,
});
});
// ── round-trip via decode ───────────────────────────────────────────
it('round-trips SendLongMsgResp through proton encode → legacy decode', () => {
const data: SendLongMsgResp = { result: { resId: 'rt-1' } };
const encoded = protobuf_encode<SendLongMsgResp>(data);
const decoded = protoDecode(encoded, SendLongMsgRespSchema);
expect(decoded?.result?.resId).toBe('rt-1');
});
it('round-trips SendLongMsgResp through legacy encode → proton decode', () => {
const data: SendLongMsgResp = { result: { resId: 'rt-2' } };
const encoded = protoEncode(data as any, SendLongMsgRespSchema);
const decoded = protobuf_decode<SendLongMsgResp>(encoded);
expect(decoded.result?.resId).toBe('rt-2');
});
});