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:
62 files changed
+4714
No files matched your search
@@ -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]));
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user