feat(proton): add @snowluma/proton — compile-time protobuf DSL

Vendors SnowLuma/protobuf-dsl into the monorepo as @snowluma/proton, with
edge-case fixes applied on top of the upstream source. Reference copy of
the unmodified upstream is kept under dev/protobuf-dsl/.

Edge cases fixed (each with a regression test):
  - Aliased pb / pb_repeated marker imports (`import { pb as P }`)
    — collector now resolves the marker name through the import resolver
  - Concrete interface with a generic-instantiated message field
    (`wrapped: pb<5, Wrapper<uint_32>>`) — field typeName now resolves
    to the mangled form, and the inner instantiation is queued for
    monomorphization
  - Generic template with a generic-instantiated field
    (`interface Outer<U> { x: pb<5, Wrapper<U>> }`) — the inner
    instantiation is now re-substituted and re-monomorphized at outer
    instantiation time
  - Wrapper-binding synthetic SourceFile was empty-text — getText()
    returned garbage, breaking mangled name computation downstream
  - Cross-file forwarded wrappers (chain → imported base) were not
    detected — parseFileForDefinitions now resolves imports recursively
    (value imports only, with cycle protection)
  - matchForwardedKnownWrapper did not propagate typePattern — chain
    treated <X> as the encoded type instead of Wrapper<X>
  - Synthetic-SF WeakMap was private to analyzer.ts — replacer could
    not see it. Moved to utils.ts so typeNodeToMangledName picks it up
    automatically.

Defensive guard: any field whose typeName resolves to neither a primitive
nor a known message now throws at analyze() time, instead of silently
leaking the WireType.Varint placeholder into codegen.

95/95 tests pass; tsc --noEmit clean.
This commit is contained in:
DrSmoothl committed 2026-05-19 08:19:13 +08:00
1 parent 02d1848d39
commit 194165f49d
62 files changed
+4714

No files matched your search

