This commit is contained in:
手瓜一十雪 committed 2026-10-24 17:28:58 +08:00
1 parent 8e28bca775
commit 1172a6bd3d
100 files changed
+8305 -6025

No files matched your search

@@ -1,169 +0,0 @@
import { describe, it, expect } from 'vitest';
import { analyzeSource } from '../../src/ast/analyzer';
import { WireType } from '../../src/ast/types';
import { loadFixture } from '../helpers';
describe('AST analyzer', () => {
it('collects TestProtobuf with correct fields', () => {
const registry = analyzeSource(loadFixture('real.ts'), 'real.ts');
const msg = registry.get('TestProtobuf')!;
expect(msg).toBeDefined();
expect(msg.fields).toHaveLength(1);
expect(msg.fields[0]).toMatchObject({
name: 'name',
fieldNumber: 1,
typeName: 'uint_32',
isMessage: false,
});
});
it('collects nested message field', () => {
const registry = analyzeSource(loadFixture('real.ts'), 'real.ts');
const msg = registry.get('TestProtobufOutput')!;
expect(msg.fields[0]).toMatchObject({
name: 'name',
fieldNumber: 1,
typeName: 'TestProtobuf',
isMessage: true,
});
});
it('topological order: dependencies first', () => {
const keys = [...analyzeSource(loadFixture('real.ts'), 'real.ts').keys()];
expect(keys.indexOf('TestProtobuf')).toBeLessThan(keys.indexOf('TestProtobufOutput'));
});
it('skips generic interfaces (no call sites)', () => {
expect(analyzeSource(loadFixture('generic-template.ts'), 'g.ts').size).toBe(0);
});
it('returns empty for non-pb interfaces', () => {
expect(analyzeSource(loadFixture('no-pb.ts'), 'no.ts').size).toBe(0);
});
it('handles multiple fields', () => {
const msg = analyzeSource(loadFixture('multi-field.ts'), 't.ts').get('UserProfile')!;
expect(msg.fields).toHaveLength(3);
expect(msg.fields[0]).toMatchObject({ name: 'id', fieldNumber: 1, typeName: 'uint_32' });
expect(msg.fields[1]).toMatchObject({
name: 'username',
fieldNumber: 2,
typeName: 'string',
});
expect(msg.fields[2]).toMatchObject({ name: 'active', fieldNumber: 3, typeName: 'bool' });
});
it('collects repeated fields', () => {
const msg = analyzeSource(loadFixture('repeated.ts'), 't.ts').get('RepeatedMsg')!;
expect(msg.fields).toHaveLength(2);
expect(msg.fields[0]).toMatchObject({
name: 'ids',
fieldNumber: 1,
typeName: 'uint_32',
isRepeated: true,
});
expect(msg.fields[1]).toMatchObject({
name: 'names',
fieldNumber: 2,
typeName: 'string',
isRepeated: true,
});
});
it('monomorphizes generics from call sites', () => {
const registry = analyzeSource(loadFixture('generic-usage.ts'), 'g.ts');
expect(registry.has('TestProtobufAny__string')).toBe(true);
expect(registry.has('TestProtobufAny__TestProtobufAny__string')).toBe(true);
});
// ── Edge cases (originally silently dropped / wrong wire type) ──────
it('edge: monomorphizes a generic-instantiated field on a concrete interface', () => {
// Regression: a concrete interface with `pb<N, Wrapper<T>>` previously
// resolved the field's typeName to the bare identifier `"Wrapper"` and
// never enqueued `Wrapper<T>` for monomorphization. The field was left
// with the placeholder WireType.Varint, corrupting the wire format.
const registry = analyzeSource(loadFixture('nested-generic-field.ts'), 'n.ts');
expect(registry.has('Wrapper__uint_32')).toBe(true);
const container = registry.get('Container')!;
expect(container).toBeDefined();
expect(container.fields[0]).toMatchObject({
name: 'wrapped',
fieldNumber: 5,
typeName: 'Wrapper__uint_32',
isMessage: true,
wireType: WireType.LengthDelim,
});
});
it('edge: monomorphizes a generic-instantiated field on a generic template', () => {
// Regression: a generic template field typed as `pb<N, Wrapper<U>>` —
// where `U` is the outer template's type param — was stored with the
// mangled-but-unsubstituted name `'Wrapper__U'` and never re-instantiated
// with the concrete substitution at monomorphization time. The field
// ended up referencing `Wrapper__U` instead of `Wrapper__uint_32` and the
// inner mangled instantiation was missing from the registry.
const registry = analyzeSource(loadFixture('generic-with-generic-field.ts'), 'g.ts');
expect(registry.has('Outer__uint_32')).toBe(true);
expect(registry.has('Wrapper__uint_32')).toBe(true);
const outer = registry.get('Outer__uint_32')!;
expect(outer.fields[0]).toMatchObject({
name: 'wrapped',
fieldNumber: 5,
typeName: 'Wrapper__uint_32',
isMessage: true,
wireType: WireType.LengthDelim,
});
const wrapper = registry.get('Wrapper__uint_32')!;
expect(wrapper.fields[0]).toMatchObject({
name: 'value',
fieldNumber: 1,
typeName: 'uint_32',
isMessage: false,
});
});
it('edge: throws when a field references an unresolved type name', () => {
// Defensive guard: anything that escapes the analyzer's type tracking
// (unions, intersections, mapped/conditional types, `Partial<T>`, etc.)
// used to silently leak `WireType.Varint` into the codegen. Now it has
// to fail loudly so future edge cases surface immediately.
const source = `
interface BadMsg {
weird: pb<1, MissingType>;
}
const buf = protobuf_encode<BadMsg>({} as any);
`;
expect(() => analyzeSource(source, 'b.ts')).toThrow(/MissingType/);
});
it('edge: recognises aliased pb / pb_repeated marker imports', () => {
// Regression: `parsePbTypeRef` compared the literal type-ref identifier
// text against the constants `'pb'` / `'pb_repeated'`. With
// `import { pb as P }` the text became `'P'`, so every field on the
// interface was silently dropped and `Aliased` never made it into the
// registry.
const registry = analyzeSource(loadFixture('aliased-pb-marker.ts'), 'a.ts');
const aliased = registry.get('Aliased')!;
expect(aliased).toBeDefined();
expect(aliased.fields).toHaveLength(2);
expect(aliased.fields[0]).toMatchObject({
name: 'id',
fieldNumber: 1,
typeName: 'uint_32',
isRepeated: false,
});
expect(aliased.fields[1]).toMatchObject({
name: 'tags',
fieldNumber: 2,
typeName: 'string',
isRepeated: true,
});
});
});
@@ -0,0 +1,242 @@
import { describe, expect, it } from 'vitest';
import { run, imports } from '../upstream/compile';
import { bundle } from '../upstream/project';
import { schemaCodecs, schemaRegistry } from '../upstream/schema';
import { generateCode } from '../../src/codegen/generator';
import { protobuf_getUnknownFields } from '../../src/runtime';
import { ProtobufCompiler } from '../../src/compiler/compiler';
import { withProject } from '../upstream/project';
import { join } from 'node:path';
describe('SnowLuma compatibility', () => {
it('leaves generic data unions and nested business types outside codec discovery', () => {
expect(
run(`
type Json = string | Json[];
interface Field<T> {value:T; metadata:Json;}
type Wrapper<T> = Field<T> & { extra?:Json };
function identity<T>(value:Field<T>) {return value;}
function generic<T>(field:Field<Wrapper<T>>) {return identity(field);}
function result<T>(ok:boolean, value:T) {if(ok) return {ok:true, value}; return {ok:false, value};}
const field:Field<Wrapper<string>> = {value:{value:'ok', metadata:[]}, metadata:[]};
export const output = result(true, generic(field)).value.value.value;
`).output,
).toBe('ok');
});
it('keeps unrelated callback aliases and inferred containers lazy', () => {
expect(
run(`
type Json = string | Json[];
type Handler<T> = (value:T) => void;
interface Field<T> {value:T; metadata:Json;}
const field:Field<Json> = {value:'ok', metadata:[]};
function wrap<T>(value:Field<T>) {return {get(){return value.value;}};}
const handler:Handler<Json> = (value) => {};
handler('x');
export const result = wrap(field).get();
`).result,
).toBe('ok');
});
it('propagates composite class bindings through generic factories', () => {
expect(
run(`
interface Box<T> { value:pb<1,T>; }
class Codec<T> { encode(value:T) { return protobuf_encode<T>(value); } }
function create<T>() { return new Codec<Box<T>>(); }
export const result = [...create<uint_32>().encode({value:7})];
`).result,
).toEqual([8, 7]);
});
it('defers unrelated class type arguments but validates codec class schemas', () => {
expect(
run(`
type Json = string | Json[];
class Field<T> { value(): null { return null; } }
function field() { return new Field<Json>(); }
export const result = field().value();
`).result,
).toBeNull();
expect(() =>
run(`
class Codec<T> { encode(value:T) {return protobuf_encode<T>(value);} }
new Codec<Missing>().encode({});
`),
).toThrow(/Unresolved type Missing/);
});
it('infers matching generic containers without expanding unrelated recursive data', () => {
expect(
run(`
type Json = string | Json[];
interface Field<T> { value: T; metadata: Json; }
function arrayField<E>(field: Field<E>) { return Object.assign({}, { get: () => field.value }); }
function wrap<E>(field: Field<E>) { return arrayField(field); }
const field: Field<string> = { value:'ok', metadata:[] };
export const result = wrap(field).get();
`).result,
).toBe('ok');
});
it('does not resolve recursive data aliases while looking for class receivers', () => {
expect(
run(`
type Data<T> = { children: T[]; name: string };
type Element = Data<Element>;
type Wrapped<T> = T;
function data(): Wrapped<Element> { return { children: [], name: 'ok' }; }
export const result = data().name.toUpperCase();
`).result,
).toBe('OK');
});
it('does not resolve ordinary generic return values or data alias members as callbacks', () => {
expect(
run(`
type Id<T> = T;
interface Data { value: string; children: Id<Data>[]; }
const data: Id<Data> = {value:'ok', children:[]};
function decode<T>(raw: Uint8Array, callback: () => T): T | null { return callback(); }
const raw: Uint8Array = new Uint8Array();
const decoded = decode(raw, () => data);
export const result = [decoded.value, data.value];
`).result,
).toEqual(['ok', 'ok']);
});
it('does not specialize ambient library functions', async () => {
const source = `import { expect } from './external';
const data: Record<string, unknown> = {};
expect(data).check();`;
await withProject(
{
'external.d.ts': 'export declare function expect<T>(value: T): { check(): void };',
'entry.ts': source,
},
(directory) => {
expect(
new ProtobufCompiler().compile(source, join(directory, 'entry.ts')),
).toBeNull();
},
);
});
it('leaves ordinary calls and data receivers outside schema resolution', () => {
expect(
run(`
interface Options { meta?: Record<string, unknown>; }
function options(value: Options): Options { return value; }
const input: Options = { meta: { source: 'test' } };
const copy = options(input);
function data(flag: boolean) { if (flag) return { value: 7 }; return { value: 8 }; }
function bytes(value: Uint8Array): Uint8Array { return value; }
const raw: Uint8Array = new Uint8Array([1]);
export const result = [copy.meta.source, data(true).value, bytes(raw).length];
`).result,
).toEqual(['test', 7, 1]);
});
it('keeps TypeScript optionality separate from explicit wire presence', () => {
const result = run(`
interface Msg {
plain?: pb<1, uint_32>;
flag?: pb<2, bool>;
text?: pb<3, string>;
data?: pb<4, bytes>;
big?: pb<5, uint_64>;
forced?: pb_optional<6, uint_32>;
}
export const wire = [...protobuf_encode<Msg>({
plain: 0, flag: false, text: '', data: new Uint8Array(), big: 0n, forced: 0,
})];
export const decoded = protobuf_decode<Msg>(new Uint8Array(wire));
`);
expect(result.wire).toEqual([48, 0]);
expect(result.decoded).toEqual({
plain: null,
flag: null,
text: null,
data: null,
big: null,
forced: 0,
});
});
it('retains aliased markers and presence through exported generic wrappers', async () => {
const result = await bundle({
'schema.ts': `import type { pb as P, pb_optional as O, pb_repeated as R, uint_32 } from '@snowluma/proton';
export interface Box<T> { value?: P<1, T>; }
export interface Msg { plain?: P<1, uint_32>; forced?: O<2, uint_32>; items?: R<3, uint_32>; }
export interface Outer<U> { inner?: P<1, Box<U>>; }`,
'barrel.ts': `export * from './schema';`,
'wrapper.ts': `${imports} import type {Outer} from './barrel';
export function encode<T>(value:Outer<T>) { return protobuf_encode<Outer<T>>(value); }`,
'forward.ts': `import {encode} from './wrapper'; import type {Outer} from './barrel';
export function forward<T>(value:Outer<T>) { return encode<T>(value); }`,
'entry.ts': `${imports} import type {Msg} from './barrel'; import {forward} from './forward';
export const wire = [...forward<Msg>({inner:{value:{plain:0,forced:0,items:[0,7]}}})];`,
});
expect(result.wire).toEqual([10, 8, 10, 6, 16, 0, 24, 0, 24, 7]);
});
it.each([true, false])('resolves package exports with tsconfig=%s', async (withConfig) => {
const result = await bundle({
...(withConfig
? {
'tsconfig.json': JSON.stringify({
compilerOptions: { moduleResolution: 'bundler', module: 'esnext' },
}),
}
: {}),
'node_modules/@fake/schemas/package.json': JSON.stringify({
name: '@fake/schemas',
type: 'module',
exports: { '.': { types: './index.ts', default: './index.ts' } },
}),
'node_modules/@fake/schemas/index.ts': `export * from './schema';`,
'node_modules/@fake/schemas/schema.ts': `export interface Msg { value:pb<1,uint_32>; }`,
'entry.ts': `${imports} import type {Msg} from '@fake/schemas';
export const result = protobuf_decode<Msg>(protobuf_encode<Msg>({value:42}));`,
});
expect(result).toEqual({ result: { value: 42 } });
});
const codec = schemaCodecs<{ value: number }>('interface Msg { value:pb<1,uint_32>; }');
it.each([
['unterminated group', [0x13, 8, 7]],
['mismatched group', [0x13, 0x1c]],
['unexpected group end', [0x14]],
['invalid group tag', [0x13, 0]],
['group payload exceeds frame', [0x13, 0x1a, 4, 0x14]],
['group recursion limit', [...Array(66).fill(0x13), ...Array(66).fill(0x14)]],
] as const)('rejects %s', (_name, bytes) => {
expect(() => codec.decode(Uint8Array.from(bytes))).toThrow(/protobuf/);
});
it('skips nested groups and retains non-enumerable metadata', () => {
const decoded = codec.decode(Uint8Array.from([0x13, 0x1b, 8, 99, 0x1c, 0x14, 8, 7]));
expect(decoded).toEqual({ value: 7 });
expect(protobuf_getUnknownFields(decoded)).toEqual([
{ fieldNumber: 2, wireType: 3, count: 1, totalByteLength: 5 },
]);
expect(JSON.stringify(decoded)).toBe('{"value":7}');
expect([...codec.encode(decoded)]).toEqual([8, 7]);
});
it.each([
[NaN, 0],
[0, NaN],
[0.5, 1],
[0, 0.5],
[-1, 1],
[1, 0],
[0, 3],
[0, Infinity],
])('rejects invalid decoder bounds %s..%s', (offset, end) => {
const generated = generateCode(schemaRegistry('interface Msg { value:pb<1,uint_32>; }'));
const decode = new Function(generated + '\nreturn protobuf_decode_Msg;')();
expect(() => decode(new Uint8Array([8, 1]), offset, end)).toThrow(/bounds/);
});
});
@@ -1,402 +0,0 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer';
import { generateCode } from '../../src/codegen/generator';
import { applyReplacements } from '../../src/transform/replacer';
import { resolveImports, type ParsedFileEntry } from '../../src/ast/import-resolver';
import { execAndGet } from '../helpers';
const crossDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures', 'cross-file');
function loadCross(name: string): { code: string; path: string } {
const path = resolve(crossDir, name);
return { code: readFileSync(path, 'utf-8'), path };
}
describe('cross-file import resolution', () => {
// ── Scenario A: imported type in encode/decode call site ──────────
it('resolves imported type for protobuf_encode/decode call site', () => {
const { code, path } = loadCross('consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
expect(imported.concrete.some((m) => m.name === 'UserMsg')).toBe(true);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
expect(registry.has('UserMsg')).toBe(true);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_UserMsg');
expect(transformedCode).toContain('protobuf_decode_UserMsg');
});
it('Scenario A round-trip', () => {
const { code, path } = loadCross('consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry);
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_UserMsg({ id: 42, name: 'alice' });
globalThis.__r = protobuf_decode_UserMsg(enc);
`,
'__r',
);
expect(result.id).toBe(42);
expect(result.name).toBe('alice');
});
// ── Scenario B: imported type as pb<> field ──────────────────────
it('resolves imported nested message type', () => {
const { code, path } = loadCross('outer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
expect(imported.concrete.some((m) => m.name === 'Inner')).toBe(true);
const registry = analyzeSource(code, path, imported);
expect(registry.has('Inner')).toBe(true);
expect(registry.has('Outer')).toBe(true);
const outer = registry.get('Outer')!;
const innerField = outer.fields.find((f) => f.name === 'inner')!;
expect(innerField.isMessage).toBe(true);
});
it('Scenario B round-trip', () => {
const { code, path } = loadCross('outer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry);
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_Outer({ inner: { value: 42 } });
globalThis.__r = protobuf_decode_Outer(enc);
`,
'__r',
);
expect(result.inner.value).toBe(42);
});
// ── Generic template import ──────────────────────────────────────
it('resolves imported generic template', () => {
const { code, path } = loadCross('generic-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
expect(imported.templates.has('Wrapper')).toBe(true);
const registry = analyzeSource(code, path, imported);
expect(registry.has('Wrapper__string')).toBe(true);
});
it('generic import round-trip', () => {
const { code, path } = loadCross('generic-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry);
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_Wrapper__string({ value: 'hello' });
globalThis.__r = protobuf_decode_Wrapper__string(enc);
`,
'__r',
);
expect(result.value).toBe('hello');
});
it('resolves generic type passed through imported wrapper functions', () => {
const { code, path } = loadCross('wrapper-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
expect(imported.templates.has('Wrapper')).toBe(true);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(2);
expect(used.callSites[0].fnName).toBe('protobuf_encode');
expect(used.callSites[1].fnName).toBe('protobuf_decode');
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
used.registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
});
it('handles wrapper aliases, arrows, nested generics, and non-first generic forwarding', () => {
const { code, path } = loadCross('wrapper-edge-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(5);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
used.registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__Wrapper__string(');
expect(transformedCode).toContain('passthroughOnly<Wrapper<string>>');
});
it('handles local wrapper functions in the entry file', () => {
const { code, path } = loadCross('local-wrapper-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(2);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
used.registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
});
it('handles complex wrapper objects, branches, nested helpers, and chains', () => {
const { code, path } = loadCross('wrapper-complex-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(7);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
used.registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
expect(transformedCode).not.toContain('encodeChained<Wrapper<string>>');
});
it('handles wrapper protobuf type derived from another generic type', () => {
const { code, path } = loadCross('wrapper-type-source-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(5);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
used.registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
expect(transformedCode).not.toContain('encodeBoxed<string>');
});
// ── Transitive imports ───────────────────────────────────────────
it('resolves transitive imports (A → B → C)', () => {
const { code, path } = loadCross('top.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
expect(imported.concrete.some((m) => m.name === 'Mid')).toBe(true);
expect(imported.concrete.some((m) => m.name === 'Deep')).toBe(true);
const registry = analyzeSource(code, path, imported);
expect(registry.has('Top')).toBe(true);
expect(registry.has('Mid')).toBe(true);
expect(registry.has('Deep')).toBe(true);
});
it('transitive import round-trip', () => {
const { code, path } = loadCross('top.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry);
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_Top({ nested: { inner: { val: 99 } } });
globalThis.__r = protobuf_decode_Top(enc);
`,
'__r',
);
expect(result.nested.inner.val).toBe(99);
});
// ── Cache behavior ───────────────────────────────────────────────
it('uses cache on repeated resolves', () => {
const { code, path } = loadCross('consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
resolveImports(code, path, cache);
expect(cache.size).toBeGreaterThan(0);
const cached = new Map(cache);
resolveImports(code, path, cache);
// Same entries, not re-created
for (const [key, val] of cache) {
expect(val).toBe(cached.get(key));
}
});
// ── Graceful fallback ────────────────────────────────────────────
it('handles missing import file gracefully', () => {
const code = `import type { Ghost } from './nonexistent';\nconst x = 1;`;
const fakePath = resolve(crossDir, 'fake.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, fakePath, cache);
expect(imported.concrete).toEqual([]);
expect(imported.templates.size).toBe(0);
});
it('only resolves imports reachable from protobuf call roots', () => {
const code = `
import { protobuf_encode } from '@snowluma/proton';
import type { UserMsg } from './types';
import type { Inner } from './inner';
const buf = protobuf_encode<UserMsg>({ id: 42, name: 'alice' });
`;
const fakePath = resolve(crossDir, 'on-demand.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, fakePath, cache);
expect(imported.concrete.map((m) => m.name)).toEqual(['UserMsg']);
expect(cache.has(resolve(crossDir, 'types.ts'))).toBe(true);
expect(cache.has(resolve(crossDir, 'inner.ts'))).toBe(false);
});
// ── Value import (non-type import) ───────────────────────────────
it('resolves value import { SimpleMessage } (not import type)', () => {
const { code, path } = loadCross('value-import-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
expect(imported.concrete.some((m) => m.name === 'SimpleMessage')).toBe(true);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
expect(registry.has('SimpleMessage')).toBe(true);
expect(callSites.length).toBe(2);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_SimpleMessage(');
expect(transformedCode).toContain('protobuf_decode_SimpleMessage(');
});
it('value import round-trip', () => {
const { code, path } = loadCross('value-import-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry);
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_SimpleMessage({ id: 42 });
globalThis.__r = protobuf_decode_SimpleMessage(enc);
`,
'__r',
);
expect(result.id).toBe(42);
});
it('canonicalizes imported type aliases to the original message name', () => {
const { code, path } = loadCross('aliased-consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('UserMsg')).toBe(true);
expect(used.registry.has('AliasMsg')).toBe(false);
expect(used.callSites).toHaveLength(2);
expect(used.callSites[0].typeName).toBe('UserMsg');
expect(used.callSites[1].typeName).toBe('UserMsg');
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
used.registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_UserMsg(');
expect(transformedCode).toContain('protobuf_decode_UserMsg(');
expect(transformedCode).not.toContain('protobuf_encode_AliasMsg(');
expect(transformedCode).not.toContain('protobuf_decode_AliasMsg(');
});
});
@@ -1,188 +0,0 @@
// Cross-package bare-specifier resolution.
//
// Companion to `cross-file.test.ts` — that suite covers relative-path
// imports between sibling files in the same package. Here we exercise
// the OTHER branch of `resolveModulePath`: a TypeScript-driven module
// resolution path that handles bare specifiers (`@scope/pkg`,
// `pkg-name`, …) so monorepo workspaces / npm packages can host proto
// definitions used from a different package.
//
// The motivating use case is decoupling `bridge/proto/proton/*.ts`
// from `@snowluma/core` into a standalone `@snowluma/proto-defs`
// package, so SnowLumaExtended (and any other consumer) can reuse the
// same wire definitions without copy-pasting them.
//
// The fixture is built in `os.tmpdir()` per-test-suite rather than
// committed to `test/fixtures/`. The reason: the resolution lookup
// has to find a real `node_modules/@fake/proto-defs/...` layout, and
// the repo-level `.gitignore` rule `**/node_modules/` would clobber a
// committed copy of that layout. A scratch tmpdir sidesteps the issue
// entirely and self-cleans in `afterAll`.
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs';
import { join, resolve } from 'path';
import { tmpdir } from 'os';
import { analyze, analyzeSource } from '../../src/ast/analyzer';
import { generateCode } from '../../src/codegen/generator';
import { applyReplacements } from '../../src/transform/replacer';
import { resolveImports, type ParsedFileEntry } from '../../src/ast/import-resolver';
import { execAndGet } from '../helpers';
describe('cross-package import resolution (bare specifier)', () => {
let tmpRoot: string;
let consumerPath: string;
beforeAll(() => {
// Build a tiny fake monorepo layout:
//
// <tmp>/
// consumer.ts ← uses `import { RemoteMsg } from '@fake/proto-defs'`
// node_modules/
// @fake/
// proto-defs/
// package.json ← exports → ./src/index.ts
// src/
// index.ts ← exported interfaces
//
// Bundler-mode `ts.resolveModuleName` walks importer → parent
// dirs looking for `node_modules`, so placing the consumer at
// `<tmp>/consumer.ts` lets `<tmp>/node_modules/...` satisfy the
// lookup.
tmpRoot = mkdtempSync(join(tmpdir(), 'proton-cross-pkg-'));
const pkgDir = resolve(tmpRoot, 'node_modules', '@fake', 'proto-defs');
mkdirSync(resolve(pkgDir, 'src'), { recursive: true });
// `exports."."` must point at a `.ts` source file — proton walks
// interface AST nodes to collect `pb<…>` field tags, and a
// generated `.d.ts` typically strips those generic args. Telling
// consumers to ship source `.ts` is the same model
// `@snowluma/proton` itself uses (`"default": "./src/runtime.ts"`).
writeFileSync(
resolve(pkgDir, 'package.json'),
JSON.stringify(
{
name: '@fake/proto-defs',
version: '1.0.0',
type: 'module',
main: './src/index.ts',
types: './src/index.ts',
exports: {
'.': {
types: './src/index.ts',
default: './src/index.ts',
},
},
},
null,
2,
),
);
writeFileSync(
resolve(pkgDir, 'src', 'index.ts'),
// proton's `collectInterface` recognises `pb<N, T>` as a marker
// type by NAME — no actual import of `@snowluma/proton` is
// needed for the fixture to parse. Matches the existing
// cross-file fixtures (`fixtures/cross-file/types.ts` does the
// same).
'export interface RemoteMsg {\n' +
' id?: pb<1, uint_32>;\n' +
' name?: pb<2, string>;\n' +
'}\n',
);
consumerPath = resolve(tmpRoot, 'consumer.ts');
writeFileSync(
consumerPath,
"import type { RemoteMsg } from '@fake/proto-defs';\n" +
'\n' +
"const buf = protobuf_encode<RemoteMsg>({ id: 42, name: 'alice' });\n" +
'const decoded = protobuf_decode<RemoteMsg>(buf);\n' +
'\n' +
'export { buf, decoded };\n',
);
});
afterAll(() => {
if (tmpRoot) {
rmSync(tmpRoot, { recursive: true, force: true });
}
});
it('collects interfaces from a `@fake/proto-defs` bare-specifier import', () => {
// Smoke test: the import resolver MUST find the package and pick
// up `RemoteMsg`. If this fails, `ts.resolveModuleName` likely
// can't find the fake node_modules layout (check that the
// BARE_SPECIFIER_COMPILER_OPTIONS in import-resolver.ts still
// sets `moduleResolution: Bundler`).
const code = readFileSync(consumerPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, consumerPath, cache);
expect(imported.concrete.some((m) => m.name === 'RemoteMsg')).toBe(true);
});
it('rewrites encode/decode call sites against the imported type', () => {
const code = readFileSync(consumerPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, consumerPath, cache);
const { registry, callSites, sourceFile } = analyze(code, consumerPath, imported);
expect(registry.has('RemoteMsg')).toBe(true);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_RemoteMsg');
expect(transformedCode).toContain('protobuf_decode_RemoteMsg');
});
it('round-trips encode/decode of a bare-specifier-imported message', () => {
// End-to-end: parse → analyze → generate codec → encode →
// decode → assert payload survived. The same shape as
// cross-file.test.ts's "Scenario A round-trip", but with the
// type sourced from a separate package.
const code = readFileSync(consumerPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, consumerPath, cache);
const registry = analyzeSource(code, consumerPath, imported);
const gen = generateCode(registry);
const result = execAndGet<{ id: number; name: string }>(
gen +
'\n' +
"const enc = protobuf_encode_RemoteMsg({ id: 42, name: 'alice' });\n" +
'globalThis.__r = protobuf_decode_RemoteMsg(enc);\n',
'__r',
);
expect(result.id).toBe(42);
expect(result.name).toBe('alice');
});
it('returns null for an unresolvable bare specifier (does not throw)', () => {
// Pre-existing relative-path behavior: missing files return
// null, never throw. The bare-specifier branch must match that
// — otherwise a typo in a package name turns into a build crash
// rather than a silent "no codec emitted" warning further down
// the pipeline.
const orphanPath = resolve(tmpRoot, 'orphan.ts');
writeFileSync(
orphanPath,
"import type { Whatever } from '@does-not-exist/nope';\n" +
'export type _ = Whatever;\n',
);
const code = readFileSync(orphanPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
// resolveImports swallows resolution failures by design — it
// simply produces an empty `concrete` for the unresolvable
// import. The assertion is that we got here without an exception.
const imported = resolveImports(code, orphanPath, cache);
expect(imported.concrete).toEqual([]);
});
});
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { analyzeSource } from '../../src/ast/analyzer';
import { schemaRegistry as analyzeSource } from '../upstream/schema';
import { generateCode } from '../../src/codegen/generator';
import { protobuf_getUnknownFieldMetadata } from '../../src/runtime';
import { loadFixture } from '../helpers';
@@ -72,8 +72,8 @@ describe('code generator', () => {
it('generates nested message code', () => {
const gen = generateCode(analyzeSource(loadFixture('nested.ts'), 't.ts'));
expect(gen).toContain('protobuf_encode_Inner(');
expect(gen).toContain('protobuf_decode_Inner(data, offset, _end)');
expect(gen).toContain('__write_Inner(');
expect(gen).toContain('protobuf_decode_Inner(data, offset, offset + _len)');
});
it('round-trip uint_32', () => {
@@ -212,23 +212,21 @@ interface Int32Msg {
// Compatibility applies only to complete uint64 varints. Truncated input
// and values wider than 64 bits must still fail loudly.
expect(() => dec(Uint8Array.from([0x08, 0x80]))).toThrow(/truncated uint64 varint/);
expect(() => dec(Uint8Array.from([0x08, 0x80]))).toThrow(/[Tt]runcated.*varint/);
expect(() =>
dec(
Uint8Array.from([0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02]),
),
).toThrow(/uint64 varint overflow/);
).toThrow(/Invalid protobuf varint/);
});
it('rejects malformed length-delimited fields without leaving parent bounds', () => {
const schema = `interface BytesMsg { data: pb<1, bytes>; }`;
const gen = generateCode(analyzeSource(schema, 'BytesMsg.ts'));
const { dec } = makeRoundTripFromSchema(schema, 'BytesMsg');
expect(gen).toContain('const _end = __checkedEnd(offset, _len, end);');
expect(() => dec(Uint8Array.from([0x0a, 0x80]))).toThrow(/truncated uint32 varint/);
expect(() => dec(Uint8Array.from([0x0a, 0x80]))).toThrow(/[Tt]runcated.*varint/);
expect(() => dec(Uint8Array.from([0x0a, 0x80, 0x80, 0x80, 0x80, 0x10]))).toThrow(
/uint32 varint overflow/,
/Invalid protobuf varint/,
);
});
@@ -1,348 +0,0 @@
import { describe, it, expect } from 'vitest';
import protobufVitePlugin from '../../src/index';
import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer';
import { generateCode } from '../../src/codegen/generator';
import { replaceCallSites } from '../../src/transform/replacer';
import { loadFixture, execAndGet } from '../helpers';
describe('plugin integration', () => {
it('full transform pipeline', () => {
const code = loadFixture('real.ts');
const registry = analyzeSource(code, 'real.ts');
expect(registry.size).toBe(2);
expect([...registry.keys()]).toEqual(['TestProtobuf', 'TestProtobufOutput']);
const gen = generateCode(registry);
expect(gen).toContain('protobuf_encode_TestProtobuf');
expect(gen).toContain('protobuf_decode_TestProtobufOutput');
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_TestProtobuf({ name: 123 })');
expect(transformedCode).toContain('protobuf_decode_TestProtobufOutput(data)');
});
it('end-to-end round-trip', () => {
const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts'));
const result = execAndGet<any>(
gen +
`\n
const wr = protobuf_encode_TestProtobufOutput({ name: { name: 123 } });
globalThis.__r = protobuf_decode_TestProtobufOutput(wr);
`,
'__r',
);
expect(result.name.name).toBe(123);
});
it('wire format: TestProtobuf { name: 123 }', () => {
const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts'));
const enc = execAndGet<Uint8Array>(
gen +
`\n
globalThis.__r = protobuf_encode_TestProtobuf({ name: 123 });
`,
'__r',
);
expect(enc.length).toBe(2);
expect(enc[0]).toBe(0x08);
expect(enc[1]).toBe(123);
});
it('wire format: nested message', () => {
const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts'));
const enc = execAndGet<Uint8Array>(
gen +
`\n
globalThis.__r = protobuf_encode_TestProtobufOutput({ name: { name: 456 } });
`,
'__r',
);
expect(enc[0]).toBe(0x0a);
expect(enc[1]).toBe(3);
expect(enc[2]).toBe(0x08);
expect(enc[3]).toBe(0xc8);
expect(enc[4]).toBe(0x03);
});
it('multi-field round-trip', () => {
const gen = generateCode(analyzeSource(loadFixture('multi-field.ts'), 't.ts'));
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_UserProfile({ id: 42, username: "alice", active: true });
globalThis.__r = protobuf_decode_UserProfile(enc);
`,
'__r',
);
expect(result.id).toBe(42);
expect(result.username).toBe('alice');
expect(result.active).toBe(true);
});
// ── generic monomorphization ───────────────────────────────────────
it('generic monomorphization registry', () => {
const registry = analyzeSource(loadFixture('generic-usage.ts'), 'g.ts');
expect(registry.has('TestProtobufAny__string')).toBe(true);
expect(registry.has('TestProtobufAny__TestProtobufAny__string')).toBe(true);
});
it('generic round-trip', () => {
const gen = generateCode(analyzeSource(loadFixture('generic-usage.ts'), 'g.ts'));
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_TestProtobufAny__TestProtobufAny__string({ name: { name: "hello" } });
globalThis.__r = protobuf_decode_TestProtobufAny__TestProtobufAny__string(enc);
`,
'__r',
);
expect(result.name.name).toBe('hello');
});
// ── repeated fields ────────────────────────────────────────────────
it('repeated fields round-trip', () => {
const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts'));
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_RepeatedMsg({ ids: [10, 20, 30], names: ["foo", "bar"] });
globalThis.__r = protobuf_decode_RepeatedMsg(enc);
`,
'__r',
);
expect(result.ids).toEqual([10, 20, 30]);
expect(result.names).toEqual(['foo', 'bar']);
});
it('repeated empty arrays', () => {
const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts'));
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_RepeatedMsg({ ids: [], names: [] });
globalThis.__r = protobuf_decode_RepeatedMsg(enc);
`,
'__r',
);
expect(result.ids).toEqual([]);
expect(result.names).toEqual([]);
});
// ── import-based usage ──────────────────────────────────────────────
it('handles code with import { protobuf_encode } from "@snowluma/proton"', () => {
const code = `
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
interface Msg { id: pb<1, uint_32>; }
const buf = protobuf_encode<Msg>({ id: 1 });
const decoded = protobuf_decode<Msg>(buf);
`;
const registry = analyzeSource(code, 'import-test.ts');
expect(registry.has('Msg')).toBe(true);
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Msg(');
expect(transformedCode).toContain('protobuf_decode_Msg(');
// import line preserved
expect(transformedCode).toContain("from '@snowluma/proton'");
});
it('import-based round-trip', () => {
const code = `
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
interface Msg { id: pb<1, uint_32>; name: pb<2, string>; }
const buf = protobuf_encode<Msg>({ id: 42, name: 'test' });
const decoded = protobuf_decode<Msg>(buf);
`;
const registry = analyzeSource(code, 'import-test.ts');
const gen = generateCode(registry);
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_Msg({ id: 42, name: 'test' });
globalThis.__r = protobuf_decode_Msg(enc);
`,
'__r',
);
expect(result.id).toBe(42);
expect(result.name).toBe('test');
});
it('runtime fallback throws error', async () => {
const { protobuf_encode, protobuf_decode } = await import('../../src/runtime');
expect(() => protobuf_encode({})).toThrow('not transformed');
expect(() => protobuf_decode(new Uint8Array())).toThrow('not transformed');
});
// ── import rename alias ─────────────────────────────────────────────
it('handles import { protobuf_encode as encode }', () => {
const code = `
import { protobuf_encode as encode, protobuf_decode as decode } from '@snowluma/proton';
interface Msg { id: pb<1, uint_32>; }
const buf = encode<Msg>({ id: 1 });
const decoded = decode<Msg>(buf);
`;
const registry = analyzeSource(code, 'alias-test.ts');
expect(registry.has('Msg')).toBe(true);
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Msg(');
expect(transformedCode).toContain('protobuf_decode_Msg(');
// alias calls replaced, import preserved
expect(transformedCode).not.toContain('encode<Msg>');
expect(transformedCode).not.toContain('decode<Msg>');
});
it('rename alias round-trip', () => {
const code = `
import { protobuf_encode as enc } from '@snowluma/proton';
interface Item { val: pb<1, uint_32>; name: pb<2, string>; }
const buf = enc<Item>({ val: 99, name: 'x' });
`;
const registry = analyzeSource(code, 'alias-rt.ts');
const gen = generateCode(registry);
const result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_Item({ val: 99, name: 'x' });
globalThis.__r = protobuf_decode_Item(enc);
`,
'__r',
);
expect(result.val).toBe(99);
expect(result.name).toBe('x');
});
it('collects call roots first and generates only used dependency closure', () => {
const code = `
import { protobuf_encode } from '@snowluma/proton';
interface Inner { id: pb<1, uint_32>; }
interface UsedMsg { inner: pb<1, Inner>; }
interface UnusedMsg { value: pb<1, string>; }
const buf = protobuf_encode<UsedMsg>({ inner: { id: 1 } });
`;
const { registry, callSites, sourceFile } = analyze(code, 'used-only.ts');
const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('UsedMsg')).toBe(true);
expect(used.registry.has('Inner')).toBe(true);
expect(used.registry.has('UnusedMsg')).toBe(false);
const gen = generateCode(used.registry);
expect(gen).toContain('protobuf_encode_UsedMsg');
expect(gen).toContain('protobuf_encode_Inner');
expect(gen).not.toContain('protobuf_encode_UnusedMsg');
});
it('emits runtime map asset when runtimeMap is enabled', () => {
const code = `
import { protobuf_encode } from '@snowluma/proton';
interface Msg { id: pb<1, uint_32>; }
const buf = protobuf_encode<Msg>({ id: 1 });
`;
const plugin = protobufVitePlugin({
runtimeMap: {
enabled: true,
fileName: 'pb.runtime-map.json',
},
});
const transformHook = plugin.transform!;
const transform =
typeof transformHook === 'function' ? transformHook : transformHook.handler;
const transformResult = transform.call({} as any, code, 'entry.ts');
expect(transformResult).toBeTruthy();
const emitted: any[] = [];
const generateHook = plugin.generateBundle!;
const generateBundle =
typeof generateHook === 'function' ? generateHook : generateHook.handler;
const testContext: any = {
emitFile(asset: any) {
emitted.push(asset);
return 'asset-id';
},
};
generateBundle.call(testContext, {} as any, {} as any, false);
expect(emitted).toHaveLength(1);
expect(emitted[0].type).toBe('asset');
expect(emitted[0].fileName).toBe('pb.runtime-map.json');
const payload = JSON.parse(emitted[0].source);
expect(payload.version).toBe(1);
expect(payload.callSites).toHaveLength(1);
expect(payload.callSites[0].fnName).toBe('protobuf_encode');
expect(payload.callSites[0].typeName).toBe('Msg');
});
it('emits canonical runtime map entries for imported type aliases', () => {
const code = `
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import type { UserMsg as AliasMsg } from './types';
const buf = protobuf_encode<AliasMsg>({ id: 1, name: 'a' });
const decoded = protobuf_decode<AliasMsg>(buf);
`;
const plugin = protobufVitePlugin({
runtimeMap: {
enabled: true,
fileName: 'pb.runtime-map.json',
},
});
const transformHook = plugin.transform!;
const transform =
typeof transformHook === 'function' ? transformHook : transformHook.handler;
const transformResult = transform.call(
{} as any,
code,
'test/fixtures/cross-file/aliased-consumer.ts',
);
expect(transformResult).toBeTruthy();
const emitted: any[] = [];
const generateHook = plugin.generateBundle!;
const generateBundle =
typeof generateHook === 'function' ? generateHook : generateHook.handler;
const testContext: any = {
emitFile(asset: any) {
emitted.push(asset);
return 'asset-id';
},
};
generateBundle.call(testContext, {} as any, {} as any, false);
expect(emitted).toHaveLength(1);
const payload = JSON.parse(emitted[0].source);
expect(payload.messages.some((msg: { name: string }) => msg.name === 'UserMsg')).toBe(true);
expect(payload.messages.some((msg: { name: string }) => msg.name === 'AliasMsg')).toBe(
false,
);
expect(payload.callSites).toHaveLength(2);
expect(payload.callSites[0].typeName).toBe('UserMsg');
expect(payload.callSites[1].typeName).toBe('UserMsg');
});
});
@@ -1,104 +0,0 @@
import { describe, it, expect } from 'vitest';
import { analyzeSource } from '../../src/ast/analyzer';
import { replaceCallSites } from '../../src/transform/replacer';
import { loadFixture } from '../helpers';
describe('call-site replacer', () => {
it('replaces protobuf_encode<T> with protobuf_encode_T', () => {
const code =
loadFixture('simple.ts') + `\nconst data = protobuf_encode<SimpleMsg>({ value: 1 });\n`;
const registry = analyzeSource(code, 't.ts');
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_SimpleMsg({ value: 1 })');
expect(transformedCode).not.toContain('protobuf_encode<SimpleMsg>');
});
it('replaces protobuf_decode<T>', () => {
const code =
loadFixture('simple.ts') + `\nconst result = protobuf_decode<SimpleMsg>(data);\n`;
const registry = analyzeSource(code, 't.ts');
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_decode_SimpleMsg(data)');
});
it('replaces multiple calls', () => {
const code =
loadFixture('simple.ts') +
`
const a = protobuf_encode<SimpleMsg>({ value: 1 });
const b = protobuf_decode<SimpleMsg>(a);
`;
const registry = analyzeSource(code, 't.ts');
const { transformedCode } = replaceCallSites(code, registry);
expect(transformedCode).toContain('protobuf_encode_SimpleMsg({ value: 1 })');
expect(transformedCode).toContain('protobuf_decode_SimpleMsg(a)');
});
it('preserves await keyword', () => {
const code =
loadFixture('simple.ts') +
`\nconst a = await protobuf_encode<SimpleMsg>({ value: 1 });\n`;
const registry = analyzeSource(code, 't.ts');
const { transformedCode } = replaceCallSites(code, registry);
expect(transformedCode).toContain('await protobuf_encode_SimpleMsg({ value: 1 })');
});
it('returns hasReplacements=false when no calls match', () => {
const code = loadFixture('simple.ts') + `\nconst x = 123;\n`;
const registry = analyzeSource(code, 't.ts');
expect(replaceCallSites(code, registry).hasReplacements).toBe(false);
});
it('does not replace unknown type arguments', () => {
const code = loadFixture('simple.ts') + `\nconst a = protobuf_encode<Unknown>({ v: 1 });\n`;
const registry = analyzeSource(code, 't.ts');
const { hasReplacements, transformedCode } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(false);
expect(transformedCode).toContain('protobuf_encode<Unknown>');
});
it('replaces generic call-sites with mangled names', () => {
const code = loadFixture('generic-usage.ts');
const registry = analyzeSource(code, 't.ts');
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain(
'protobuf_encode_TestProtobufAny__TestProtobufAny__string',
);
expect(transformedCode).toContain(
'protobuf_decode_TestProtobufAny__TestProtobufAny__string',
);
});
it('replaces namespace import calls', () => {
const code = `
import * as pbx from '@snowluma/proton';
interface Msg { id: pb<1, uint_32>; }
const a = pbx.protobuf_encode<Msg>({ id: 1 });
const b = pbx.protobuf_decode<Msg>(a);
`;
const registry = analyzeSource(code, 'ns.ts');
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('const a = protobuf_encode_Msg({ id: 1 });');
expect(transformedCode).toContain('const b = protobuf_decode_Msg(a);');
});
it('does not replace same-name imports from non-runtime modules', () => {
const code = `
import { protobuf_encode } from './other';
interface Msg { id: pb<1, uint_32>; }
const a = protobuf_encode<Msg>({ id: 1 });
`;
const registry = analyzeSource(code, 'guard.ts');
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(false);
expect(transformedCode).toContain('protobuf_encode<Msg>({ id: 1 })');
});
});
@@ -1,113 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest';
import { analyzeSource } from '../../src/ast/analyzer';
import { createRuntimeMap } from '../../src/runtime-map';
import {
protobuf_decode,
protobuf_disableRuntimeMapFallback,
protobuf_enableRuntimeMapFallback,
protobuf_encode,
} from '../../src/runtime';
function captureFrameFromThrow(
fn: () => unknown,
sourceFile: string,
): { line: number; column: number } {
try {
fn();
} catch (err) {
const stack = err instanceof Error ? (err.stack ?? '') : '';
for (const raw of stack.split('\n')) {
const line = raw.trim();
if (!line.includes(sourceFile)) {
continue;
}
const location =
line.endsWith(')') && line.includes('(')
? line.slice(line.lastIndexOf('(') + 1, -1)
: line.replace(/^at\s+/, '');
const lastColon = location.lastIndexOf(':');
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
if (lastColon < 0 || secondLastColon < 0) {
continue;
}
const parsedLine = Number(location.slice(secondLastColon + 1, lastColon));
const parsedColumn = Number(location.slice(lastColon + 1));
if (Number.isFinite(parsedLine) && Number.isFinite(parsedColumn)) {
return { line: parsedLine, column: parsedColumn };
}
}
}
throw new Error(`Unable to capture stack frame for ${sourceFile}`);
}
function invokeEncode(): Uint8Array {
return new Function(
'protobuf_encode',
`\n//# sourceURL=runtime-map-encode.js\nreturn protobuf_encode({ value: 7 });`,
)(protobuf_encode) as Uint8Array;
}
function invokeDecode(data: Uint8Array): any {
return new Function(
'protobuf_decode',
'data',
`\n//# sourceURL=runtime-map-decode.js\nreturn protobuf_decode(data);`,
)(protobuf_decode, data);
}
describe('runtime map fallback', () => {
afterEach(() => {
protobuf_disableRuntimeMapFallback();
});
it('dynamically generates encode/decode from runtime map when enabled', () => {
const schema = `
interface SimpleMsg {
value: pb<1, uint_32>;
}
`;
const registry = analyzeSource(schema, 'schema.ts');
const encodeFrame = captureFrameFromThrow(invokeEncode, 'runtime-map-encode.js');
const decodeFrame = captureFrameFromThrow(
() => invokeDecode(new Uint8Array([0x08, 0x07])),
'runtime-map-decode.js',
);
const runtimeMap = createRuntimeMap({
messages: registry,
callSites: [
{
file: 'runtime-map-encode.js',
line: encodeFrame.line,
column: encodeFrame.column,
fnName: 'protobuf_encode',
typeName: 'SimpleMsg',
},
{
file: 'runtime-map-decode.js',
line: decodeFrame.line,
column: decodeFrame.column,
fnName: 'protobuf_decode',
typeName: 'SimpleMsg',
},
],
});
protobuf_enableRuntimeMapFallback(runtimeMap);
const encoded = invokeEncode();
expect([...encoded]).toEqual([0x08, 0x07]);
const decoded = invokeDecode(encoded);
expect(decoded.value).toBe(7);
});
});