This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

+151 -127
View File
@@ -4,142 +4,166 @@ 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,
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,
});
});
const wrapper = registry.get('Wrapper__uint_32')!;
expect(wrapper.fields[0]).toMatchObject({
name: 'value',
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('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 = `
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(() => analyzeSource(source, 'b.ts')).toThrow(/MissingType/);
});
expect(aliased.fields[1]).toMatchObject({
name: 'tags',
fieldNumber: 2,
typeName: 'string',
isRepeated: true,
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,
});
});
});
});
+301 -241
View File
@@ -11,332 +11,392 @@ 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 };
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 ──────────
// ── 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);
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);
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 { 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');
});
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);
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 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');
});
`,
'__r',
);
expect(result.id).toBe(42);
expect(result.name).toBe('alice');
});
// ── Scenario B: imported type as pb<> field ──────────────────────
// ── 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);
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);
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 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);
});
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);
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 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);
});
`,
'__r',
);
expect(result.inner.value).toBe(42);
});
// ── Generic template import ──────────────────────────────────────
// ── 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);
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);
expect(imported.templates.has('Wrapper')).toBe(true);
const registry = analyzeSource(code, path, imported);
expect(registry.has('Wrapper__string')).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);
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 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');
});
`,
'__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);
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);
expect(imported.templates.has('Wrapper')).toBe(true);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile);
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');
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(');
});
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);
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);
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);
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>>');
});
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);
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);
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.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(');
});
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);
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);
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);
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>>');
});
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);
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);
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);
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>');
});
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 ───────────────────────────────────────────
// ── 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);
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);
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);
});
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);
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 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);
});
`,
'__r',
);
expect(result.nested.inner.val).toBe(99);
});
// ── Cache behavior ───────────────────────────────────────────────
// ── Cache behavior ───────────────────────────────────────────────
it('uses cache on repeated resolves', () => {
const { code, path } = loadCross('consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
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);
resolveImports(code, path, cache);
expect(cache.size).toBeGreaterThan(0);
const cached = new Map(cache);
resolveImports(code, path, cache);
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));
}
});
// Same entries, not re-created
for (const [key, val] of cache) {
expect(val).toBe(cached.get(key));
}
});
// ── Graceful fallback ────────────────────────────────────────────
// ── 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>();
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);
});
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 = `
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 fakePath = resolve(crossDir, 'on-demand.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, fakePath, cache);
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);
});
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) ───────────────────────────────
// ── 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);
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);
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 { 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(');
});
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);
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 result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_SimpleMessage({ id: 42 });
globalThis.__r = protobuf_decode_SimpleMessage(enc);
`, '__r');
expect(result.id).toBe(42);
});
`,
'__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);
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);
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');
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(');
});
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(');
});
});
@@ -30,147 +30,159 @@ import { resolveImports, type ParsedFileEntry } from '../../src/ast/import-resol
import { execAndGet } from '../helpers';
describe('cross-package import resolution (bare specifier)', () => {
let tmpRoot: string;
let consumerPath: string;
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-'));
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 });
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),
);
// `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',
);
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',
);
});
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 });
});
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);
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);
});
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);
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 { 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');
});
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);
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');
});
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([]);
});
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([]);
});
});
+258 -251
View File
@@ -6,108 +6,120 @@ import { loadFixture } from '../helpers';
/** Analyze fixture → generate → eval → return encode/decode pair */
function makeRoundTrip(fixtureName: string, msgName: string) {
const gen = generateCode(analyzeSource(loadFixture(fixtureName), fixtureName));
new Function(gen + `\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`)();
const enc = (globalThis as any).__enc as (obj: any) => Uint8Array;
const dec = (globalThis as any).__dec as (data: Uint8Array) => any;
delete (globalThis as any).__enc;
delete (globalThis as any).__dec;
return { enc, dec };
const gen = generateCode(analyzeSource(loadFixture(fixtureName), fixtureName));
new Function(
gen +
`\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`,
)();
const enc = (globalThis as any).__enc as (obj: any) => Uint8Array;
const dec = (globalThis as any).__dec as (data: Uint8Array) => any;
delete (globalThis as any).__enc;
delete (globalThis as any).__dec;
return { enc, dec };
}
function makeRoundTripFromSchema(schema: string, msgName: string) {
const gen = generateCode(analyzeSource(schema, `${msgName}.ts`));
new Function(gen + `\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`)();
const enc = (globalThis as any).__enc as (obj: any) => Uint8Array;
const dec = (globalThis as any).__dec as (data: Uint8Array) => any;
delete (globalThis as any).__enc;
delete (globalThis as any).__dec;
return { enc, dec };
const gen = generateCode(analyzeSource(schema, `${msgName}.ts`));
new Function(
gen +
`\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`,
)();
const enc = (globalThis as any).__enc as (obj: any) => Uint8Array;
const dec = (globalThis as any).__dec as (data: Uint8Array) => any;
delete (globalThis as any).__enc;
delete (globalThis as any).__dec;
return { enc, dec };
}
function encodeVarint32(value: number): number[] {
const bytes: number[] = [];
let remaining = value >>> 0;
do {
let byte = remaining & 0x7f;
remaining >>>= 7;
if (remaining !== 0) byte |= 0x80;
bytes.push(byte);
} while (remaining !== 0);
return bytes;
const bytes: number[] = [];
let remaining = value >>> 0;
do {
let byte = remaining & 0x7f;
remaining >>>= 7;
if (remaining !== 0) {
byte |= 0x80;
}
bytes.push(byte);
} while (remaining !== 0);
return bytes;
}
describe('code generator', () => {
it('generates encode/decode for simple uint_32', () => {
const gen = generateCode(analyzeSource(loadFixture('simple.ts'), 't.ts'));
expect(gen).toContain('function protobuf_encode_SimpleMsg(obj)');
expect(gen).toContain('function protobuf_decode_SimpleMsg(data');
// Tag for field 1, varint should be pre-computed as 0x08
expect(gen).toContain('buf[offset++] = 8;');
});
it('generates encode/decode for simple uint_32', () => {
const gen = generateCode(analyzeSource(loadFixture('simple.ts'), 't.ts'));
expect(gen).toContain('function protobuf_encode_SimpleMsg(obj)');
expect(gen).toContain('function protobuf_decode_SimpleMsg(data');
// Tag for field 1, varint should be pre-computed as 0x08
expect(gen).toContain('buf[offset++] = 8;');
});
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)');
});
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)');
});
it('round-trip uint_32', () => {
const { enc, dec } = makeRoundTrip('simple.ts', 'SimpleMsg');
expect(dec(enc({ value: 42 })).value).toBe(42);
});
it('round-trip uint_32', () => {
const { enc, dec } = makeRoundTrip('simple.ts', 'SimpleMsg');
expect(dec(enc({ value: 42 })).value).toBe(42);
});
it('round-trip nested message', () => {
const { enc, dec } = makeRoundTrip('nested.ts', 'Outer');
expect(dec(enc({ inner: { value: 999 } })).inner.value).toBe(999);
});
it('round-trip nested message', () => {
const { enc, dec } = makeRoundTrip('nested.ts', 'Outer');
expect(dec(enc({ inner: { value: 999 } })).inner.value).toBe(999);
});
it('round-trip string', () => {
const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg');
expect(dec(enc({ text: 'hello world' })).text).toBe('hello world');
});
it('round-trip string', () => {
const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg');
expect(dec(enc({ text: 'hello world' })).text).toBe('hello world');
});
it('round-trip unicode string', () => {
const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg');
expect(dec(enc({ text: '你好,protobuf🚀' })).text).toBe('你好,protobuf🚀');
});
it('round-trip unicode string', () => {
const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg');
expect(dec(enc({ text: '你好,protobuf🚀' })).text).toBe('你好,protobuf🚀');
});
it('round-trip bool', () => {
const { enc, dec } = makeRoundTrip('bool-msg.ts', 'BoolMsg');
expect(dec(enc({ active: true })).active).toBe(true);
const empty = enc({ active: false });
expect(empty.length).toBe(0);
expect(dec(empty).active).toBe(false);
});
it('round-trip bool', () => {
const { enc, dec } = makeRoundTrip('bool-msg.ts', 'BoolMsg');
expect(dec(enc({ active: true })).active).toBe(true);
const empty = enc({ active: false });
expect(empty.length).toBe(0);
expect(dec(empty).active).toBe(false);
});
it('proto3 default encoding (0 → empty)', () => {
const { enc } = makeRoundTrip('simple.ts', 'SimpleMsg');
expect(enc({ value: 0 }).length).toBe(0);
});
it('proto3 default encoding (0 → empty)', () => {
const { enc } = makeRoundTrip('simple.ts', 'SimpleMsg');
expect(enc({ value: 0 }).length).toBe(0);
});
it('round-trip repeated uint_32', () => {
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
const result = dec(enc({ ids: [10, 20, 30], names: [] }));
expect(result.ids).toEqual([10, 20, 30]);
expect(result.names).toEqual([]);
});
it('round-trip repeated uint_32', () => {
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
const result = dec(enc({ ids: [10, 20, 30], names: [] }));
expect(result.ids).toEqual([10, 20, 30]);
expect(result.names).toEqual([]);
});
it('round-trip repeated string', () => {
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
const result = dec(enc({ ids: [], names: ['hello', 'world'] }));
expect(result.ids).toEqual([]);
expect(result.names).toEqual(['hello', 'world']);
});
it('round-trip repeated string', () => {
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
const result = dec(enc({ ids: [], names: ['hello', 'world'] }));
expect(result.ids).toEqual([]);
expect(result.names).toEqual(['hello', 'world']);
});
it('repeated empty arrays round-trip', () => {
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
const result = dec(enc({ ids: [], names: [] }));
expect(result.ids).toEqual([]);
expect(result.names).toEqual([]);
});
it('repeated empty arrays round-trip', () => {
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
const result = dec(enc({ ids: [], names: [] }));
expect(result.ids).toEqual([]);
expect(result.names).toEqual([]);
});
it('round-trip bigint-backed 64-bit integers', () => {
const schema = `
it('round-trip bigint-backed 64-bit integers', () => {
const schema = `
interface BigIntMsg {
unsigned: pb<1, uint_64>;
signed: pb<2, int_64>;
@@ -116,210 +128,205 @@ interface BigIntMsg {
sfixed: pb<5, sfixed_64>;
ids: pb_repeated<6, uint_64>;
}`;
const { enc, dec } = makeRoundTripFromSchema(schema, 'BigIntMsg');
const input = {
unsigned: 18446744073709551615n,
signed: -1n,
zigzag: -1234567890123456789n,
fixed: 0x0102030405060708n,
sfixed: -0x0102030405060708n,
ids: [1n, 2n, 9007199254740993n],
};
expect(dec(enc(input))).toEqual(input);
});
const { enc, dec } = makeRoundTripFromSchema(schema, 'BigIntMsg');
const input = {
unsigned: 18446744073709551615n,
signed: -1n,
zigzag: -1234567890123456789n,
fixed: 0x0102030405060708n,
sfixed: -0x0102030405060708n,
ids: [1n, 2n, 9007199254740993n],
};
expect(dec(enc(input))).toEqual(input);
});
it('round-trip sint_32 with negative values', () => {
const schema = `
it('round-trip sint_32 with negative values', () => {
const schema = `
interface Sint32Msg {
value: pb<1, sint_32>;
values: pb_repeated<2, sint_32>;
}`;
const { enc, dec } = makeRoundTripFromSchema(schema, 'Sint32Msg');
const input = { value: -789, values: [-1, 0, 1, -789, 2147483647, -2147483648] };
expect(dec(enc(input))).toEqual(input);
});
const { enc, dec } = makeRoundTripFromSchema(schema, 'Sint32Msg');
const input = { value: -789, values: [-1, 0, 1, -789, 2147483647, -2147483648] };
expect(dec(enc(input))).toEqual(input);
});
it('preserves legacy outbound int_32 bytes while accepting canonical negative varints', () => {
const schema = `
it('preserves legacy outbound int_32 bytes while accepting canonical negative varints', () => {
const schema = `
interface Int32Msg {
value: pb<1, int_32>;
values: pb_repeated<2, int_32>;
forced: pb_optional<3, int_32>;
}`;
const { enc, dec } = makeRoundTripFromSchema(schema, 'Int32Msg');
const input = {
value: -1,
values: [-2147483648, -1, 0, 1, 2147483647],
forced: -2147483648,
};
const encoded = enc(input);
const { enc, dec } = makeRoundTripFromSchema(schema, 'Int32Msg');
const input = {
value: -1,
values: [-2147483648, -1, 0, 1, 2147483647],
forced: -2147483648,
};
const encoded = enc(input);
// Keep SnowLuma's established five-byte negative int32 encoding on the
// outbound path until QQ interoperability is verified on a live account.
// The decoder remains liberal and accepts protobuf's canonical ten-byte
// negative form below.
expect(Array.from(encoded.slice(0, 6))).toEqual([
0x08,
0xff, 0xff, 0xff, 0xff, 0x0f,
]);
expect(dec(encoded)).toEqual(input);
expect(dec(Uint8Array.from([
0x08,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01,
])).value).toBe(-1);
});
// Keep SnowLuma's established five-byte negative int32 encoding on the
// outbound path until QQ interoperability is verified on a live account.
// The decoder remains liberal and accepts protobuf's canonical ten-byte
// negative form below.
expect(Array.from(encoded.slice(0, 6))).toEqual([0x08, 0xff, 0xff, 0xff, 0xff, 0x0f]);
expect(dec(encoded)).toEqual(input);
expect(
dec(Uint8Array.from([0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]))
.value,
).toBe(-1);
});
it('retains the low 32 bits of extended uint_32 field varints', () => {
const { dec } = makeRoundTripFromSchema(
`interface Uint32Msg { value: pb<1, uint_32>; }`,
'Uint32Msg',
);
it('retains the low 32 bits of extended uint_32 field varints', () => {
const { dec } = makeRoundTripFromSchema(
`interface Uint32Msg { value: pb<1, uint_32>; }`,
'Uint32Msg',
);
// QQ sometimes serializes a signed 32-bit source into a schema slot that
// clients expose as uint32. Protobuf readers consume the full ten-byte
// varint and retain its low 32 bits for wire compatibility.
expect(dec(Uint8Array.from([
0x08,
0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01,
])).value).toBe(0xfffffffe);
// QQ sometimes serializes a signed 32-bit source into a schema slot that
// clients expose as uint32. Protobuf readers consume the full ten-byte
// varint and retain its low 32 bits for wire compatibility.
expect(
dec(Uint8Array.from([0x08, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]))
.value,
).toBe(0xfffffffe);
// QQ-compatible uint32 readers consume up to a full 64-bit varint and
// retain its low 32 bits. Some push-envelope sequences use that wire
// representation, so values with non-zero high bits must remain decodable.
expect(dec(Uint8Array.from([
0x08,
0x80, 0x80, 0x80, 0x80, 0x10,
])).value).toBe(0);
expect(dec(Uint8Array.from([
0x08,
0x87, 0x80, 0x80, 0x80, 0x10,
])).value).toBe(7);
// QQ-compatible uint32 readers consume up to a full 64-bit varint and
// retain its low 32 bits. Some push-envelope sequences use that wire
// representation, so values with non-zero high bits must remain decodable.
expect(dec(Uint8Array.from([0x08, 0x80, 0x80, 0x80, 0x80, 0x10])).value).toBe(0);
expect(dec(Uint8Array.from([0x08, 0x87, 0x80, 0x80, 0x80, 0x10])).value).toBe(7);
// 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, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02,
]))).toThrow(/uint64 varint overflow/);
});
// 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, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02]),
),
).toThrow(/uint64 varint overflow/);
});
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');
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, 0x80, 0x80, 0x80, 0x10]))).toThrow(/uint32 varint overflow/);
});
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, 0x80, 0x80, 0x80, 0x10]))).toThrow(
/uint32 varint overflow/,
);
});
it('skips unknown groups without decoding their fields into the parent', () => {
const schema = `
it('skips unknown groups without decoding their fields into the parent', () => {
const schema = `
interface Text { str: pb<1, string>; }
interface Elem { text: pb<1, Text>; }
`;
const { dec } = makeRoundTripFromSchema(schema, 'Elem');
const decoded = dec(Uint8Array.from([
0x7b,
0x0a, 0x08, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x67, 0x65, 0x64,
0x7c,
]));
const { dec } = makeRoundTripFromSchema(schema, 'Elem');
const decoded = dec(
Uint8Array.from([
0x7b, 0x0a, 0x08, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x67, 0x65, 0x64, 0x7c,
]),
);
expect(decoded.text).toBeNull();
expect(protobuf_getUnknownFieldMetadata(decoded).fields).toMatchObject([
{ fieldNumber: 15, wireType: 3 },
]);
});
it('aggregates repeated unknown fields instead of retaining every occurrence', () => {
const { dec } = makeRoundTripFromSchema(
`interface UnknownMsg { known: pb<1, uint_32>; }`,
'UnknownMsg',
);
const wire: number[] = [];
const tag = encodeVarint32((60 << 3) | 0);
for (let index = 0; index < 1_000; index++) wire.push(...tag, 0);
const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire)));
expect(metadata).toEqual({
fields: [{ fieldNumber: 60, wireType: 0, count: 1_000, totalByteLength: 1_000 }],
totalOccurrences: 1_000,
omittedOccurrences: 0,
omittedByteLength: 0,
expect(decoded.text).toBeNull();
expect(protobuf_getUnknownFieldMetadata(decoded).fields).toMatchObject([
{ fieldNumber: 15, wireType: 3 },
]);
});
});
it('caps retained unknown field kinds and summarizes overflow', () => {
const { dec } = makeRoundTripFromSchema(
`interface UnknownKindsMsg { known: pb<1, uint_32>; }`,
'UnknownKindsMsg',
);
const wire: number[] = [];
for (let fieldNumber = 2; fieldNumber <= 66; fieldNumber++) {
wire.push(...encodeVarint32((fieldNumber << 3) | 0), 0);
}
it('aggregates repeated unknown fields instead of retaining every occurrence', () => {
const { dec } = makeRoundTripFromSchema(
`interface UnknownMsg { known: pb<1, uint_32>; }`,
'UnknownMsg',
);
const wire: number[] = [];
const tag = encodeVarint32((60 << 3) | 0);
const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire)));
expect(metadata.fields).toHaveLength(64);
expect(metadata.totalOccurrences).toBe(65);
expect(metadata.omittedOccurrences).toBe(1);
expect(metadata.omittedByteLength).toBe(1);
});
for (let index = 0; index < 1_000; index++) {
wire.push(...tag, 0);
}
it('round-trip double as ieee754 number', () => {
const schema = `
const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire)));
expect(metadata).toEqual({
fields: [{ fieldNumber: 60, wireType: 0, count: 1_000, totalByteLength: 1_000 }],
totalOccurrences: 1_000,
omittedOccurrences: 0,
omittedByteLength: 0,
});
});
it('caps retained unknown field kinds and summarizes overflow', () => {
const { dec } = makeRoundTripFromSchema(
`interface UnknownKindsMsg { known: pb<1, uint_32>; }`,
'UnknownKindsMsg',
);
const wire: number[] = [];
for (let fieldNumber = 2; fieldNumber <= 66; fieldNumber++) {
wire.push(...encodeVarint32((fieldNumber << 3) | 0), 0);
}
const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire)));
expect(metadata.fields).toHaveLength(64);
expect(metadata.totalOccurrences).toBe(65);
expect(metadata.omittedOccurrences).toBe(1);
expect(metadata.omittedByteLength).toBe(1);
});
it('round-trip double as ieee754 number', () => {
const schema = `
interface DoubleMsg {
value: pb<1, double>;
values: pb_repeated<2, double>;
}`;
const { enc, dec } = makeRoundTripFromSchema(schema, 'DoubleMsg');
const result = dec(enc({ value: Math.PI, values: [Math.E, -0.5] }));
expect(result.value).toBeCloseTo(Math.PI);
expect(result.values[0]).toBeCloseTo(Math.E);
expect(result.values[1]).toBeCloseTo(-0.5);
});
const { enc, dec } = makeRoundTripFromSchema(schema, 'DoubleMsg');
const result = dec(enc({ value: Math.PI, values: [Math.E, -0.5] }));
expect(result.value).toBeCloseTo(Math.PI);
expect(result.values[0]).toBeCloseTo(Math.E);
expect(result.values[1]).toBeCloseTo(-0.5);
});
});
describe('pb_optional explicit presence', () => {
it('serialises a zero scalar (where pb<> would omit it)', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface OptMsg { forced: pb_optional<1, uint_32>; }`,
'OptMsg',
);
// field 1, varint, value 0 → tag 0x08 then payload 0x00 (NOT empty).
expect(Array.from(enc({ forced: 0 }))).toEqual([0x08, 0x00]);
expect(dec(enc({ forced: 0 })).forced).toBe(0);
});
it('serialises a zero scalar (where pb<> would omit it)', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface OptMsg { forced: pb_optional<1, uint_32>; }`,
'OptMsg',
);
// field 1, varint, value 0 → tag 0x08 then payload 0x00 (NOT empty).
expect(Array.from(enc({ forced: 0 }))).toEqual([0x08, 0x00]);
expect(dec(enc({ forced: 0 })).forced).toBe(0);
});
it('still omits the field when the value is absent (undefined)', () => {
const { enc } = makeRoundTripFromSchema(
`interface OptMsg2 { forced: pb_optional<1, uint_32>; }`,
'OptMsg2',
);
expect(enc({}).length).toBe(0);
});
it('still omits the field when the value is absent (undefined)', () => {
const { enc } = makeRoundTripFromSchema(
`interface OptMsg2 { forced: pb_optional<1, uint_32>; }`,
'OptMsg2',
);
expect(enc({}).length).toBe(0);
});
it('does not change a sibling plain pb<> field (it still omits its zero)', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface MixMsg { plain: pb<1, uint_32>; forced: pb_optional<2, uint_32>; }`,
'MixMsg',
);
// plain=0 omitted (unchanged); only forced=0 is emitted (field 2 → tag 0x10).
expect(Array.from(enc({ plain: 0, forced: 0 }))).toEqual([0x10, 0x00]);
expect(dec(enc({ plain: 7, forced: 9 }))).toEqual({ plain: 7, forced: 9 });
});
it('does not change a sibling plain pb<> field (it still omits its zero)', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface MixMsg { plain: pb<1, uint_32>; forced: pb_optional<2, uint_32>; }`,
'MixMsg',
);
// plain=0 omitted (unchanged); only forced=0 is emitted (field 2 → tag 0x10).
expect(Array.from(enc({ plain: 0, forced: 0 }))).toEqual([0x10, 0x00]);
expect(dec(enc({ plain: 7, forced: 9 }))).toEqual({ plain: 7, forced: 9 });
});
it('forces a false bool onto the wire', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface BoolOpt { flag: pb_optional<1, bool>; }`,
'BoolOpt',
);
expect(Array.from(enc({ flag: false }))).toEqual([0x08, 0x00]);
expect(dec(enc({ flag: false })).flag).toBe(false);
expect(Array.from(enc({ flag: true }))).toEqual([0x08, 0x01]);
});
it('forces a false bool onto the wire', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface BoolOpt { flag: pb_optional<1, bool>; }`,
'BoolOpt',
);
expect(Array.from(enc({ flag: false }))).toEqual([0x08, 0x00]);
expect(dec(enc({ flag: false })).flag).toBe(false);
expect(Array.from(enc({ flag: true }))).toEqual([0x08, 0x01]);
});
});
+246 -205
View File
@@ -6,107 +6,135 @@ 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']);
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 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)');
});
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
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);
});
`,
'__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
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);
});
`,
'__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
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);
});
`,
'__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
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);
});
`,
'__r',
);
expect(result.id).toBe(42);
expect(result.username).toBe('alice');
expect(result.active).toBe(true);
});
// ── generic monomorphization ───────────────────────────────────────
// ── 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 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
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');
});
`,
'__r',
);
expect(result.name.name).toBe('hello');
});
// ── repeated fields ────────────────────────────────────────────────
// ── repeated fields ────────────────────────────────────────────────
it('repeated fields round-trip', () => {
const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts'));
const result = execAndGet<any>(gen + `\n
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']);
});
`,
'__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
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([]);
});
`,
'__r',
);
expect(result.ids).toEqual([]);
expect(result.names).toEqual([]);
});
// ── import-based usage ──────────────────────────────────────────────
// ── import-based usage ──────────────────────────────────────────────
it('handles code with import { protobuf_encode } from "@snowluma/proton"', () => {
const code = `
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>; }
@@ -114,19 +142,19 @@ 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 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'");
});
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 = `
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>; }
@@ -134,26 +162,30 @@ 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 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');
});
`,
'__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');
});
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 ─────────────────────────────────────────────
// ── import rename alias ─────────────────────────────────────────────
it('handles import { protobuf_encode as encode }', () => {
const code = `
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>; }
@@ -161,38 +193,42 @@ 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 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>');
});
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 = `
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 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');
});
`,
'__r',
);
expect(result.val).toBe(99);
expect(result.name).toBe('x');
});
it('collects call roots first and generates only used dependency closure', () => {
const code = `
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>; }
@@ -202,69 +238,66 @@ 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);
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);
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');
});
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 = `
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 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');
});
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 = `
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';
@@ -272,36 +305,44 @@ 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 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');
});
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');
});
});
+73 -63
View File
@@ -4,66 +4,76 @@ 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_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 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') + `
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)');
});
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('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('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('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 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 = `
it('replaces namespace import calls', () => {
const code = `
import * as pbx from '@snowluma/proton';
interface Msg { id: pb<1, uint_32>; }
@@ -71,24 +81,24 @@ 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);');
});
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 = `
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 })');
});
const registry = analyzeSource(code, 'guard.ts');
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(false);
expect(transformedCode).toContain('protobuf_encode<Msg>({ id: 1 })');
});
});
@@ -2,97 +2,112 @@ 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,
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;
function captureFrameFromThrow(
fn: () => unknown,
sourceFile: string,
): { line: number; column: number } {
try {
fn();
} catch (err) {
const stack = err instanceof Error ? (err.stack ?? '') : '';
const location = line.endsWith(')') && line.includes('(')
? line.slice(line.lastIndexOf('(') + 1, -1)
: line.replace(/^at\s+/, '');
for (const raw of stack.split('\n')) {
const line = raw.trim();
const lastColon = location.lastIndexOf(':');
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
if (lastColon < 0 || secondLastColon < 0) continue;
if (!line.includes(sourceFile)) {
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 };
}
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}`);
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;
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);
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();
});
afterEach(() => {
protobuf_disableRuntimeMapFallback();
});
it('dynamically generates encode/decode from runtime map when enabled', () => {
const schema = `
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 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 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',
},
],
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);
});
protobuf_enableRuntimeMapFallback(runtimeMap);
const encoded = invokeEncode();
expect([...encoded]).toEqual([0x08, 0x07]);
const decoded = invokeDecode(encoded);
expect(decoded.value).toBe(7);
});
});
+101 -94
View File
@@ -1,110 +1,117 @@
import { describe, it, expect } from 'vitest';
import { encodeVarint, decodeVarint, writeTag, writeString, readString, skipField } from '../../src/codegen/wire';
import {
encodeVarint,
decodeVarint,
writeTag,
writeString,
readString,
skipField,
} from '../../src/codegen/wire';
describe('wire format primitives', () => {
describe('varint', () => {
const cases: [number, number[]][] = [
[0, [0x00]],
[1, [0x01]],
[127, [0x7f]],
[128, [0x80, 0x01]],
[300, [0xac, 0x02]],
[16384, [0x80, 0x80, 0x01]],
];
describe('varint', () => {
const cases: [number, number[]][] = [
[0, [0x00]],
[1, [0x01]],
[127, [0x7f]],
[128, [0x80, 0x01]],
[300, [0xac, 0x02]],
[16384, [0x80, 0x80, 0x01]],
];
it.each(cases)('encodeVarint(%i) produces correct bytes', (value, expected) => {
const buf: number[] = [];
encodeVarint(value, buf);
expect(buf).toEqual(expected);
it.each(cases)('encodeVarint(%i) produces correct bytes', (value, expected) => {
const buf: number[] = [];
encodeVarint(value, buf);
expect(buf).toEqual(expected);
});
it.each(cases)('decodeVarint round-trip for %i', (value) => {
const buf: number[] = [];
encodeVarint(value, buf);
const data = new Uint8Array(buf);
const [decoded, offset] = decodeVarint(data, 0);
expect(decoded).toBe(value);
expect(offset).toBe(buf.length);
});
it('handles max uint32', () => {
const value = 0xffffffff;
const buf: number[] = [];
encodeVarint(value, buf);
const [decoded] = decodeVarint(new Uint8Array(buf), 0);
expect(decoded).toBe(value);
});
});
it.each(cases)('decodeVarint round-trip for %i', (value) => {
const buf: number[] = [];
encodeVarint(value, buf);
const data = new Uint8Array(buf);
const [decoded, offset] = decodeVarint(data, 0);
expect(decoded).toBe(value);
expect(offset).toBe(buf.length);
describe('tag encoding', () => {
it('field 1, varint (wire type 0) produces 0x08', () => {
const buf: number[] = [];
writeTag(1, 0, buf);
expect(buf).toEqual([0x08]);
});
it('field 1, length-delimited (wire type 2) produces 0x0A', () => {
const buf: number[] = [];
writeTag(1, 2, buf);
expect(buf).toEqual([0x0a]);
});
it('field 2, varint produces 0x10', () => {
const buf: number[] = [];
writeTag(2, 0, buf);
expect(buf).toEqual([0x10]);
});
});
it('handles max uint32', () => {
const value = 0xFFFFFFFF;
const buf: number[] = [];
encodeVarint(value, buf);
const [decoded] = decodeVarint(new Uint8Array(buf), 0);
expect(decoded).toBe(value);
});
});
describe('string encoding', () => {
it('encodes and decodes "hello"', () => {
const buf: number[] = [];
writeString('hello', buf);
const data = new Uint8Array(buf);
// First byte is length (5), followed by UTF-8 bytes
expect(data[0]).toBe(5);
const decoded = readString(data, 1, 5);
expect(decoded).toBe('hello');
});
describe('tag encoding', () => {
it('field 1, varint (wire type 0) produces 0x08', () => {
const buf: number[] = [];
writeTag(1, 0, buf);
expect(buf).toEqual([0x08]);
it('handles empty string', () => {
const buf: number[] = [];
writeString('', buf);
expect(buf).toEqual([0]); // length 0
});
it('handles unicode', () => {
const buf: number[] = [];
writeString('你好', buf);
const data = new Uint8Array(buf);
const [len, offset] = [data[0], 1];
const decoded = readString(data, offset, len);
expect(decoded).toBe('你好');
});
});
it('field 1, length-delimited (wire type 2) produces 0x0A', () => {
const buf: number[] = [];
writeTag(1, 2, buf);
expect(buf).toEqual([0x0a]);
});
describe('skipField', () => {
it('skips varint field', () => {
const buf: number[] = [];
encodeVarint(300, buf); // multi-byte varint
const data = new Uint8Array(buf);
const newOffset = skipField(data, 0, 0);
expect(newOffset).toBe(buf.length);
});
it('field 2, varint produces 0x10', () => {
const buf: number[] = [];
writeTag(2, 0, buf);
expect(buf).toEqual([0x10]);
});
});
it('skips length-delimited field', () => {
// length=3 followed by 3 bytes
const data = new Uint8Array([3, 0x41, 0x42, 0x43]);
const newOffset = skipField(data, 0, 2);
expect(newOffset).toBe(4);
});
describe('string encoding', () => {
it('encodes and decodes "hello"', () => {
const buf: number[] = [];
writeString('hello', buf);
const data = new Uint8Array(buf);
// First byte is length (5), followed by UTF-8 bytes
expect(data[0]).toBe(5);
const decoded = readString(data, 1, 5);
expect(decoded).toBe('hello');
});
it('skips 32-bit field', () => {
expect(skipField(new Uint8Array(4), 0, 5)).toBe(4);
});
it('handles empty string', () => {
const buf: number[] = [];
writeString('', buf);
expect(buf).toEqual([0]); // length 0
it('skips 64-bit field', () => {
expect(skipField(new Uint8Array(8), 0, 1)).toBe(8);
});
});
it('handles unicode', () => {
const buf: number[] = [];
writeString('你好', buf);
const data = new Uint8Array(buf);
const [len, offset] = [data[0], 1];
const decoded = readString(data, offset, len);
expect(decoded).toBe('你好');
});
});
describe('skipField', () => {
it('skips varint field', () => {
const buf: number[] = [];
encodeVarint(300, buf); // multi-byte varint
const data = new Uint8Array(buf);
const newOffset = skipField(data, 0, 0);
expect(newOffset).toBe(buf.length);
});
it('skips length-delimited field', () => {
// length=3 followed by 3 bytes
const data = new Uint8Array([3, 0x41, 0x42, 0x43]);
const newOffset = skipField(data, 0, 2);
expect(newOffset).toBe(4);
});
it('skips 32-bit field', () => {
expect(skipField(new Uint8Array(4), 0, 5)).toBe(4);
});
it('skips 64-bit field', () => {
expect(skipField(new Uint8Array(8), 0, 1)).toBe(8);
});
});
});
+5 -5
View File
@@ -6,7 +6,7 @@ const fixturesDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixt
/** Load a fixture file as a string. */
export function loadFixture(name: string): string {
return readFileSync(resolve(fixturesDir, name), 'utf-8');
return readFileSync(resolve(fixturesDir, name), 'utf-8');
}
/**
@@ -14,8 +14,8 @@ export function loadFixture(name: string): string {
* Cleans up the global after retrieval.
*/
export function execAndGet<T>(code: string, globalKey: string): T {
new Function(code)();
const val = (globalThis as any)[globalKey] as T;
delete (globalThis as any)[globalKey];
return val;
new Function(code)();
const val = (globalThis as any)[globalKey] as T;
delete (globalThis as any)[globalKey];
return val;
}