+267
View File
@@ -0,0 +1,267 @@
import ts from 'typescript';
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufMessage, type MessageRegistry, type GenericProtobufTemplate } from './types.js';
import { collectInterface, collectGenericInterface, collectConcreteFieldGenericTypeArgs } from './collector.js';
import { monomorphizeTypeNode } from './monomorphizer.js';
import {
createImportedTypeNameResolver,
typeNodeToMangledName,
registerSyntheticTypeSourceFile,
resolveSourceFileForTypeNode,
} from './utils.js';
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
import {
collectProtobufImportBindings,
matchProtobufCallSite,
type CanonicalProtobufFn,
} from './callsite.js';
import { buildDependencyRegistry } from './dependency-graph.js';
export { typeNodeToMangledName } from './utils.js';
function getCallableName(expr: ts.Expression): string | null {
if (ts.isIdentifier(expr)) return expr.text;
if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
return null;
}
function instantiateWrapperTypePattern(
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
): ts.TypeNode | null {
if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null;
let text = binding.typePattern;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) return null;
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
// Parse the substituted type pattern into a fresh source file whose
// `fileName` is the binding's origin (so subsequent import resolution can
// find the right module) AND whose `text` contains the substituted source
// (so `getText()` on the resulting TypeNode returns the actual type, not
// garbage from an empty-text companion file).
const parsed = ts.createSourceFile(
binding.sourceFilePath ?? sf.fileName,
`type __T = ${text};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) return null;
registerSyntheticTypeSourceFile(stmt.type, parsed);
return stmt.type;
}
/** A recorded call-site for later replacement. */
export interface CallSiteRecord {
fnName: CanonicalProtobufFn;
exprStart: number; // position of identifier start
typeArgsEnd: number; // position after closing '>'
firstTypeArg: ts.TypeNode; // the type argument node
line: number; // 1-based line for runtime map lookup
column: number; // 1-based column for runtime map lookup
}
export interface ResolvedCallSiteRecord extends CallSiteRecord {
typeName: string;
}
export interface AnalysisResult {
registry: MessageRegistry;
callSites: CallSiteRecord[];
sourceFile: ts.SourceFile;
}
export interface UsedRegistryResult {
registry: MessageRegistry;
roots: Set<string>;
callSites: ResolvedCallSiteRecord[];
}
/**
* Analyze TypeScript source in a **single parse + single walk**.
*
* One walk handles both:
* - Collecting concrete + generic interfaces
* - Recording protobuf_encode/decode call-sites
*
* Then post-processes: monomorphize → resolve wire types → topo sort.
*/
export function analyze(code: string, filePath: string, imported?: ImportedDefinitions): AnalysisResult {
const sf = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true);
const concrete: ProtobufMessage[] = [];
const templates = new Map<string, GenericProtobufTemplate>();
const mono = new Map<string, ProtobufMessage>();
const callSites: CallSiteRecord[] = [];
const deferredTypeArgs: ts.TypeNode[] = [];
const importBindings = collectProtobufImportBindings(sf);
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
const wrapperBindings = imported?.wrapperBindings ?? new Map<string, WrapperBinding>();
// Seed with imported definitions
if (imported) {
concrete.push(...imported.concrete);
for (const [k, v] of imported.templates) templates.set(k, v);
}
// ── single walk ─────────────────────────────────────────────────────
ts.forEachChild(sf, function visit(node) {
if (ts.isInterfaceDeclaration(node)) {
if (node.typeParameters?.length) {
const tpl = collectGenericInterface(node, sf, resolveImportedTypeName);
if (tpl) templates.set(tpl.name, tpl);
} else {
const msg = collectInterface(node, sf, resolveImportedTypeName);
if (msg) concrete.push(msg);
// Queue any generic-instantiated type-args appearing as field types
// (e.g. `wrapped: pb<5, Wrapper<uint_32>>`) for monomorphization.
// The call-site queue only sees the outer concrete type, so without
// this the nested instantiation would never reach the registry.
for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) {
deferredTypeArgs.push(ta);
}
}
}
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) {
deferredTypeArgs.push(cs.firstTypeArg);
callSites.push(cs);
} else if (
node.typeArguments?.length &&
getCallableName(node.expression) &&
wrapperBindings.has(getCallableName(node.expression)!)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!)!;
const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf);
if (!firstTypeArg) {
ts.forEachChild(node, visit);
return;
}
const exprStart = node.expression.getStart(sf);
const lc = sf.getLineAndCharacterOfPosition(exprStart);
deferredTypeArgs.push(firstTypeArg);
callSites.push({
fnName: binding.fnName,
exprStart,
typeArgsEnd: node.typeArguments.end + 1,
firstTypeArg,
line: lc.line + 1,
column: lc.character + 1,
});
}
}
ts.forEachChild(node, visit);
});
// ── post-walk: monomorphize deferred type args ──────────────────────
for (const typeArg of deferredTypeArgs) {
const typeSf = resolveSourceFileForTypeNode(typeArg, sf);
const typeResolver = createImportedTypeNameResolver(typeSf);
monomorphizeTypeNode(typeArg, typeSf, templates, mono, typeResolver);
}
for (const m of mono.values()) concrete.push(m);
// ── resolve wire types ──────────────────────────────────────────────
// Anything that doesn't resolve to a primitive or a registered message is
// a type-tracking miss — historically these leaked the placeholder
// `WireType.Varint` into codegen and corrupted the wire format silently.
// Throw loudly instead so future analyzer gaps surface immediately.
const names = new Set(concrete.map(m => m.name));
for (const msg of concrete) {
for (const f of msg.fields) {
const prim = PRIMITIVE_TYPE_MAP[f.typeName];
if (prim) {
f.wireType = prim.wireType;
f.isMessage = false;
} else if (names.has(f.typeName)) {
f.wireType = WireType.LengthDelim;
f.isMessage = true;
} else {
throw new Error(
`Cannot resolve protobuf field type "${f.typeName}" on message "${msg.name}" ` +
`(field "${f.name}", field number ${f.fieldNumber}). The analyzer did not produce ` +
`a primitive or registered message for this type. Common causes: union / intersection / ` +
`mapped / conditional types, TypeScript utility types (Partial<T>, Pick<T>, …), ` +
`qualified names (ns.Type), or a missing import.`,
);
}
}
}
return { registry: topoSort(concrete), callSites, sourceFile: sf };
}
/**
* Backward-compatible wrapper: returns only the MessageRegistry.
* Uses the same single-walk analysis internally.
*/
export function analyzeSource(code: string, filePath: string, imported?: ImportedDefinitions): MessageRegistry {
return analyze(code, filePath, imported).registry;
}
/**
* Build a minimal message registry by collecting only call-site root types and
* their transitive message dependencies.
*/
export function selectUsedRegistry(
registry: MessageRegistry,
callSites: CallSiteRecord[],
sourceFile: ts.SourceFile,
): UsedRegistryResult {
const roots = new Set<string>();
const resolved: ResolvedCallSiteRecord[] = [];
const resolveImportedTypeName = createImportedTypeNameResolver(sourceFile);
for (const cs of callSites) {
const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile);
const typeName = typeNodeToMangledName(cs.firstTypeArg, typeSf, createImportedTypeNameResolver(typeSf));
if (!registry.has(typeName)) continue;
roots.add(typeName);
resolved.push({ ...cs, typeName });
}
if (roots.size === 0) {
return { registry: new Map(), roots, callSites: resolved };
}
return {
registry: buildDependencyRegistry(registry, roots),
roots,
callSites: resolved,
};
}
// ── topological sort ──────────────────────────────────────────────────
function topoSort(messages: ProtobufMessage[]): MessageRegistry {
const map = new Map(messages.map(m => [m.name, m]));
const deps = new Map(messages.map(m => [
m.name,
new Set(m.fields.filter(f => map.has(f.typeName)).map(f => f.typeName)),
]));
const sorted: ProtobufMessage[] = [];
const visited = new Set<string>();
const visiting = new Set<string>();
function dfs(name: string): void {
if (visited.has(name)) return;
if (visiting.has(name)) throw new Error(`Circular dependency: ${name}`);
visiting.add(name);
for (const d of deps.get(name) || []) dfs(d);
visiting.delete(name);
visited.add(name);
sorted.push(map.get(name)!);
}
for (const m of messages) dfs(m.name);
return new Map(sorted.map(m => [m.name, m]));
}
+119
View File
@@ -0,0 +1,119 @@
import ts from 'typescript';
export type CanonicalProtobufFn = 'protobuf_encode' | 'protobuf_decode';
const CANONICAL = new Set<CanonicalProtobufFn>(['protobuf_encode', 'protobuf_decode']);
const PROTOBUF_RUNTIME_MODULES = new Set([
'@snowluma/proton',
]);
export interface ProtobufImportBindings {
identifierToCanonical: Map<string, CanonicalProtobufFn>;
namespaceAliases: Set<string>;
blockedLegacyCanonical: Set<CanonicalProtobufFn>;
hasRuntimeImport: boolean;
}
export interface ProtobufCallSite {
fnName: CanonicalProtobufFn;
exprStart: number;
typeArgsEnd: number;
firstTypeArg: ts.TypeNode;
line: number;
column: number;
}
export function collectProtobufImportBindings(sf: ts.SourceFile): ProtobufImportBindings {
const identifierToCanonical = new Map<string, CanonicalProtobufFn>();
const namespaceAliases = new Set<string>();
const blockedLegacyCanonical = new Set<CanonicalProtobufFn>();
let hasRuntimeImport = false;
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
if (!ts.isStringLiteral(stmt.moduleSpecifier)) continue;
const fromRuntime = PROTOBUF_RUNTIME_MODULES.has(stmt.moduleSpecifier.text);
if (fromRuntime) hasRuntimeImport = true;
const bindings = stmt.importClause.namedBindings;
const defaultImport = stmt.importClause.name?.text;
if (defaultImport && CANONICAL.has(defaultImport as CanonicalProtobufFn) && !fromRuntime) {
blockedLegacyCanonical.add(defaultImport as CanonicalProtobufFn);
}
if (!bindings) continue;
if (ts.isNamedImports(bindings)) {
for (const el of bindings.elements) {
const imported = (el.propertyName ?? el.name).text;
if (fromRuntime && CANONICAL.has(imported as CanonicalProtobufFn)) {
identifierToCanonical.set(el.name.text, imported as CanonicalProtobufFn);
continue;
}
if (CANONICAL.has(el.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(el.name.text as CanonicalProtobufFn);
}
}
continue;
}
if (fromRuntime && ts.isNamespaceImport(bindings)) {
namespaceAliases.add(bindings.name.text);
} else if (CANONICAL.has(bindings.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(bindings.name.text as CanonicalProtobufFn);
}
}
return { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport };
}
interface MatchOptions {
allowLegacyUnboundCanonical?: boolean;
}
export function matchProtobufCallSite(
node: ts.CallExpression,
sf: ts.SourceFile,
bindings: ProtobufImportBindings,
options?: MatchOptions,
): ProtobufCallSite | null {
const ta = node.typeArguments;
if (!ta?.length) return null;
const expr = node.expression;
const allowLegacy = options?.allowLegacyUnboundCanonical === true;
let fnName: CanonicalProtobufFn | null = null;
let exprStart = expr.getStart(sf);
if (ts.isIdentifier(expr)) {
fnName = bindings.identifierToCanonical.get(expr.text) ?? null;
if (
!fnName &&
allowLegacy &&
!bindings.hasRuntimeImport &&
CANONICAL.has(expr.text as CanonicalProtobufFn) &&
!bindings.blockedLegacyCanonical.has(expr.text as CanonicalProtobufFn)
) {
fnName = expr.text as CanonicalProtobufFn;
}
} else if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression)) {
if (bindings.namespaceAliases.has(expr.expression.text) && CANONICAL.has(expr.name.text as CanonicalProtobufFn)) {
fnName = expr.name.text as CanonicalProtobufFn;
exprStart = expr.getStart(sf);
}
}
if (!fnName) return null;
const lc = sf.getLineAndCharacterOfPosition(exprStart);
return {
fnName,
exprStart,
typeArgsEnd: ta.end + 1,
firstTypeArg: ta[0],
line: lc.line + 1,
column: lc.character + 1,
};
}
+157
View File
@@ -0,0 +1,157 @@
import ts from 'typescript';
import {
WireType,
PB_MARKER, PB_REPEATED_MARKER,
type ProtobufField, type ProtobufMessage,
type GenericProtobufTemplate, type GenericFieldTemplate,
} from './types.js';
import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js';
function identityImportedTypeName(name: string): string {
return name;
}
/**
* Yield generic-instantiated type-arg nodes appearing as field types on a
* **concrete** (non-generic) interface — e.g. `wrapped: pb<5, Wrapper<uint_32>>`
* yields the `Wrapper<uint_32>` node so the analyzer can enqueue it for
* monomorphization. (The call-site-driven queue only sees the outer concrete
* type; nested generic instantiations on its fields would otherwise be missed.)
*/
export function* collectConcreteFieldGenericTypeArgs(
node: ts.InterfaceDeclaration,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): IterableIterator<ts.TypeNode> {
if (node.typeParameters?.length) return;
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue;
const parsed = parsePbTypeRef(m, resolveImportedTypeName);
if (!parsed) continue;
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
yield ta;
}
}
}
/** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */
export function collectInterface(
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): ProtobufMessage | null {
const fields: ProtobufField[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue;
const f = extractField(m, sf, resolveImportedTypeName);
if (f) fields.push(f);
}
return fields.length ? { name: node.name.text, fields } : null;
}
/** Collect a generic interface template. */
export function collectGenericInterface(
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): GenericProtobufTemplate | null {
const typeParams = node.typeParameters!.map(p => p.name.text);
const tpSet = new Set(typeParams);
const fields: GenericFieldTemplate[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue;
const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName);
if (f) fields.push(f);
}
return fields.length ? { name: node.name.text, typeParams, fields } : null;
}
// ── helpers ───────────────────────────────────────────────────────────
function parsePbTypeRef(
member: ts.PropertySignature,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): { marker: string; fieldNumber: number; typeArgNode: ts.TypeNode } | null {
const t = member.type!;
if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null;
// Resolve the marker name through aliased imports so `import { pb as P }`
// / `import { pb_repeated as PR }` still match the marker constants.
const marker = resolveImportedTypeName(t.typeName.text);
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null;
const ta = t.typeArguments;
if (!ta || ta.length !== 2) return null;
const fnNode = ta[0];
if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null;
return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] };
}
function resolveTypeName(
node: ts.TypeNode,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
): string | null {
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
// Generic instantiations (e.g. `Wrapper<uint_32>`) must resolve to the
// mangled name produced by monomorphization so wire-type resolution can
// find the message in the registry. Without this the field would carry
// the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`.
if (node.typeArguments && node.typeArguments.length > 0) {
return typeNodeToMangledName(node, sf, resolveImportedTypeName);
}
return resolveImportedTypeName(node.typeName.text);
}
if (isKeywordTypeNode(node)) return node.getText(sf);
return null;
}
function extractField(
member: ts.PropertySignature,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
): ProtobufField | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) return null;
const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!typeName || !ts.isIdentifier(member.name)) return null;
return {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
typeName,
wireType: WireType.Varint, // placeholder
isMessage: false, // placeholder
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
};
}
function extractGenericField(
member: ts.PropertySignature,
sf: ts.SourceFile,
tpSet: Set<string>,
resolveImportedTypeName: ImportedTypeNameResolver,
): GenericFieldTemplate | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) return null;
const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!raw || !ts.isIdentifier(member.name)) return null;
const result: GenericFieldTemplate = {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw),
isTypeParam: tpSet.has(raw),
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
};
// If the field's type-arg is itself a generic instantiation (`Wrapper<U>`,
// where U is a type param of the enclosing template), capture the original
// source text so monomorphization can substitute U and re-instantiate the
// inner generic. Without this the field's `rawTypeName` would stay at the
// unsubstituted `'Wrapper__U'` form and the substituted instantiation
// would never reach the registry.
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
result.genericTypeArgText = ta.getText(sf);
result.genericTypeArgSourceFilePath = sf.fileName;
}
return result;
}
@@ -0,0 +1,32 @@
import type { MessageRegistry } from './types.js';
export function collectDependencyClosure(registry: MessageRegistry, roots: Iterable<string>): Set<string> {
const selected = new Set<string>();
function visit(name: string): void {
if (selected.has(name)) return;
const msg = registry.get(name);
if (!msg) return;
selected.add(name);
for (const field of msg.fields) {
if (registry.has(field.typeName)) visit(field.typeName);
}
}
for (const root of roots) visit(root);
return selected;
}
export function pickRegistrySubset(registry: MessageRegistry, selectedNames: Set<string>): MessageRegistry {
const subset: MessageRegistry = new Map();
for (const [name, msg] of registry) {
if (selectedNames.has(name)) subset.set(name, msg);
}
return subset;
}
export function buildDependencyRegistry(registry: MessageRegistry, roots: Iterable<string>): MessageRegistry {
const selected = collectDependencyClosure(registry, roots);
return pickRegistrySubset(registry, selected);
}
+659
View File
@@ -0,0 +1,659 @@
import ts from 'typescript';
import { readFileSync, existsSync } from 'fs';
import { dirname, resolve } from 'path';
import { collectInterface, collectGenericInterface } from './collector.js';
import { PRIMITIVE_TYPE_MAP, type ProtobufMessage, type GenericProtobufTemplate } from './types.js';
import { createImportedTypeNameResolver, isKeywordTypeNode, type ImportedTypeNameResolver } from './utils.js';
import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalProtobufFn } from './callsite.js';
export interface WrapperBinding {
fnName: CanonicalProtobufFn;
typeArgIndex: number;
typePattern?: string;
typeParamNames?: string[];
sourceFilePath?: string;
}
export interface ParsedFileEntry {
filePath: string;
concrete: ProtobufMessage[];
templates: Map<string, GenericProtobufTemplate>;
importedTypeSources: Map<string, string>;
resolveImportedTypeName: ImportedTypeNameResolver;
exportedWrappers: Map<string, WrapperBinding>;
}
export interface ImportedDefinitions {
concrete: ProtobufMessage[];
templates: Map<string, GenericProtobufTemplate>;
wrapperBindings: Map<string, WrapperBinding>;
}
interface ImportClause {
importedName: string;
localName: string;
specifier: string;
}
function getCallableName(expr: ts.Expression): string | null {
if (ts.isIdentifier(expr)) return expr.text;
if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
return null;
}
/** Extract all named imports from the source file (both type and value imports). */
function extractImports(sf: ts.SourceFile): ImportClause[] {
const result: ImportClause[] = [];
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
const spec = stmt.moduleSpecifier;
if (!ts.isStringLiteral(spec)) continue;
const specifier = spec.text;
const clause = stmt.importClause;
if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
for (const el of clause.namedBindings.elements) {
result.push({
importedName: (el.propertyName ?? el.name).text,
localName: el.name.text,
specifier,
});
}
}
}
return result;
}
/** Like `extractImports`, but skips `import type { ... }` and `import { type X }`
* entries. Wrapper functions are values, so type-only imports can't introduce
* one and we shouldn't eagerly parse their source files just to look for wrappers. */
function extractValueImports(sf: ts.SourceFile): ImportClause[] {
const result: ImportClause[] = [];
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
if (stmt.importClause.isTypeOnly) continue;
const spec = stmt.moduleSpecifier;
if (!ts.isStringLiteral(spec)) continue;
const specifier = spec.text;
const clause = stmt.importClause;
if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
for (const el of clause.namedBindings.elements) {
if (el.isTypeOnly) continue;
result.push({
importedName: (el.propertyName ?? el.name).text,
localName: el.name.text,
specifier,
});
}
}
}
return result;
}
/** Resolve a relative module specifier to an absolute file path. Returns null if not found. */
function resolveModulePath(specifier: string, importerPath: string): string | null {
if (!specifier.startsWith('.')) return null; // skip bare/alias specifiers
const base = resolve(dirname(importerPath), specifier);
// Try exact path (e.g., './types.ts')
if (existsSync(base) && !base.endsWith('.ts') === false) return base;
if (base.endsWith('.ts') && existsSync(base)) return base;
// Try appending .ts
const withTs = base + '.ts';
if (existsSync(withTs)) return withTs;
// Try as directory with index.ts
const indexTs = resolve(base, 'index.ts');
if (existsSync(indexTs)) return indexTs;
return null;
}
function hasExportModifier(node: ts.Node): boolean {
return ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);
}
function matchForwardedProtobufFn(
body: ts.ConciseBody | ts.Block | undefined,
sf: ts.SourceFile,
typeParams: readonly ts.TypeParameterDeclaration[] | undefined,
): WrapperBinding | null {
if (!body || !typeParams?.length) return null;
const typeParamIndexes = new Map(typeParams.map((p, index) => [p.name.text, index]));
const typeParamNames = typeParams.map(p => p.name.text);
const bindings = collectProtobufImportBindings(sf);
let found: WrapperBinding | null = null;
function visit(node: ts.Node): void {
if (found) return;
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, bindings, {
allowLegacyUnboundCanonical: true,
});
if (
cs &&
ts.isTypeReferenceNode(cs.firstTypeArg) &&
ts.isIdentifier(cs.firstTypeArg.typeName) &&
typeParamIndexes.has(cs.firstTypeArg.typeName.text)
) {
found = {
fnName: cs.fnName,
typeArgIndex: typeParamIndexes.get(cs.firstTypeArg.typeName.text)!,
sourceFilePath: sf.fileName,
};
return;
}
if (cs && containsTypeParameter(cs.firstTypeArg, typeParamIndexes)) {
found = {
fnName: cs.fnName,
typeArgIndex: firstTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) ?? 0,
typePattern: cs.firstTypeArg.getText(sf),
typeParamNames,
sourceFilePath: sf.fileName,
};
return;
}
}
ts.forEachChild(node, visit);
}
visit(body);
return found;
}
function containsTypeParameter(typeNode: ts.TypeNode, typeParamIndexes: Map<string, number>): boolean {
let found = false;
function visit(node: ts.Node): void {
if (found) return;
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) {
found = true;
return;
}
ts.forEachChild(node, visit);
}
visit(typeNode);
return found;
}
function firstTypeParameterIndex(typeNode: ts.TypeNode, typeParamIndexes: Map<string, number>): number | null {
let index: number | null = null;
function visit(node: ts.Node): void {
if (index !== null) return;
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) {
index = typeParamIndexes.get(node.typeName.text)!;
return;
}
ts.forEachChild(node, visit);
}
visit(typeNode);
return index;
}
function instantiateWrapperTypePattern(
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
): ts.TypeNode | null {
if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null;
let text = binding.typePattern;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) return null;
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
const parsed = ts.createSourceFile('wrapper-type.ts', `type __T = ${text};`, ts.ScriptTarget.Latest, true);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) return null;
return stmt.type;
}
function matchForwardedKnownWrapper(
body: ts.ConciseBody | ts.Block | undefined,
typeParams: readonly ts.TypeParameterDeclaration[] | undefined,
knownWrappers: Map<string, WrapperBinding>,
): WrapperBinding | null {
if (!body || !typeParams?.length) return null;
const tps = typeParams; // narrowed copy for closure scope
const typeParamIndexes = new Map(tps.map((p, index) => [p.name.text, index]));
let found: WrapperBinding | null = null;
function visit(node: ts.Node): void {
if (found) return;
if (ts.isCallExpression(node) && node.typeArguments?.length) {
const callableName = getCallableName(node.expression);
const wrapper = callableName ? knownWrappers.get(callableName) : undefined;
const forwardedTypeArg = wrapper ? node.typeArguments[wrapper.typeArgIndex] : undefined;
if (
wrapper &&
forwardedTypeArg &&
ts.isTypeReferenceNode(forwardedTypeArg) &&
ts.isIdentifier(forwardedTypeArg.typeName) &&
!forwardedTypeArg.typeArguments?.length &&
typeParamIndexes.has(forwardedTypeArg.typeName.text)
) {
const chainTypeArgIndex = typeParamIndexes.get(forwardedTypeArg.typeName.text)!;
const binding: WrapperBinding = {
fnName: wrapper.fnName,
typeArgIndex: chainTypeArgIndex,
};
// Propagate the typePattern from the inner wrapper, substituting
// its type-param names with the chain's own. Otherwise the chain
// would treat its own `<X>` as the encoded type rather than the
// wrapped form (e.g. `Wrapper<X>`).
if (wrapper.typePattern && wrapper.typeParamNames?.length === 1) {
const chainParamName = tps[chainTypeArgIndex].name.text;
const wrapperParamName = wrapper.typeParamNames[0];
binding.typePattern = wrapperParamName === chainParamName
? wrapper.typePattern
: wrapper.typePattern.replace(new RegExp(`\\b${wrapperParamName}\\b`, 'g'), chainParamName);
binding.typeParamNames = [chainParamName];
binding.sourceFilePath = wrapper.sourceFilePath;
}
found = binding;
return;
}
}
ts.forEachChild(node, visit);
}
visit(body);
return found;
}
function collectWrapperCandidates(
sf: ts.SourceFile,
exportedOnly: boolean,
): Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> {
const candidates: Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> = [];
for (const stmt of sf.statements) {
if (ts.isFunctionDeclaration(stmt) && stmt.name && (!exportedOnly || hasExportModifier(stmt))) {
candidates.push({ name: stmt.name.text, body: stmt.body, typeParameters: stmt.typeParameters });
continue;
}
if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue;
for (const decl of stmt.declarationList.declarations) {
if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;
const init = decl.initializer;
if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) {
candidates.push({ name: decl.name.text, body: init.body, typeParameters: init.typeParameters });
continue;
}
if (ts.isObjectLiteralExpression(init)) {
for (const prop of init.properties) {
if (ts.isPropertyAssignment(prop)) {
const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null;
const propInit = prop.initializer;
if (propName && (ts.isArrowFunction(propInit) || ts.isFunctionExpression(propInit))) {
candidates.push({ name: propName, body: propInit.body, typeParameters: propInit.typeParameters });
}
continue;
}
if (ts.isMethodDeclaration(prop)) {
const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null;
if (propName) candidates.push({ name: propName, body: prop.body, typeParameters: prop.typeParameters });
}
}
}
}
}
return candidates;
}
function collectWrappers(
sf: ts.SourceFile,
exportedOnly: boolean,
externalKnownWrappers: Map<string, WrapperBinding> = new Map(),
): Map<string, WrapperBinding> {
const wrappers = new Map<string, WrapperBinding>();
const localWrapperMembers = new Map<string, Map<string, WrapperBinding>>();
const candidates = collectWrapperCandidates(sf, exportedOnly);
for (const candidate of candidates) {
const fn = matchForwardedProtobufFn(candidate.body, sf, candidate.typeParameters);
if (fn) wrappers.set(candidate.name, fn);
}
// Detect both intra-file forwarders (`encodeFoo<T>(v) { return encodeBar<T>(v); }`
// where `encodeBar` is local) AND cross-file forwarders to wrappers imported
// from already-parsed modules. Externally known wrappers are seeded by the
// caller (`parseFileForDefinitions`) after it resolves imports.
const knownForForwarding = new Map<string, WrapperBinding>();
for (const [k, v] of externalKnownWrappers) knownForForwarding.set(k, v);
for (const [k, v] of wrappers) knownForForwarding.set(k, v);
for (const candidate of candidates) {
if (wrappers.has(candidate.name)) continue;
const fn = matchForwardedKnownWrapper(candidate.body, candidate.typeParameters, knownForForwarding);
if (fn) wrappers.set(candidate.name, fn);
}
for (const stmt of sf.statements) {
if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue;
for (const decl of stmt.declarationList.declarations) {
if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;
const init = decl.initializer;
if (ts.isObjectLiteralExpression(init)) {
const memberWrappers = new Map<string, WrapperBinding>();
for (const prop of init.properties) {
if (!('name' in prop) || !prop.name) continue;
const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null;
if (!propName) continue;
const fn = wrappers.get(propName);
if (fn) {
memberWrappers.set(propName, fn);
}
}
if (memberWrappers.size) localWrapperMembers.set(decl.name.text, memberWrappers);
}
}
}
for (const stmt of sf.statements) {
if (exportedOnly || !ts.isVariableStatement(stmt)) continue;
for (const decl of stmt.declarationList.declarations) {
if (!ts.isIdentifier(decl.name) || !decl.initializer || !ts.isPropertyAccessExpression(decl.initializer)) continue;
if (!ts.isIdentifier(decl.initializer.expression)) continue;
const memberWrappers = localWrapperMembers.get(decl.initializer.expression.text);
const fn = memberWrappers?.get(decl.initializer.name.text);
if (fn) wrappers.set(decl.name.text, fn);
}
}
return wrappers;
}
function collectExportedWrappers(
sf: ts.SourceFile,
externalKnownWrappers: Map<string, WrapperBinding> = new Map(),
): Map<string, WrapperBinding> {
return collectWrappers(sf, true, externalKnownWrappers);
}
/**
* Parse a file and extract its protobuf interfaces and generic templates.
*
* When `cache` is provided, this resolves the file's imports recursively
* (with cycle protection) so cross-file forwarded wrappers — e.g.
* `export function encodeChain<T>(v) { return encodeBase<T>(v); }`
* where `encodeBase` is imported from another module — can be detected.
*/
function parseFileForDefinitions(
absolutePath: string,
code?: string,
cache?: Map<string, ParsedFileEntry>,
parsing?: Set<string>,
): ParsedFileEntry {
const sourceText = code ?? readFileSync(absolutePath, 'utf-8');
const sf = ts.createSourceFile(absolutePath, sourceText, ts.ScriptTarget.Latest, true);
const concrete: ProtobufMessage[] = [];
const templates = new Map<string, GenericProtobufTemplate>();
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
const importedTypeSources = new Map<string, string>();
// Collect imported wrapper bindings under their LOCAL names so this file's
// forwarders can match against them. Skip work entirely if there's no cache
// (legacy callers that don't care about cross-file forwarding).
//
// Only descends into value imports (not `import type { ... }`), since
// type-only imports can never introduce a wrapper function. This avoids
// pulling unrelated type-only modules into the cache.
const importedKnownWrappers = new Map<string, WrapperBinding>();
if (cache) {
const inProgress = parsing ?? new Set<string>();
inProgress.add(absolutePath);
for (const imp of extractValueImports(sf)) {
const resolved = resolveModulePath(imp.specifier, absolutePath);
if (!resolved) continue;
if (inProgress.has(resolved)) continue; // cycle guard
let entry = cache.get(resolved);
if (!entry) {
entry = parseFileForDefinitions(resolved, undefined, cache, inProgress);
cache.set(resolved, entry);
}
const wrapperFn = entry.exportedWrappers.get(imp.importedName);
if (wrapperFn) importedKnownWrappers.set(imp.localName, wrapperFn);
}
inProgress.delete(absolutePath);
}
const exportedWrappers = collectExportedWrappers(sf, importedKnownWrappers);
for (const imp of extractImports(sf)) {
const resolved = resolveModulePath(imp.specifier, absolutePath);
if (!resolved) continue;
importedTypeSources.set(imp.importedName, resolved);
importedTypeSources.set(imp.localName, resolved);
}
for (const stmt of sf.statements) {
if (!ts.isInterfaceDeclaration(stmt)) continue;
if (stmt.typeParameters?.length) {
const tpl = collectGenericInterface(stmt, sf, resolveImportedTypeName);
if (tpl) templates.set(tpl.name, tpl);
} else {
const msg = collectInterface(stmt, sf, resolveImportedTypeName);
if (msg) concrete.push(msg);
}
}
return {
filePath: absolutePath,
concrete,
templates,
importedTypeSources,
resolveImportedTypeName,
exportedWrappers,
};
}
function collectCallRootTypeNodes(sf: ts.SourceFile): ts.TypeNode[] {
const roots: ts.TypeNode[] = [];
const importBindings = collectProtobufImportBindings(sf);
ts.forEachChild(sf, function visit(node) {
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) roots.push(cs.firstTypeArg);
}
ts.forEachChild(node, visit);
});
return roots;
}
interface RootTypeNode {
typeNode: ts.TypeNode;
from: ParsedFileEntry;
}
/**
* Resolve only the import definitions reachable from protobuf call-site roots.
*/
export function resolveImports(
code: string,
importerPath: string,
cache: Map<string, ParsedFileEntry>,
): ImportedDefinitions {
const entryPath = resolve(importerPath);
const entry = parseFileForDefinitions(entryPath, code, cache);
const concrete = new Map<string, ProtobufMessage>();
const templates = new Map<string, GenericProtobufTemplate>();
const fileEntries = new Map<string, ParsedFileEntry>([[entryPath, entry]]);
const visitedConcrete = new Set<string>();
const visitedTemplates = new Set<string>();
const importedObjectWrapperMembers = new Map<string, Map<string, WrapperBinding>>();
function getEntry(filePath: string): ParsedFileEntry {
const abs = resolve(filePath);
const known = fileEntries.get(abs);
if (known) return known;
let parsed = cache.get(abs);
if (!parsed) {
parsed = parseFileForDefinitions(abs, undefined, cache);
cache.set(abs, parsed);
}
fileEntries.set(abs, parsed);
return parsed;
}
function collectCalledGenericIdentifiers(sf: ts.SourceFile): Set<string> {
const names = new Set<string>();
ts.forEachChild(sf, function visit(node) {
if (ts.isCallExpression(node) && node.typeArguments?.length) {
const callableName = getCallableName(node.expression);
if (callableName) names.add(callableName);
}
ts.forEachChild(node, visit);
});
return names;
}
function collectWrapperBindings(from: ParsedFileEntry, sf: ts.SourceFile): Map<string, WrapperBinding> {
const bindings = new Map<string, WrapperBinding>();
const localWrappers = from.filePath === entryPath ? collectWrappers(sf, false) : from.exportedWrappers;
for (const [name, fn] of localWrappers) bindings.set(name, fn);
const calledGenericIdentifiers = collectCalledGenericIdentifiers(sf);
for (const imp of extractImports(sf)) {
if (!calledGenericIdentifiers.has(imp.localName)) continue;
const resolved = resolveModulePath(imp.specifier, from.filePath);
if (!resolved) continue;
const wrapperFn = getEntry(resolved).exportedWrappers.get(imp.importedName);
if (wrapperFn) bindings.set(imp.localName, wrapperFn);
const importedEntry = getEntry(resolved);
const memberNames = [...importedEntry.exportedWrappers.keys()].filter(name => calledGenericIdentifiers.has(name));
if (memberNames.length) {
const members = new Map<string, WrapperBinding>();
for (const name of memberNames) {
const memberBinding = importedEntry.exportedWrappers.get(name)!;
members.set(name, memberBinding);
bindings.set(name, memberBinding);
}
importedObjectWrapperMembers.set(imp.localName, members);
}
}
return bindings;
}
function resolveTypeName(typeName: string, from: ParsedFileEntry): void {
if (typeName in PRIMITIVE_TYPE_MAP) return;
const concreteMsg = from.concrete.find(msg => msg.name === typeName);
if (concreteMsg) {
const visitKey = `${from.filePath}:message:${typeName}`;
if (visitedConcrete.has(visitKey)) return;
visitedConcrete.add(visitKey);
if (from.filePath !== entryPath && !concrete.has(concreteMsg.name)) {
concrete.set(concreteMsg.name, concreteMsg);
}
for (const field of concreteMsg.fields) {
resolveTypeName(field.typeName, from);
}
return;
}
const template = from.templates.get(typeName);
if (template) {
const visitKey = `${from.filePath}:template:${typeName}`;
if (visitedTemplates.has(visitKey)) return;
visitedTemplates.add(visitKey);
if (from.filePath !== entryPath && !templates.has(template.name)) {
templates.set(template.name, template);
}
for (const field of template.fields) {
if (!field.isTypeParam) resolveTypeName(field.rawTypeName, from);
}
return;
}
const importedPath = from.importedTypeSources.get(typeName);
if (!importedPath) return;
resolveTypeName(typeName, getEntry(importedPath));
}
function resolveTypeNode(typeNode: ts.TypeNode, from: ParsedFileEntry): void {
if (isKeywordTypeNode(typeNode)) return;
if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return;
const typeName = from.resolveImportedTypeName(typeNode.typeName.text);
resolveTypeName(typeName, from);
if (!typeNode.typeArguments?.length) return;
for (const typeArg of typeNode.typeArguments) {
resolveTypeNode(typeArg, from);
}
}
const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true))
.map(typeNode => ({ typeNode, from: entry }));
const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true);
const wrapperBindings = collectWrapperBindings(entry, entrySourceFile);
ts.forEachChild(entrySourceFile, function visit(node) {
if (
ts.isCallExpression(node) &&
node.typeArguments?.length &&
getCallableName(node.expression) &&
(
wrapperBindings.has(getCallableName(node.expression)!) ||
(
ts.isPropertyAccessExpression(node.expression) &&
ts.isIdentifier(node.expression.expression) &&
importedObjectWrapperMembers.get(node.expression.expression.text)?.has(node.expression.name.text)
)
)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!) ?? (
ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)
? importedObjectWrapperMembers.get(node.expression.expression.text)?.get(node.expression.name.text)
: undefined
);
if (!binding) return;
const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile);
if (typeArg) rootTypeNodes.push({
typeNode: typeArg,
from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry,
});
if (binding.typePattern) {
for (const callerTypeArg of node.typeArguments) {
rootTypeNodes.push({ typeNode: callerTypeArg, from: entry });
}
}
}
ts.forEachChild(node, visit);
});
for (const root of rootTypeNodes) {
resolveTypeNode(root.typeNode, root.from);
}
return { concrete: [...concrete.values()], templates, wrapperBindings };
}
+131
View File
@@ -0,0 +1,131 @@
import ts from 'typescript';
import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js';
import {
isKeywordTypeNode,
createImportedTypeNameResolver,
resolveSourceFileForTypeNode,
type ImportedTypeNameResolver,
typeNodeToMangledName,
} from './utils.js';
function identityImportedTypeName(name: string): string {
return name;
}
/** Resolved value for a single template type parameter. */
interface ResolvedTypeArg {
/** Mangled-name form used when substituting into a `rawTypeName` slot
* for an `isTypeParam` field. */
mangled: string;
/** Original TypeScript source text — used when re-substituting into a
* field's `genericTypeArgText` so the substituted text remains parseable. */
text: string;
}
/**
* Recursively monomorphize a generic type instantiation into concrete ProtobufMessages.
* E.g. `Wrapper<Wrapper<string>>` → creates `Wrapper__string` and `Wrapper__Wrapper__string`.
* Returns the mangled name of the concrete type, or null if it cannot be resolved.
*/
export function monomorphizeTypeNode(
typeNode: ts.TypeNode,
sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): string | null {
if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null;
const baseName = resolveImportedTypeName(typeNode.typeName.text);
const typeArgs = typeNode.typeArguments;
if (!typeArgs || typeArgs.length === 0) return baseName; // already concrete
const tpl = templates.get(baseName);
if (!tpl || typeArgs.length !== tpl.typeParams.length) return null;
const mangledName = typeNodeToMangledName(typeNode, sf, resolveImportedTypeName);
if (out.has(mangledName)) return mangledName; // already done
// Resolve each type parameter → both mangled name AND source text.
const paramMap = new Map<string, ResolvedTypeArg>();
for (let i = 0; i < tpl.typeParams.length; i++) {
const resolved = resolveTypeArg(typeArgs[i], sf, templates, out, resolveImportedTypeName);
if (!resolved) return null;
paramMap.set(tpl.typeParams[i], resolved);
}
// Substitute type params in template fields.
const fields: ProtobufField[] = tpl.fields.map(f => {
if (f.genericTypeArgText) {
// Field type is an inner generic instantiation referencing template
// type params (e.g. `pb<N, Wrapper<U>>`). Substitute the params into
// the captured text, re-parse, and re-monomorphize so the resulting
// concrete instantiation (`Wrapper<uint_32>`) lands in `out`.
let substituted = f.genericTypeArgText;
for (const [paramName, value] of paramMap) {
substituted = substituted.replace(
new RegExp(`\\b${paramName}\\b`, 'g'),
value.text,
);
}
const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName;
const innerSf = ts.createSourceFile(
innerSfPath,
`type __X = ${substituted};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = innerSf.statements[0];
let resolvedTypeName: string | null = null;
if (ts.isTypeAliasDeclaration(stmt)) {
const innerResolver = createImportedTypeNameResolver(innerSf);
resolvedTypeName = monomorphizeTypeNode(stmt.type, innerSf, templates, out, innerResolver);
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: resolvedTypeName ?? f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
};
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: f.isTypeParam ? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName) : f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
};
});
out.set(mangledName, { name: mangledName, fields });
return mangledName;
}
function resolveTypeArg(
node: ts.TypeNode,
sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver,
): ResolvedTypeArg | null {
const effectiveSf = resolveSourceFileForTypeNode(node, sf);
// Try recursive monomorphization first (handles nested generics).
const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName);
if (mono) return { mangled: mono, text: node.getText(effectiveSf) };
// Keyword type (string, number, …)
if (isKeywordTypeNode(node)) {
const text = node.getText(effectiveSf);
return { mangled: text, text };
}
// Simple identifier (uint_32, SomeMsg, …)
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) {
const name = resolveImportedTypeName(node.typeName.text);
return { mangled: name, text: name };
}
return null;
}
+72
View File
@@ -0,0 +1,72 @@
export enum WireType {
Varint = 0,
Bit64 = 1,
LengthDelim = 2,
Bit32 = 5,
}
export interface ProtobufField {
name: string;
fieldNumber: number;
typeName: string;
wireType: WireType;
isMessage: boolean;
isOptional: boolean;
isRepeated: boolean;
}
export interface ProtobufMessage {
name: string;
fields: ProtobufField[];
}
/** Generic interface template, e.g. `interface Wrapper<T> { val: pb<1, T>; }` */
export interface GenericProtobufTemplate {
name: string;
typeParams: string[];
fields: GenericFieldTemplate[];
}
export interface GenericFieldTemplate {
name: string;
fieldNumber: number;
rawTypeName: string;
isTypeParam: boolean;
isOptional: boolean;
isRepeated: boolean;
/**
* For fields whose type-arg is itself a generic instantiation
* (e.g. `wrapped: pb<5, Wrapper<U>>` where `U` is a template type
* parameter), the original type-arg source text. At monomorphization
* time the substituted text is re-parsed and re-instantiated so
* `Wrapper<uint_32>` ends up in the registry under its mangled name.
*/
genericTypeArgText?: string;
/** Source-file path captured alongside `genericTypeArgText`, used as
* the synthetic file name when re-parsing the substituted text. */
genericTypeArgSourceFilePath?: string;
}
export type MessageRegistry = Map<string, ProtobufMessage>;
export const PRIMITIVE_TYPE_MAP: Record<string, { wireType: WireType; defaultValue: string }> = {
uint_32: { wireType: WireType.Varint, defaultValue: '0' },
int_32: { wireType: WireType.Varint, defaultValue: '0' },
uint_64: { wireType: WireType.Varint, defaultValue: '0' },
int_64: { wireType: WireType.Varint, defaultValue: '0' },
sint_32: { wireType: WireType.Varint, defaultValue: '0' },
sint_64: { wireType: WireType.Varint, defaultValue: '0' },
bool: { wireType: WireType.Varint, defaultValue: 'false' },
string: { wireType: WireType.LengthDelim, defaultValue: '""' },
bytes: { wireType: WireType.LengthDelim, defaultValue: 'new Uint8Array(0)' },
float: { wireType: WireType.Bit32, defaultValue: '0' },
double: { wireType: WireType.Bit64, defaultValue: '0' },
fixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
fixed_64: { wireType: WireType.Bit64, defaultValue: '0' },
sfixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
sfixed_64: { wireType: WireType.Bit64, defaultValue: '0' },
};
/** Marker identifiers recognised in type references */
export const PB_MARKER = 'pb';
export const PB_REPEATED_MARKER = 'pb_repeated';
+85
View File
@@ -0,0 +1,85 @@
import ts from 'typescript';
export type ImportedTypeNameResolver = (name: string) => string;
function identityImportedTypeName(name: string): string {
return name;
}
// Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in
// their own SourceFile, not in the caller's. Anyone that needs to read text or
// resolve imports against such a node must use the registered SF; otherwise
// `node.getText(callerSf)` reads garbage from the wrong buffer.
const syntheticTypeSourceFiles = new WeakMap<ts.TypeNode, ts.SourceFile>();
export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void {
syntheticTypeSourceFiles.set(node, sf);
}
export function resolveSourceFileForTypeNode(node: ts.TypeNode, fallback: ts.SourceFile): ts.SourceFile {
return syntheticTypeSourceFiles.get(node) ?? fallback;
}
// TS 5.9+ removed ts.isKeywordTypeNode — manual kind-based check
const KEYWORD_TYPE_KINDS = new Set([
ts.SyntaxKind.StringKeyword,
ts.SyntaxKind.NumberKeyword,
ts.SyntaxKind.BooleanKeyword,
ts.SyntaxKind.AnyKeyword,
ts.SyntaxKind.VoidKeyword,
ts.SyntaxKind.UndefinedKeyword,
ts.SyntaxKind.NullKeyword,
ts.SyntaxKind.NeverKeyword,
ts.SyntaxKind.UnknownKeyword,
ts.SyntaxKind.BigIntKeyword,
ts.SyntaxKind.SymbolKeyword,
ts.SyntaxKind.ObjectKeyword,
]);
export function isKeywordTypeNode(node: ts.Node): boolean {
return KEYWORD_TYPE_KINDS.has(node.kind);
}
export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver {
const localToImported = new Map<string, string>();
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
const bindings = stmt.importClause.namedBindings;
if (!bindings || !ts.isNamedImports(bindings)) continue;
for (const el of bindings.elements) {
localToImported.set(el.name.text, (el.propertyName ?? el.name).text);
}
}
return (name: string) => localToImported.get(name) ?? name;
}
/**
* Deterministic mangled name for a type node.
* `Foo` → `Foo`
* `Foo<string>` → `Foo__string`
* `Foo<Bar<uint_32>>` → `Foo__Bar__uint_32`
*
* If `typeNode` is a synthetic node produced by wrapper-binding instantiation,
* its registered source file is used automatically so `getText()` returns
* the substituted type text rather than garbage from `sf`.
*/
export function typeNodeToMangledName(
typeNode: ts.TypeNode,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): string {
const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf);
if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
const base = resolveImportedTypeName(typeNode.typeName.text);
if (typeNode.typeArguments && typeNode.typeArguments.length > 0) {
const args = typeNode.typeArguments.map(a => typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName));
return base + '__' + args.join('__');
}
return base;
}
if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf);
return typeNode.getText(effectiveSf);
}
+154
View File
@@ -0,0 +1,154 @@
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js';
function tagValue(field: ProtobufField): number {
const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes'
? WireType.LengthDelim
: field.wireType;
return ((field.fieldNumber << 3) | wireType) >>> 0;
}
/** Emit inline varint decode, storing result in `varName`. */
function varintDec(varName: string, ind: string): string {
return [
`${ind}let ${varName} = data[offset++];`,
`${ind}if (${varName} & 0x80) {`,
`${ind} let _s = 7, _b;`,
`${ind} ${varName} &= 0x7f;`,
`${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`,
`${ind}}`,
].join('\n');
}
function varintDec64(varName: string, ind: string): string {
return [
`${ind}let ${varName} = 0n, _s = 0n, _b;`,
`${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`,
].join('\n');
}
function isVarint64(typeName: string): boolean {
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
}
function isFixed64BigInt(typeName: string): boolean {
return typeName === 'fixed_64' || typeName === 'sfixed_64';
}
const INLINE_SKIP = [
` const wireType = _tag & 0x7;`,
` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`,
` else if (wireType === 1) offset += 8;`,
` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`,
` else if (wireType === 5) offset += 4;`,
].join('\n');
export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
const locals = msg.fields.map((field, index) => {
const keyword = field.isRepeated ? 'const' : 'let';
return ` ${keyword} _f${index} = ${getDefault(field)};`;
});
const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', ');
const L = [
`function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`,
...locals,
` while (offset < end) {`,
` let _tag = data[offset++];`,
` if (_tag & 0x80) {`,
` let _ts = 7, _tb;`,
` _tag &= 0x7f;`,
` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`,
` }`,
` switch (_tag) {`,
];
msg.fields.forEach((field, index) => {
L.push(decodeField(field, index));
});
L.push(
` default: {`,
INLINE_SKIP,
` break;`,
` }`,
` }`,
` }`,
` return { ${result} };`,
`}`,
);
return L.join('\n');
}
function decodeField(field: ProtobufField, index: number): string {
const { typeName, wireType, isMessage, isRepeated } = field;
const I = ' ';
const local = `_f${index}`;
const assign = (expr: string) => isRepeated
? `${I}${local}.push(${expr});`
: `${I}${local} = ${expr};`;
const L: string[] = [` case ${tagValue(field)}: {`];
if (isMessage) {
L.push(varintDec('_len', I));
L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`));
L.push(`${I}offset += _len;`);
} else if (typeName === 'string') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = offset + _len;`);
L.push(assign(`__td.decode(data.subarray(offset, _end))`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bytes') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = offset + _len;`);
L.push(assign(`data.slice(offset, _end)`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bool') {
L.push(varintDec('_val', I));
L.push(assign(`_val !== 0`));
} else if (isVarint64(typeName)) {
L.push(varintDec64('_val', I));
if (typeName === 'uint_64') {
L.push(assign(`_val`));
} else if (typeName === 'int_64') {
L.push(assign(`BigInt.asIntN(64, _val)`));
} else {
L.push(assign(`__zigZagDecode64(_val)`));
}
} else if (typeName === 'sint_32') {
L.push(varintDec('_val', I));
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
} else if (wireType === WireType.Varint) {
L.push(varintDec('_val', I));
L.push(assign(`_val >>> 0`));
} else if (typeName === 'float') {
L.push(assign(`__readFloat32(data, offset)`));
L.push(`${I}offset += 4;`);
} else if (wireType === WireType.Bit32) {
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 4;`);
} else if (typeName === 'double') {
L.push(assign(`__readFloat64(data, offset)`));
L.push(`${I}offset += 8;`);
} else if (isFixed64BigInt(typeName)) {
if (typeName === 'fixed_64') {
L.push(assign(`__readFixed64(data, offset)`));
} else {
L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`));
}
L.push(`${I}offset += 8;`);
} else if (wireType === WireType.Bit64) {
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 8;`);
}
L.push(`${I}break;`, ` }`);
return L.join('\n');
}
function getDefault(field: ProtobufField): string {
if (field.isRepeated) return '[]';
if (field.isOptional || field.isMessage) return 'null';
const primitive = PRIMITIVE_TYPE_MAP[field.typeName];
return primitive ? primitive.defaultValue : 'null';
}
+590
View File
@@ -0,0 +1,590 @@
import { WireType, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js';
/**
* Pre-compute tag bytes at codegen time.
* Field 1 + Varint(0) -> [0x08], Field 1 + LenDelim(2) -> [0x0a], etc.
*/
function computeTagBytes(fieldNumber: number, wireType: number): number[] {
let value = ((fieldNumber << 3) | wireType) >>> 0;
const bytes: number[] = [];
while (value > 0x7f) {
bytes.push((value & 0x7f) | 0x80);
value >>>= 7;
}
bytes.push(value & 0x7f);
return bytes;
}
function writeTag(fieldNumber: number, wireType: number, ind: string): string {
return computeTagBytes(fieldNumber, wireType)
.map(byte => `${ind}buf[offset++] = ${byte};`)
.join('\n');
}
function varintSize(varName: string, ind: string): string {
return `${ind}size += ${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`;
}
function writeVarint(expr: string, ind: string): string {
return [
`${ind}let _v = ${expr};`,
`${ind}if (_v < 0x80) {`,
`${ind} buf[offset++] = _v;`,
`${ind}} else if (_v < 0x4000) {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 7;`,
`${ind}} else if (_v < 0x200000) {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 14;`,
`${ind}} else if (_v < 0x10000000) {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 21;`,
`${ind}} else {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 28;`,
`${ind}}`,
].join('\n');
}
function isVarint64(typeName: string): boolean {
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
}
function isFixed64BigInt(typeName: string): boolean {
return typeName === 'fixed_64' || typeName === 'sfixed_64';
}
function bigintVarintExpr(typeName: string, expr: string): string {
if (typeName === 'uint_64') return `BigInt.asUintN(64, ${expr})`;
if (typeName === 'int_64') return `BigInt.asUintN(64, ${expr})`;
return `__zigZagEncode64(${expr})`;
}
interface EncoderBlock {
declare: string[];
size: string[];
write: string[];
}
export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
const blocks = msg.fields.map((field, index) => field.isRepeated ? buildRepeatedBlock(field, index) : buildSingularBlock(field, index));
const L = [
`function protobuf_encode_${msg.name}(obj) {`,
` let size = 0;`,
...blocks.flatMap(block => block.declare),
...blocks.flatMap(block => block.size),
` const buf = new Uint8Array(size);`,
` let offset = 0;`,
...blocks.flatMap(block => block.write),
` return buf;`,
`}`,
];
return L.join('\n');
}
function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock {
const { name, fieldNumber, typeName, wireType, isMessage } = field;
const valueVar = `_f${index}`;
const cacheVar = `_c${index}`;
const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length;
if (isMessage) {
return {
declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`],
size: [
` if (${valueVar} != null) {`,
` ${cacheVar} = protobuf_encode_${typeName}(${valueVar});`,
` const _len = ${cacheVar}.length;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
],
write: [
` if (${valueVar} != null) {`,
` const _data = ${cacheVar};`,
writeTag(fieldNumber, 2, ' '),
` const _len = _data.length;`,
writeVarint('_len', ' '),
` buf.set(_data, offset);`,
` offset += _len;`,
` }`,
],
};
}
if (typeName === 'string') {
return {
declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`],
size: [
` if (${valueVar} != null && ${valueVar} !== "") {`,
` ${cacheVar} = __utf8Len(${valueVar});`,
` const _len = ${cacheVar};`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar} !== "") {`,
writeTag(fieldNumber, 2, ' '),
` const _len = ${cacheVar};`,
writeVarint('_len', ' '),
` offset = __utf8Write(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (typeName === 'bytes') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [
` if (${valueVar} != null && ${valueVar}.length > 0) {`,
` const _len = ${valueVar}.length;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar}.length > 0) {`,
writeTag(fieldNumber, 2, ' '),
` const _len = ${valueVar}.length;`,
writeVarint('_len', ' '),
` buf.set(${valueVar}, offset);`,
` offset += _len;`,
` }`,
],
};
}
if (typeName === 'bool') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} === true) size += ${tagLength + 1};`],
write: [
` if (${valueVar} === true) {`,
writeTag(fieldNumber, 0, ' '),
` buf[offset++] = 1;`,
` }`,
],
};
}
if (isVarint64(typeName)) {
const bigintExpr = bigintVarintExpr(typeName, valueVar);
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
` const _val = ${bigintExpr};`,
` size += ${tagLength};`,
` size += __varint64Size(_val);`,
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
` const _val = ${bigintExpr};`,
writeTag(fieldNumber, 0, ' '),
` offset = __writeVarint64(buf, offset, _val);`,
` }`,
],
};
}
if (typeName === 'sint_32') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '),
` }`,
],
};
}
if (wireType === WireType.Varint) {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
` const _val = ${valueVar} >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`${valueVar} >>> 0`, ' '),
` }`,
],
};
}
if (typeName === 'float') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 5, ' '),
` offset = __writeFloat32(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (wireType === WireType.Bit32) {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 5, ' '),
` const _val = ${valueVar};`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` }`,
],
};
}
if (typeName === 'double') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFloat64(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (isFixed64BigInt(typeName)) {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0n) size += ${tagLength + 8};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFixed64(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (wireType === WireType.Bit64) {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 1, ' '),
` const _val = ${valueVar};`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` }`,
],
};
}
return { declare: [], size: [], write: [] };
}
function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock {
const { name, fieldNumber, typeName, wireType, isMessage } = field;
const arrayVar = `_f${index}`;
const cacheVar = `_c${index}`;
const tagWireType = isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType;
const tagLength = computeTagBytes(fieldNumber, tagWireType).length;
if (isMessage) {
return {
declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` ${cacheVar} = new Array(${arrayVar}.length);`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _data = protobuf_encode_${typeName}(${arrayVar}[_i]);`,
` ${cacheVar}[_i] = _data;`,
` const _len = _data.length;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _data = ${cacheVar}[_i];`,
writeTag(fieldNumber, 2, ' '),
` const _len = _data.length;`,
writeVarint('_len', ' '),
` buf.set(_data, offset);`,
` offset += _len;`,
` }`,
` }`,
],
};
}
if (typeName === 'string') {
return {
declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` ${cacheVar} = new Array(${arrayVar}.length);`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _len = __utf8Len(${arrayVar}[_i]);`,
` ${cacheVar}[_i] = _len;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _len = ${cacheVar}[_i];`,
writeTag(fieldNumber, 2, ' '),
writeVarint('_len', ' '),
` offset = __utf8Write(buf, offset, ${arrayVar}[_i]);`,
` }`,
` }`,
],
};
}
if (typeName === 'bytes') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _data = ${arrayVar}[_i];`,
` const _len = _data.length;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _data = ${arrayVar}[_i];`,
writeTag(fieldNumber, 2, ' '),
` const _len = _data.length;`,
writeVarint('_len', ' '),
` buf.set(_data, offset);`,
` offset += _len;`,
` }`,
` }`,
],
};
}
if (typeName === 'bool') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 1};`],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 0, ' '),
` buf[offset++] = ${arrayVar}[_i] ? 1 : 0;`,
` }`,
` }`,
],
};
}
if (isVarint64(typeName)) {
const bigintExpr = bigintVarintExpr(typeName, `${arrayVar}[_i]`);
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _val = ${bigintExpr};`,
` size += ${tagLength};`,
` size += __varint64Size(_val);`,
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _val = ${bigintExpr};`,
writeTag(fieldNumber, 0, ' '),
` offset = __writeVarint64(buf, offset, _val);`,
` }`,
` }`,
],
};
}
if (typeName === 'sint_32') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _val = ((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0`, ' '),
` }`,
` }`,
],
};
}
if (wireType === WireType.Varint) {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _val = ${arrayVar}[_i] >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`${arrayVar}[_i] >>> 0`, ' '),
` }`,
` }`,
],
};
}
if (typeName === 'float') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 5, ' '),
` offset = __writeFloat32(buf, offset, ${arrayVar}[_i]);`,
` }`,
` }`,
],
};
}
if (wireType === WireType.Bit32) {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 5, ' '),
` const _val = ${arrayVar}[_i];`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` }`,
` }`,
],
};
}
if (typeName === 'double') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFloat64(buf, offset, ${arrayVar}[_i]);`,
` }`,
` }`,
],
};
}
if (isFixed64BigInt(typeName)) {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFixed64(buf, offset, ${arrayVar}[_i]);`,
` }`,
` }`,
],
};
}
if (wireType === WireType.Bit64) {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 1, ' '),
` const _val = ${arrayVar}[_i];`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` }`,
` }`,
],
};
}
return { declare: [], size: [], write: [] };
}
+171
View File
@@ -0,0 +1,171 @@
import type { MessageRegistry } from '../ast/types.js';
import { generateEncoder } from './encoder.js';
import { generateDecoder } from './decoder.js';
/** Shared preamble: UTF-8 string helpers plus TextDecoder for decode. */
const CODEGEN_PREAMBLE = `const __td = new TextDecoder();
const __scratch = new DataView(new ArrayBuffer(8));
function __utf8Len(value) {
let length = 0;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (code < 0x80) {
length++;
continue;
}
if (code < 0x800) {
length += 2;
continue;
}
if ((code & 0xfc00) === 0xd800) {
if (i + 1 < value.length) {
const next = value.charCodeAt(i + 1);
if ((next & 0xfc00) === 0xdc00) {
length += 4;
i++;
continue;
}
}
length += 3;
continue;
}
if ((code & 0xfc00) === 0xdc00) {
length += 3;
continue;
}
length += 3;
}
return length;
}
function __utf8Write(buf, offset, value) {
for (let i = 0; i < value.length; i++) {
let code = value.charCodeAt(i);
if (code < 0x80) {
buf[offset++] = code;
continue;
}
if (code < 0x800) {
buf[offset++] = 0xc0 | (code >> 6);
buf[offset++] = 0x80 | (code & 0x3f);
continue;
}
if ((code & 0xfc00) === 0xd800) {
if (i + 1 < value.length) {
const next = value.charCodeAt(i + 1);
if ((next & 0xfc00) === 0xdc00) {
const point = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000;
buf[offset++] = 0xf0 | (point >> 18);
buf[offset++] = 0x80 | ((point >> 12) & 0x3f);
buf[offset++] = 0x80 | ((point >> 6) & 0x3f);
buf[offset++] = 0x80 | (point & 0x3f);
i++;
continue;
}
}
code = 0xfffd;
} else if ((code & 0xfc00) === 0xdc00) {
code = 0xfffd;
}
buf[offset++] = 0xe0 | (code >> 12);
buf[offset++] = 0x80 | ((code >> 6) & 0x3f);
buf[offset++] = 0x80 | (code & 0x3f);
}
return offset;
}
function __varint64Size(value) {
let size = 1;
while (value > 0x7fn) {
value >>= 7n;
size++;
}
return size;
}
function __writeVarint64(buf, offset, value) {
while (value > 0x7fn) {
buf[offset++] = Number((value & 0x7fn) | 0x80n);
value >>= 7n;
}
buf[offset++] = Number(value);
return offset;
}
function __zigZagEncode64(value) {
value = BigInt.asIntN(64, value);
return BigInt.asUintN(64, (value << 1n) ^ (value >> 63n));
}
function __zigZagDecode64(value) {
return BigInt.asIntN(64, (value >> 1n) ^ -(value & 1n));
}
function __writeFloat32(buf, offset, value) {
__scratch.setFloat32(0, value, true);
buf[offset++] = __scratch.getUint8(0);
buf[offset++] = __scratch.getUint8(1);
buf[offset++] = __scratch.getUint8(2);
buf[offset++] = __scratch.getUint8(3);
return offset;
}
function __readFloat32(data, offset) {
__scratch.setUint8(0, data[offset]);
__scratch.setUint8(1, data[offset + 1]);
__scratch.setUint8(2, data[offset + 2]);
__scratch.setUint8(3, data[offset + 3]);
return __scratch.getFloat32(0, true);
}
function __writeFloat64(buf, offset, value) {
__scratch.setFloat64(0, value, true);
buf[offset++] = __scratch.getUint8(0);
buf[offset++] = __scratch.getUint8(1);
buf[offset++] = __scratch.getUint8(2);
buf[offset++] = __scratch.getUint8(3);
buf[offset++] = __scratch.getUint8(4);
buf[offset++] = __scratch.getUint8(5);
buf[offset++] = __scratch.getUint8(6);
buf[offset++] = __scratch.getUint8(7);
return offset;
}
function __readFloat64(data, offset) {
__scratch.setUint8(0, data[offset]);
__scratch.setUint8(1, data[offset + 1]);
__scratch.setUint8(2, data[offset + 2]);
__scratch.setUint8(3, data[offset + 3]);
__scratch.setUint8(4, data[offset + 4]);
__scratch.setUint8(5, data[offset + 5]);
__scratch.setUint8(6, data[offset + 6]);
__scratch.setUint8(7, data[offset + 7]);
return __scratch.getFloat64(0, true);
}
function __writeFixed64(buf, offset, value) {
value = BigInt.asUintN(64, value);
buf[offset++] = Number(value & 0xffn);
buf[offset++] = Number((value >> 8n) & 0xffn);
buf[offset++] = Number((value >> 16n) & 0xffn);
buf[offset++] = Number((value >> 24n) & 0xffn);
buf[offset++] = Number((value >> 32n) & 0xffn);
buf[offset++] = Number((value >> 40n) & 0xffn);
buf[offset++] = Number((value >> 48n) & 0xffn);
buf[offset++] = Number((value >> 56n) & 0xffn);
return offset;
}
function __readFixed64(data, offset) {
return BigInt(data[offset])
| (BigInt(data[offset + 1]) << 8n)
| (BigInt(data[offset + 2]) << 16n)
| (BigInt(data[offset + 3]) << 24n)
| (BigInt(data[offset + 4]) << 32n)
| (BigInt(data[offset + 5]) << 40n)
| (BigInt(data[offset + 6]) << 48n)
| (BigInt(data[offset + 7]) << 56n);
}`;
/**
* Generate fully self-contained encode/decode source code.
* No runtime imports needed — all wire-format logic is inlined.
*/
export function generateCode(registry: MessageRegistry): string {
if (registry.size === 0) return '';
const parts: string[] = [CODEGEN_PREAMBLE];
for (const msg of registry.values()) {
parts.push(generateEncoder(msg, registry));
parts.push(generateDecoder(msg, registry));
}
return parts.join('\n');
}
+52
View File
@@ -0,0 +1,52 @@
// Protobuf wire format helpers — used directly by wire.test.ts
// The generated code no longer depends on these (everything is inlined).
export function encodeVarint(value: number, buf: number[]): void {
value = value >>> 0;
while (value > 0x7f) {
buf.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
buf.push(value & 0x7f);
}
export function decodeVarint(data: Uint8Array, offset: number): [number, number] {
let result = 0;
let shift = 0;
let byte: number;
do {
byte = data[offset++];
result |= (byte & 0x7f) << shift;
shift += 7;
} while (byte & 0x80);
return [result >>> 0, offset];
}
export function writeTag(fieldNumber: number, wireType: number, buf: number[]): void {
encodeVarint((fieldNumber << 3) | wireType, buf);
}
export function writeString(value: string, buf: number[]): void {
const encoded = new TextEncoder().encode(value);
encodeVarint(encoded.length, buf);
for (let i = 0; i < encoded.length; i++) buf.push(encoded[i]);
}
export function readString(data: Uint8Array, offset: number, length: number): string {
return new TextDecoder().decode(data.subarray(offset, offset + length));
}
export function writeBytes(value: Uint8Array, buf: number[]): void {
encodeVarint(value.length, buf);
for (let i = 0; i < value.length; i++) buf.push(value[i]);
}
export function skipField(data: Uint8Array, offset: number, wireType: number): number {
switch (wireType) {
case 0: while (data[offset] & 0x80) offset++; return offset + 1;
case 1: return offset + 8;
case 2: { const [len, o] = decodeVarint(data, offset); return o + len; }
case 5: return offset + 4;
default: throw new Error(`Unknown wire type: ${wireType}`);
}
}
+113
View File
@@ -0,0 +1,113 @@
import type { Plugin } from 'vite';
import { analyze, analyzeSource, selectUsedRegistry, typeNodeToMangledName } from './ast/analyzer.js';
import { generateCode } from './codegen/generator.js';
import { applyReplacements, replaceCallSites } from './transform/replacer.js';
import type { MessageRegistry } from './ast/types.js';
import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
import { createRuntimeMap, type RuntimeMapCallSite } from './runtime-map.js';
export interface ProtobufRuntimeMapPluginOptions {
enabled?: boolean;
fileName?: string;
}
export interface ProtobufVitePluginOptions {
runtimeMap?: ProtobufRuntimeMapPluginOptions;
}
interface RuntimeMapFileEntry {
messages: MessageRegistry;
callSites: RuntimeMapCallSite[];
}
export default function protobufVitePlugin(options: ProtobufVitePluginOptions = {}): Plugin {
const fileCache = new Map<string, ParsedFileEntry>();
const runtimeMapByFile = new Map<string, RuntimeMapFileEntry>();
const runtimeMapEnabled = options.runtimeMap?.enabled === true;
const runtimeMapFileName = options.runtimeMap?.fileName ?? 'snowluma-proton.runtime-map.json';
return {
name: 'vite-plugin-protobuf',
enforce: 'pre',
transform(code, id) {
const cleanId = id.split('?')[0];
if (!cleanId.endsWith('.ts') || cleanId.endsWith('.d.ts')) return null;
const imported = resolveImports(code, cleanId, fileCache);
const { registry, callSites, sourceFile } = analyze(code, cleanId, imported);
if (registry.size === 0 && callSites.length === 0) return null;
const used = selectUsedRegistry(registry, callSites, sourceFile);
if (used.registry.size === 0) {
runtimeMapByFile.delete(cleanId);
return null;
}
if (runtimeMapEnabled) {
runtimeMapByFile.set(cleanId, {
messages: used.registry,
callSites: used.callSites.map(cs => ({
file: cleanId,
line: cs.line,
column: cs.column,
fnName: cs.fnName as RuntimeMapCallSite['fnName'],
typeName: cs.typeName,
})),
});
}
const generatedCode = generateCode(used.registry);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
if (!hasReplacements && generatedCode === '') return null;
return { code: generatedCode + '\n' + transformedCode, map: null };
},
handleHotUpdate({ file }) {
if (file.endsWith('.ts')) {
fileCache.delete(file);
runtimeMapByFile.delete(file);
}
},
generateBundle() {
if (!runtimeMapEnabled) return;
const mergedMessages: MessageRegistry = new Map();
const mergedCallSites: RuntimeMapCallSite[] = [];
for (const entry of runtimeMapByFile.values()) {
for (const [name, msg] of entry.messages) mergedMessages.set(name, msg);
mergedCallSites.push(...entry.callSites);
}
if (mergedMessages.size === 0 || mergedCallSites.length === 0) return;
const runtimeMap = createRuntimeMap({
messages: mergedMessages,
callSites: mergedCallSites,
});
this.emitFile({
type: 'asset',
fileName: runtimeMapFileName,
source: JSON.stringify(runtimeMap, null, 2),
});
},
};
}
export {
analyze,
analyzeSource,
generateCode,
replaceCallSites,
applyReplacements,
typeNodeToMangledName,
resolveImports,
selectUsedRegistry,
createRuntimeMap,
};
export type { ProtobufRuntimeMap, RuntimeMapCallSite } from './runtime-map.js';
+71
View File
@@ -0,0 +1,71 @@
import type { MessageRegistry, ProtobufField, ProtobufMessage } from './ast/types.js';
export type RuntimeMapFnName = 'protobuf_encode' | 'protobuf_decode';
export interface RuntimeMapCallSite {
file: string;
line: number;
column: number;
fnName: RuntimeMapFnName;
typeName: string;
}
export interface ProtobufRuntimeMap {
version: 1;
messages: ProtobufMessage[];
callSites: RuntimeMapCallSite[];
}
function cloneField(field: ProtobufField): ProtobufField {
return {
name: field.name,
fieldNumber: field.fieldNumber,
typeName: field.typeName,
wireType: field.wireType,
isMessage: field.isMessage,
isOptional: field.isOptional,
isRepeated: field.isRepeated,
};
}
function cloneMessage(msg: ProtobufMessage): ProtobufMessage {
return {
name: msg.name,
fields: msg.fields.map(cloneField),
};
}
export function registryToRuntimeMapMessages(registry: MessageRegistry): ProtobufMessage[] {
return [...registry.values()].map(cloneMessage);
}
export function runtimeMapToRegistry(map: ProtobufRuntimeMap): MessageRegistry {
const registry: MessageRegistry = new Map();
for (const msg of map.messages) {
registry.set(msg.name, cloneMessage(msg));
}
return registry;
}
export function normalizeRuntimeMapPath(filePath: string): string {
const noQuery = filePath.replace(/[?#].*$/, '');
return noQuery.replace(/\\/g, '/').replace(/^file:\/\//, '');
}
export function createRuntimeMap(map: { messages: MessageRegistry; callSites: RuntimeMapCallSite[] }): ProtobufRuntimeMap {
const dedupedCallSites = new Map<string, RuntimeMapCallSite>();
for (const cs of map.callSites) {
const normalized = {
...cs,
file: normalizeRuntimeMapPath(cs.file),
};
const key = `${normalized.file}:${normalized.line}:${normalized.column}:${normalized.fnName}:${normalized.typeName}`;
dedupedCallSites.set(key, normalized);
}
return {
version: 1,
messages: registryToRuntimeMapMessages(map.messages),
callSites: [...dedupedCallSites.values()],
};
}
+220
View File
@@ -0,0 +1,220 @@
/**
* Runtime fallback functions.
* If the Vite plugin is active, calls to protobuf_encode/decode are replaced
* at compile-time with generated type-specific functions.
* If NOT transformed, these fallbacks throw to alert the developer.
*/
import type { MessageRegistry } from './ast/types.js';
import { buildDependencyRegistry } from './ast/dependency-graph.js';
import { generateCode } from './codegen/generator.js';
import {
normalizeRuntimeMapPath,
runtimeMapToRegistry,
type ProtobufRuntimeMap,
type RuntimeMapCallSite,
type RuntimeMapFnName,
} from './runtime-map.js';
type DynamicEncode = (params: unknown) => Uint8Array;
type DynamicDecode = (data: Uint8Array) => unknown;
interface DynamicTypeFns {
encode?: DynamicEncode;
decode?: DynamicDecode;
}
interface StackFrame {
file: string;
line: number;
column: number;
}
const DYNAMIC_MISS = Symbol('snowluma-proton-dynamic-miss');
let runtimeMapFallback: ProtobufRuntimeMap | null = null;
let runtimeMapRegistry: MessageRegistry | null = null;
let runtimeMapCallSites: RuntimeMapCallSite[] = [];
const dynamicTypeCache = new Map<string, DynamicTypeFns>();
/**
* Enable dynamic runtime fallback from a pre-collected map file.
* This is disabled by default.
*/
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void {
runtimeMapFallback = map;
runtimeMapRegistry = runtimeMapToRegistry(map);
runtimeMapCallSites = map.callSites.map(cs => ({
...cs,
file: normalizeRuntimeMapPath(cs.file),
}));
dynamicTypeCache.clear();
}
/** Disable dynamic runtime fallback and clear all generated function caches. */
export function protobuf_disableRuntimeMapFallback(): void {
runtimeMapFallback = null;
runtimeMapRegistry = null;
runtimeMapCallSites = [];
dynamicTypeCache.clear();
}
export function protobuf_encode<T>(_params: T): Uint8Array {
const dynamic = tryDynamicInvoke('protobuf_encode', _params);
if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array;
throw new Error(
'protobuf_encode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
);
}
export function protobuf_decode<T>(_data: Uint8Array): T {
const dynamic = tryDynamicInvoke('protobuf_decode', _data);
if (dynamic !== DYNAMIC_MISS) return dynamic as T;
throw new Error(
'protobuf_decode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
);
}
function tryDynamicInvoke(fnName: RuntimeMapFnName, payload: unknown): unknown {
if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) {
return DYNAMIC_MISS;
}
const caller = getFirstUserFrame();
if (!caller) return DYNAMIC_MISS;
const callSite = resolveCallSite(fnName, caller);
if (!callSite) return DYNAMIC_MISS;
const typeFns = ensureTypeFunctions(callSite.typeName);
if (!typeFns) return DYNAMIC_MISS;
const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode;
if (typeof fn !== 'function') return DYNAMIC_MISS;
return fn(payload as never);
}
function ensureTypeFunctions(typeName: string): DynamicTypeFns | null {
const cached = dynamicTypeCache.get(typeName);
if (cached) return cached;
if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null;
const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]);
if (subset.size === 0) return null;
const generated = generateCode(subset);
if (!generated) return null;
const factory = new Function(
`${generated}\nreturn {\n` +
` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` +
` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` +
`};`,
) as () => DynamicTypeFns;
const compiled = factory();
dynamicTypeCache.set(typeName, compiled);
return compiled;
}
function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeMapCallSite | null {
const callerFile = normalizeRuntimeMapPath(caller.file);
const candidates = runtimeMapCallSites.filter(cs =>
cs.fnName === fnName &&
cs.line === caller.line &&
pathsLikelySame(callerFile, cs.file),
);
if (candidates.length === 0) return null;
if (candidates.length === 1) return candidates[0];
let best = candidates[0];
let bestDistance = Math.abs(best.column - caller.column);
for (let i = 1; i < candidates.length; i++) {
const dist = Math.abs(candidates[i].column - caller.column);
if (dist < bestDistance) {
best = candidates[i];
bestDistance = dist;
}
}
return best;
}
function getFirstUserFrame(): StackFrame | null {
const err = new Error();
if (!err.stack) return null;
const lines = err.stack.split('\n').slice(1);
for (const raw of lines) {
const frame = parseStackLine(raw);
if (!frame) continue;
const file = normalizeRuntimeMapPath(frame.file);
if (isRuntimeInternalFile(file)) continue;
return {
file,
line: frame.line,
column: frame.column,
};
}
return null;
}
function parseStackLine(line: string): StackFrame | null {
const trimmed = line.trim();
if (!trimmed) return null;
let location = trimmed;
const atPrefix = 'at ';
if (location.startsWith(atPrefix)) {
location = location.slice(atPrefix.length).trim();
}
const openParen = location.lastIndexOf('(');
if (openParen >= 0 && location.endsWith(')')) {
location = location.slice(openParen + 1, -1);
}
const lastColon = location.lastIndexOf(':');
if (lastColon < 0) return null;
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
if (secondLastColon < 0) return null;
const file = location.slice(0, secondLastColon);
const linePart = location.slice(secondLastColon + 1, lastColon);
const colPart = location.slice(lastColon + 1);
const parsedLine = Number(linePart);
const parsedCol = Number(colPart);
if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) return null;
return {
file,
line: parsedLine,
column: parsedCol,
};
}
function isRuntimeInternalFile(file: string): boolean {
return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js');
}
function pathsLikelySame(a: string, b: string): boolean {
if (a === b) return true;
const aBase = basename(a);
const bBase = basename(b);
return aBase !== '' && aBase === bBase;
}
function basename(file: string): string {
const normalized = normalizeRuntimeMapPath(file);
const idx = normalized.lastIndexOf('/');
return idx >= 0 ? normalized.slice(idx + 1) : normalized;
}
+61
View File
@@ -0,0 +1,61 @@
import type { MessageRegistry } from '../ast/types.js';
import type { CallSiteRecord } from '../ast/analyzer.js';
import { createImportedTypeNameResolver, typeNodeToMangledName } from '../ast/utils.js';
import { collectProtobufImportBindings, matchProtobufCallSite } from '../ast/callsite.js';
import ts from 'typescript';
interface TextEdit { start: number; end: number; replacement: string }
/**
* Apply replacements using pre-recorded call-sites from analyze().
* No parsing or AST walking — just position-based string edits.
*/
export function applyReplacements(
code: string,
sf: ts.SourceFile,
callSites: CallSiteRecord[],
registry: MessageRegistry,
): { transformedCode: string; hasReplacements: boolean } {
const edits: TextEdit[] = [];
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
for (const cs of callSites) {
const mangled = typeNodeToMangledName(cs.firstTypeArg, sf, resolveImportedTypeName);
if (registry.has(mangled)) {
edits.push({
start: cs.exprStart,
end: cs.typeArgsEnd,
replacement: `${cs.fnName}_${mangled}`,
});
}
}
if (!edits.length) return { transformedCode: code, hasReplacements: false };
edits.sort((a, b) => b.start - a.start);
let result = code;
for (const ed of edits) result = result.slice(0, ed.start) + ed.replacement + result.slice(ed.end);
return { transformedCode: result, hasReplacements: true };
}
/**
* Backward-compatible: parses + walks on its own.
* Prefer applyReplacements() with pre-recorded call-sites from analyze().
*/
export function replaceCallSites(code: string, registry: MessageRegistry): { transformedCode: string; hasReplacements: boolean } {
const sf = ts.createSourceFile('input.ts', code, ts.ScriptTarget.Latest, true);
const callSites: CallSiteRecord[] = [];
const importBindings = collectProtobufImportBindings(sf);
ts.forEachChild(sf, function visit(node) {
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) callSites.push(cs);
}
ts.forEachChild(node, visit);
});
return applyReplacements(code, sf, callSites, registry);
}