lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
+351
-235
@@ -1,84 +1,111 @@
|
||||
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 {
|
||||
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,
|
||||
createImportedTypeNameResolver,
|
||||
typeNodeToMangledName,
|
||||
registerSyntheticTypeSourceFile,
|
||||
resolveSourceFileForTypeNode,
|
||||
} from './utils.js';
|
||||
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
|
||||
import {
|
||||
collectProtobufImportBindings,
|
||||
matchProtobufCallSite,
|
||||
type CanonicalProtobufFn,
|
||||
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;
|
||||
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,
|
||||
binding: WrapperBinding,
|
||||
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
|
||||
sf: ts.SourceFile,
|
||||
): ts.TypeNode | null {
|
||||
if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? 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));
|
||||
}
|
||||
let text = binding.typePattern;
|
||||
|
||||
// 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;
|
||||
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
|
||||
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;
|
||||
typeName: string;
|
||||
}
|
||||
|
||||
export interface AnalysisResult {
|
||||
registry: MessageRegistry;
|
||||
callSites: CallSiteRecord[];
|
||||
sourceFile: ts.SourceFile;
|
||||
registry: MessageRegistry;
|
||||
callSites: CallSiteRecord[];
|
||||
sourceFile: ts.SourceFile;
|
||||
}
|
||||
|
||||
export interface UsedRegistryResult {
|
||||
registry: MessageRegistry;
|
||||
roots: Set<string>;
|
||||
callSites: ResolvedCallSiteRecord[];
|
||||
registry: MessageRegistry;
|
||||
roots: Set<string>;
|
||||
callSites: ResolvedCallSiteRecord[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,171 +117,236 @@ export interface UsedRegistryResult {
|
||||
*
|
||||
* 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>();
|
||||
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);
|
||||
}
|
||||
// Seed with imported definitions
|
||||
if (imported) {
|
||||
concrete.push(...imported.concrete);
|
||||
|
||||
// Stack of generic-function type-param scopes. When visiting a
|
||||
// `protobuf_encode/decode<X>` call whose type arg references one of
|
||||
// these (e.g. `protobuf_encode<OidbBase<T>>(env)` inside
|
||||
// `function encodeOidbEnv<T>(...)`), we MUST skip monomorphization —
|
||||
// the type arg only resolves once the wrapper itself is instantiated
|
||||
// at a downstream call site, and that case is handled separately by
|
||||
// the wrapper-binding path in `matchForwardedProtobufFn`. Without
|
||||
// this skip, the analyzer would happily mint a literal `OidbBase__T`
|
||||
// registry entry with a `body.typeName = 'T'` field, which the
|
||||
// wire-type guard then trips on.
|
||||
const enclosingTypeParamStack: Set<string>[] = [];
|
||||
function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean {
|
||||
if (enclosingTypeParamStack.length === 0) return false;
|
||||
let found = false;
|
||||
function check(n: ts.Node): void {
|
||||
if (found) return;
|
||||
if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) {
|
||||
const name = n.typeName.text;
|
||||
for (const scope of enclosingTypeParamStack) {
|
||||
if (scope.has(name)) { found = true; return; }
|
||||
for (const [k, v] of imported.templates) {
|
||||
templates.set(k, v);
|
||||
}
|
||||
}
|
||||
ts.forEachChild(n, check);
|
||||
}
|
||||
check(typeArg);
|
||||
return found;
|
||||
}
|
||||
function nodeIntroducesTypeParams(n: ts.Node): readonly ts.TypeParameterDeclaration[] | undefined {
|
||||
if (ts.isFunctionDeclaration(n)) return n.typeParameters;
|
||||
if (ts.isFunctionExpression(n)) return n.typeParameters;
|
||||
if (ts.isArrowFunction(n)) return n.typeParameters;
|
||||
if (ts.isMethodDeclaration(n)) return n.typeParameters;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ── single walk ─────────────────────────────────────────────────────
|
||||
ts.forEachChild(sf, function visit(node) {
|
||||
const introduced = nodeIntroducesTypeParams(node);
|
||||
const pushedScope = !!(introduced && introduced.length);
|
||||
if (pushedScope) {
|
||||
enclosingTypeParamStack.push(new Set(introduced!.map(p => p.name.text)));
|
||||
}
|
||||
|
||||
try {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Stack of generic-function type-param scopes. When visiting a
|
||||
// `protobuf_encode/decode<X>` call whose type arg references one of
|
||||
// these (e.g. `protobuf_encode<OidbBase<T>>(env)` inside
|
||||
// `function encodeOidbEnv<T>(...)`), we MUST skip monomorphization —
|
||||
// the type arg only resolves once the wrapper itself is instantiated
|
||||
// at a downstream call site, and that case is handled separately by
|
||||
// the wrapper-binding path in `matchForwardedProtobufFn`. Without
|
||||
// this skip, the analyzer would happily mint a literal `OidbBase__T`
|
||||
// registry entry with a `body.typeName = 'T'` field, which the
|
||||
// wire-type guard then trips on.
|
||||
const enclosingTypeParamStack: Set<string>[] = [];
|
||||
|
||||
function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean {
|
||||
if (enclosingTypeParamStack.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let found = false;
|
||||
|
||||
function check(n: ts.Node): void {
|
||||
if (found) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) {
|
||||
const name = n.typeName.text;
|
||||
|
||||
for (const scope of enclosingTypeParamStack) {
|
||||
if (scope.has(name)) {
|
||||
found = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ts.forEachChild(n, check);
|
||||
}
|
||||
|
||||
check(typeArg);
|
||||
return found;
|
||||
}
|
||||
|
||||
function nodeIntroducesTypeParams(
|
||||
n: ts.Node,
|
||||
): readonly ts.TypeParameterDeclaration[] | undefined {
|
||||
if (ts.isFunctionDeclaration(n)) {
|
||||
return n.typeParameters;
|
||||
}
|
||||
|
||||
if (ts.isFunctionExpression(n)) {
|
||||
return n.typeParameters;
|
||||
}
|
||||
|
||||
if (ts.isArrowFunction(n)) {
|
||||
return n.typeParameters;
|
||||
}
|
||||
|
||||
if (ts.isMethodDeclaration(n)) {
|
||||
return n.typeParameters;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ── single walk ─────────────────────────────────────────────────────
|
||||
ts.forEachChild(sf, function visit(node) {
|
||||
const introduced = nodeIntroducesTypeParams(node);
|
||||
const pushedScope = !!(introduced && introduced.length);
|
||||
|
||||
if (pushedScope) {
|
||||
enclosingTypeParamStack.push(new Set(introduced!.map((p) => p.name.text)));
|
||||
}
|
||||
|
||||
try {
|
||||
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) {
|
||||
if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) {
|
||||
deferredTypeArgs.push(cs.firstTypeArg);
|
||||
callSites.push(cs);
|
||||
}
|
||||
// else: this call sits inside a generic wrapper definition; the
|
||||
// wrapper-binding path will materialise concrete codecs at each
|
||||
// downstream call site instead.
|
||||
} 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (ts.isCallExpression(node)) {
|
||||
const cs = matchProtobufCallSite(node, sf, importBindings, {
|
||||
allowLegacyUnboundCanonical: true,
|
||||
});
|
||||
if (cs) {
|
||||
if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) {
|
||||
deferredTypeArgs.push(cs.firstTypeArg);
|
||||
callSites.push(cs);
|
||||
}
|
||||
// else: this call sits inside a generic wrapper definition; the
|
||||
// wrapper-binding path will materialise concrete codecs at each
|
||||
// downstream call site instead.
|
||||
} 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,
|
||||
});
|
||||
} finally {
|
||||
if (pushedScope) {
|
||||
enclosingTypeParamStack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ts.forEachChild(node, visit);
|
||||
} finally {
|
||||
if (pushedScope) enclosingTypeParamStack.pop();
|
||||
// ── 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);
|
||||
}
|
||||
});
|
||||
|
||||
// ── 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.`,
|
||||
);
|
||||
}
|
||||
for (const m of mono.values()) {
|
||||
concrete.push(m);
|
||||
}
|
||||
}
|
||||
|
||||
return { registry: topoSort(concrete), callSites, sourceFile: sf };
|
||||
// ── 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;
|
||||
export function analyzeSource(
|
||||
code: string,
|
||||
filePath: string,
|
||||
imported?: ImportedDefinitions,
|
||||
): MessageRegistry {
|
||||
return analyze(code, filePath, imported).registry;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -262,54 +354,78 @@ export function analyzeSource(code: string, filePath: string, imported?: Importe
|
||||
* their transitive message dependencies.
|
||||
*/
|
||||
export function selectUsedRegistry(
|
||||
registry: MessageRegistry,
|
||||
callSites: CallSiteRecord[],
|
||||
sourceFile: ts.SourceFile,
|
||||
registry: MessageRegistry,
|
||||
callSites: CallSiteRecord[],
|
||||
sourceFile: ts.SourceFile,
|
||||
): UsedRegistryResult {
|
||||
const roots = new Set<string>();
|
||||
const resolved: ResolvedCallSiteRecord[] = [];
|
||||
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 });
|
||||
}
|
||||
const roots = new Set<string>();
|
||||
const resolved: ResolvedCallSiteRecord[] = [];
|
||||
|
||||
if (roots.size === 0) {
|
||||
return { registry: new Map(), roots, callSites: resolved };
|
||||
}
|
||||
for (const cs of callSites) {
|
||||
const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile);
|
||||
const typeName = typeNodeToMangledName(
|
||||
cs.firstTypeArg,
|
||||
typeSf,
|
||||
createImportedTypeNameResolver(typeSf),
|
||||
);
|
||||
|
||||
return {
|
||||
registry: buildDependencyRegistry(registry, roots),
|
||||
roots,
|
||||
callSites: resolved,
|
||||
};
|
||||
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 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>();
|
||||
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)!);
|
||||
}
|
||||
function dfs(name: string): void {
|
||||
if (visited.has(name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const m of messages) dfs(m.name);
|
||||
return new Map(sorted.map(m => [m.name, m]));
|
||||
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]));
|
||||
}
|
||||
@@ -3,117 +3,139 @@ 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',
|
||||
]);
|
||||
const PROTOBUF_RUNTIME_MODULES = new Set(['@snowluma/proton']);
|
||||
|
||||
export interface ProtobufImportBindings {
|
||||
identifierToCanonical: Map<string, CanonicalProtobufFn>;
|
||||
namespaceAliases: Set<string>;
|
||||
blockedLegacyCanonical: Set<CanonicalProtobufFn>;
|
||||
hasRuntimeImport: boolean;
|
||||
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;
|
||||
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;
|
||||
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;
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (CANONICAL.has(el.name.text as CanonicalProtobufFn)) {
|
||||
blockedLegacyCanonical.add(el.name.text as CanonicalProtobufFn);
|
||||
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);
|
||||
}
|
||||
}
|
||||
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 };
|
||||
return { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport };
|
||||
}
|
||||
|
||||
interface MatchOptions {
|
||||
allowLegacyUnboundCanonical?: boolean;
|
||||
allowLegacyUnboundCanonical?: boolean;
|
||||
}
|
||||
|
||||
export function matchProtobufCallSite(
|
||||
node: ts.CallExpression,
|
||||
sf: ts.SourceFile,
|
||||
bindings: ProtobufImportBindings,
|
||||
options?: MatchOptions,
|
||||
node: ts.CallExpression,
|
||||
sf: ts.SourceFile,
|
||||
bindings: ProtobufImportBindings,
|
||||
options?: MatchOptions,
|
||||
): ProtobufCallSite | null {
|
||||
const ta = node.typeArguments;
|
||||
if (!ta?.length) return null;
|
||||
const ta = node.typeArguments;
|
||||
|
||||
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;
|
||||
if (!ta?.length) {
|
||||
return null;
|
||||
}
|
||||
} 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);
|
||||
|
||||
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);
|
||||
if (!fnName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
fnName,
|
||||
exprStart,
|
||||
typeArgsEnd: ta.end + 1,
|
||||
firstTypeArg: ta[0],
|
||||
line: lc.line + 1,
|
||||
column: lc.character + 1,
|
||||
};
|
||||
const lc = sf.getLineAndCharacterOfPosition(exprStart);
|
||||
|
||||
return {
|
||||
fnName,
|
||||
exprStart,
|
||||
typeArgsEnd: ta.end + 1,
|
||||
firstTypeArg: ta[0],
|
||||
line: lc.line + 1,
|
||||
column: lc.character + 1,
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,22 @@
|
||||
import ts from 'typescript';
|
||||
import {
|
||||
WireType,
|
||||
PB_MARKER, PB_REPEATED_MARKER, PB_OPTIONAL_MARKER,
|
||||
type ProtobufField, type ProtobufMessage,
|
||||
type GenericProtobufTemplate, type GenericFieldTemplate,
|
||||
WireType,
|
||||
PB_MARKER,
|
||||
PB_REPEATED_MARKER,
|
||||
PB_OPTIONAL_MARKER,
|
||||
type ProtobufField,
|
||||
type ProtobufMessage,
|
||||
type GenericProtobufTemplate,
|
||||
type GenericFieldTemplate,
|
||||
} from './types.js';
|
||||
import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js';
|
||||
import {
|
||||
isKeywordTypeNode,
|
||||
typeNodeToMangledName,
|
||||
type ImportedTypeNameResolver,
|
||||
} from './utils.js';
|
||||
|
||||
function identityImportedTypeName(name: string): string {
|
||||
return name;
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -19,149 +27,218 @@ function identityImportedTypeName(name: string): string {
|
||||
* type; nested generic instantiations on its fields would otherwise be missed.)
|
||||
*/
|
||||
export function* collectConcreteFieldGenericTypeArgs(
|
||||
node: ts.InterfaceDeclaration,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
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;
|
||||
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,
|
||||
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);
|
||||
}
|
||||
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as
|
||||
// zero-field proto messages — proto3 wire format allows them and
|
||||
// downstream code routinely uses them for "this OIDB call has no
|
||||
// meaningful response body" placeholders. Interfaces that have
|
||||
// members but no pb-marked fields are NOT proto messages — they
|
||||
// belong to regular TS types and must stay unregistered to avoid
|
||||
// polluting the registry.
|
||||
if (fields.length === 0 && node.members.length > 0) return null;
|
||||
return { name: node.name.text, fields };
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as
|
||||
// zero-field proto messages — proto3 wire format allows them and
|
||||
// downstream code routinely uses them for "this OIDB call has no
|
||||
// meaningful response body" placeholders. Interfaces that have
|
||||
// members but no pb-marked fields are NOT proto messages — they
|
||||
// belong to regular TS types and must stay unregistered to avoid
|
||||
// polluting the registry.
|
||||
if (fields.length === 0 && node.members.length > 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { name: node.name.text, fields };
|
||||
}
|
||||
|
||||
/** Collect a generic interface template. */
|
||||
export function collectGenericInterface(
|
||||
node: ts.InterfaceDeclaration,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
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;
|
||||
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,
|
||||
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 && marker !== PB_OPTIONAL_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] };
|
||||
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 && marker !== PB_OPTIONAL_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,
|
||||
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);
|
||||
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);
|
||||
}
|
||||
return resolveImportedTypeName(node.typeName.text);
|
||||
}
|
||||
if (isKeywordTypeNode(node)) return node.getText(sf);
|
||||
return null;
|
||||
|
||||
if (isKeywordTypeNode(node)) {
|
||||
return node.getText(sf);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function extractField(
|
||||
member: ts.PropertySignature,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver,
|
||||
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,
|
||||
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
|
||||
};
|
||||
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,
|
||||
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
|
||||
};
|
||||
}
|
||||
|
||||
function extractGenericField(
|
||||
member: ts.PropertySignature,
|
||||
sf: ts.SourceFile,
|
||||
tpSet: Set<string>,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver,
|
||||
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,
|
||||
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
|
||||
};
|
||||
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,
|
||||
explicitPresence: parsed.marker === PB_OPTIONAL_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;
|
||||
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;
|
||||
}
|
||||
@@ -1,32 +1,57 @@
|
||||
import type { MessageRegistry } from './types.js';
|
||||
|
||||
export function collectDependencyClosure(registry: MessageRegistry, roots: Iterable<string>): Set<string> {
|
||||
const selected = new Set<string>();
|
||||
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;
|
||||
function visit(name: string): void {
|
||||
if (selected.has(name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
selected.add(name);
|
||||
for (const field of msg.fields) {
|
||||
if (registry.has(field.typeName)) visit(field.typeName);
|
||||
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;
|
||||
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 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);
|
||||
export function buildDependencyRegistry(
|
||||
registry: MessageRegistry,
|
||||
roots: Iterable<string>,
|
||||
): MessageRegistry {
|
||||
const selected = collectDependencyClosure(registry, roots);
|
||||
return pickRegistrySubset(registry, selected);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,15 +1,20 @@
|
||||
import ts from 'typescript';
|
||||
import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js';
|
||||
import {
|
||||
isKeywordTypeNode,
|
||||
createImportedTypeNameResolver,
|
||||
resolveSourceFileForTypeNode,
|
||||
type ImportedTypeNameResolver,
|
||||
typeNodeToMangledName,
|
||||
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;
|
||||
return name;
|
||||
}
|
||||
|
||||
/** Resolved value for a single template type parameter. */
|
||||
@@ -28,106 +33,141 @@ interface ResolvedTypeArg {
|
||||
* 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,
|
||||
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,
|
||||
explicitPresence: f.explicitPresence,
|
||||
};
|
||||
if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) {
|
||||
return null;
|
||||
}
|
||||
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,
|
||||
explicitPresence: f.explicitPresence,
|
||||
};
|
||||
});
|
||||
|
||||
out.set(mangledName, { name: mangledName, fields });
|
||||
return mangledName;
|
||||
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,
|
||||
explicitPresence: f.explicitPresence,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
explicitPresence: f.explicitPresence,
|
||||
};
|
||||
});
|
||||
|
||||
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,
|
||||
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;
|
||||
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;
|
||||
}
|
||||
@@ -1,80 +1,80 @@
|
||||
export enum WireType {
|
||||
Varint = 0,
|
||||
Bit64 = 1,
|
||||
LengthDelim = 2,
|
||||
Bit32 = 5,
|
||||
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;
|
||||
/**
|
||||
* Explicit presence (proto3 `optional`), set only by the `pb_optional<>`
|
||||
* marker. When true, a scalar field serialises even at its zero/default
|
||||
* value. Distinct from `isOptional` (which merely tracks the TS `?` and is
|
||||
* true for almost every field) — the encoder keys off THIS flag, never
|
||||
* `isOptional`, so existing `pb<>` fields are unaffected.
|
||||
*/
|
||||
explicitPresence: boolean;
|
||||
name: string;
|
||||
fieldNumber: number;
|
||||
typeName: string;
|
||||
wireType: WireType;
|
||||
isMessage: boolean;
|
||||
isOptional: boolean;
|
||||
isRepeated: boolean;
|
||||
/**
|
||||
* Explicit presence (proto3 `optional`), set only by the `pb_optional<>`
|
||||
* marker. When true, a scalar field serialises even at its zero/default
|
||||
* value. Distinct from `isOptional` (which merely tracks the TS `?` and is
|
||||
* true for almost every field) — the encoder keys off THIS flag, never
|
||||
* `isOptional`, so existing `pb<>` fields are unaffected.
|
||||
*/
|
||||
explicitPresence: boolean;
|
||||
}
|
||||
|
||||
export interface ProtobufMessage {
|
||||
name: string;
|
||||
fields: ProtobufField[];
|
||||
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[];
|
||||
name: string;
|
||||
typeParams: string[];
|
||||
fields: GenericFieldTemplate[];
|
||||
}
|
||||
|
||||
export interface GenericFieldTemplate {
|
||||
name: string;
|
||||
fieldNumber: number;
|
||||
rawTypeName: string;
|
||||
isTypeParam: boolean;
|
||||
isOptional: boolean;
|
||||
isRepeated: boolean;
|
||||
/** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */
|
||||
explicitPresence: 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;
|
||||
name: string;
|
||||
fieldNumber: number;
|
||||
rawTypeName: string;
|
||||
isTypeParam: boolean;
|
||||
isOptional: boolean;
|
||||
isRepeated: boolean;
|
||||
/** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */
|
||||
explicitPresence: 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' },
|
||||
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 */
|
||||
|
||||
@@ -3,7 +3,7 @@ import ts from 'typescript';
|
||||
export type ImportedTypeNameResolver = (name: string) => string;
|
||||
|
||||
function identityImportedTypeName(name: string): string {
|
||||
return name;
|
||||
return name;
|
||||
}
|
||||
|
||||
// Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in
|
||||
@@ -13,47 +13,56 @@ function identityImportedTypeName(name: string): string {
|
||||
const syntheticTypeSourceFiles = new WeakMap<ts.TypeNode, ts.SourceFile>();
|
||||
|
||||
export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void {
|
||||
syntheticTypeSourceFiles.set(node, sf);
|
||||
syntheticTypeSourceFiles.set(node, sf);
|
||||
}
|
||||
|
||||
export function resolveSourceFileForTypeNode(node: ts.TypeNode, fallback: ts.SourceFile): ts.SourceFile {
|
||||
return syntheticTypeSourceFiles.get(node) ?? fallback;
|
||||
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,
|
||||
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);
|
||||
return KEYWORD_TYPE_KINDS.has(node.kind);
|
||||
}
|
||||
|
||||
export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver {
|
||||
const localToImported = new Map<string, string>();
|
||||
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 stmt of sf.statements) {
|
||||
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const el of bindings.elements) {
|
||||
localToImported.set(el.name.text, (el.propertyName ?? el.name).text);
|
||||
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;
|
||||
return (name: string) => localToImported.get(name) ?? name;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,19 +76,28 @@ export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeN
|
||||
* the substituted type text rather than garbage from `sf`.
|
||||
*/
|
||||
export function typeNodeToMangledName(
|
||||
typeNode: ts.TypeNode,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
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('__');
|
||||
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;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf);
|
||||
return typeNode.getText(effectiveSf);
|
||||
|
||||
if (isKeywordTypeNode(typeNode)) {
|
||||
return typeNode.getText(effectiveSf);
|
||||
}
|
||||
|
||||
return typeNode.getText(effectiveSf);
|
||||
}
|
||||
Reference in new issue
Block a user