Files
SnowLuma/packages/core/tests/actions/misc.test.ts
T
DrSmoothl 5802812392 feat(proton): finish OIDB migration — runOidb on protobuf_encode<OidbBase<T>>
Closes the OIDB phase of the proton migration. Every consumer that
talked to the OIDB service through the old runtime
`makeOidbBaseSchema()` factory now goes through the compile-time
generic `OidbBase<T>` instead — proton monomorphizes the codec per
call-site instantiation.

@snowluma/proton — two analyzer fixes uncovered by the migration:

1. Skip queuing call-site type-args that reference an *enclosing
   generic function's* type parameter for monomorphization. Before
   this, a wrapper like

     export function encodeOidbEnv<T>(env: OidbBase<T>): Uint8Array {
       return protobuf_encode<OidbBase<T>>(env);
     }

   would cause the analyzer to mint a literal `OidbBase__T` registry
   entry with `body.typeName = 'T'`, which the post-walk wire-type
   guard then tripped on. The enclosing-scope type params are tracked
   on a stack as the walker descends into FunctionDeclaration,
   FunctionExpression, ArrowFunction, MethodDeclaration nodes; matching
   call sites are skipped (the wrapper-binding path is still
   responsible for materialising concrete codecs at downstream call
   sites).

2. Register *explicitly* empty interfaces (`interface X {}`) as
   zero-field proto messages. OIDB has a handful of these
   ('this call has no meaningful response body' placeholders —
   Oidb0xeb7Resp, Oidb0xcd4Resp, Oidb0x112aResp, Oidb0x8a0Resp,
   Oidb0xf16Resp, OidbClientKeyReq). Proto3 wire allows zero-field
   messages, and downstream code does `protobuf_decode<OidbBase<X>>`
   where X is one of these — the wire-type guard would otherwise trip
   on the missing `X` registration. Interfaces that have members but
   no pb-marked fields are still NOT registered.

@snowluma/core — the OIDB-layer refactor itself:

bridge-oidb.ts ditches the runtime ProtoSchema factory and exposes:
  - makeOidbEnvelope<T>(oidbCmd, subCmd, body, isUid)   pure helper
  - encodeOidbEnv<T>(env)                               pass-through
  - decodeOidbEnv<T>(bytes)                             pass-through
  - runOidb(bridge, cmd, envelopeBytes)                 non-generic raw

`encodeOidbEnv` / `decodeOidbEnv` are pure pass-through generic
wrappers — proton wrapper-binds them and substitutes every call site
with the inlined `protobuf_encode_OidbBase__X` / `protobuf_decode_…`
function. `runOidb` is non-generic (proton leaves it alone) so it can
be mocked in tests. `makeOidbEnvelope` is plain TS — also mockable for
introspection.

56 `runOidb` call sites across 11 files migrated to the new API:
  - bridge-contacts.ts, actions/extras.ts, actions/friend.ts,
    actions/group-admin.ts, actions/group-file.ts,
    actions/group-message.ts, actions/interaction.ts,
    actions/misc.ts, actions/profile.ts, web-actions/cookies.ts,
    highway/pipeline.ts

pipeline.ts also drops `makeOidbBaseSchema(NTV2UploadRichMediaReqSchema)`
and the residual `protoEncode({...}, EncodableMediaMsgInfoSchema)` —
both go through proton now.

Tests:
  - 8 test files migrated from `vi.mocked(decodeOidbEnv).mockReturnValueOnce`
    to `vi.mocked(runOidb).mockResolvedValueOnce(protobuf_encode<OidbBase<X>>({body: …}))`
    — the proton substitution means the old mock layer is bypassed at
    build time, so the only mockable point is the bytes layer at `runOidb`.
  - 2 new parity tests pinning `OidbBase<T>` ↔ legacy
    `makeOidbBaseSchema(InnerSchema)` byte equivalence.

Verification:
  - @snowluma/proton: 95/95 tests pass, tsc --noEmit clean
  - @snowluma/core:   605/605 tests pass (network-manager.test.ts
    fails to load due to a missing darwin-arm64 native binary in this
    environment — pre-existing), tsc --noEmit clean
2026-05-19 08:19:14 +08:00

102 lines
3.9 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '../../src/bridge/proto/proton/oidb';
import type {
Oidb0x990Resp,
Oidb0x112eResp,
} from '../../src/bridge/proto/proton/oidb-action';
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// — the plugin substitutes them at the call site with the inlined codec,
// so mocking them on the module object is a no-op. We mock `runOidb`
// (non-generic, untouched by proton) to return real proton-encoded bytes
// that the production-side codec then actually decodes.
vi.mock('../../src/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('../../src/bridge/bridge-oidb')>(
'../../src/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '../../src/bridge/bridge-oidb';
import * as misc from '../../src/bridge/actions/misc';
import { mockBridge } from './_helpers';
describe('actions/misc', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('translateEn2Zh returns dstWords when present', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x990Resp>>({
body: { translateResp: { dstWords: ['你好', '世界'] } } as any,
}),
);
const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']);
expect(out).toEqual(['你好', '世界']);
});
it('translateEn2Zh throws on empty response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x990Resp>>({ body: {} }),
);
await expect(misc.translateEn2Zh(bridge as any, ['hello']))
.rejects.toThrow(/empty/);
});
it('getMiniAppArk rejects unsupported types', async () => {
const bridge = mockBridge();
await expect(
misc.getMiniAppArk(bridge as any, 'youtube', 't', 'd', 'p', 'u'),
).rejects.toThrow(/unsupported type/);
});
it('getMiniAppArk routes to LightAppSvc with the encoded body', async () => {
// sendRawPacket is what the action calls; we need a deterministic
// successful response with a decodable body. Easiest: stub the
// raw packet with the encoded response we expect to come back.
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: null,
})) as any,
});
// With null responseData, the action should throw on decode — that
// still proves the right serviceCmd was used.
await expect(misc.getMiniAppArk(bridge as any, 'bili', 't', 'd', 'p', 'u')).rejects.toThrow();
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.sendRawPacket.mock.calls[0]![0])
.toBe('LightAppSvc.mini_app_share.AdaptShareInfo');
});
it('clickInlineKeyboardButton returns shaped result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x112eResp>>({
body: { result: 1, errMsg: 'ok', promptText: 'hi' } as any,
}),
);
const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100);
expect(out).toMatchObject({ result: 1, errMsg: 'ok', promptText: 'hi', status: 0 });
});
it('sendGroupSign dispatches to 0xEB7_1', async () => {
const bridge = mockBridge();
await misc.sendGroupSign(bridge as any, 12345);
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xEB7_1');
});
});