Add text-edit utility and import resolution caches

Introduce a TextEdit type and applyTextEdits utility for safe, reverse-ordered string edits and refactor replacer to produce and consume edit lists (collectReplacementEdits) instead of performing manual slicing. Propagate ts.SourceFile through ParsedFileEntry/ImportedDefinitions and use cached extraction of imports/exports to avoid repeated AST traversal when resolving imports; analyzer now prefers an imported sourceFile when available. Wire text edits into the plugin pipeline (compose replacement + override edits) and remove the previous applyOverrideInsertions helper. Add a tsconfig lookup cache in program-cache to speed up upward tsconfig searches and invalidate it when the program cache is cleared. README updated to list the new files.
This commit is contained in:
手瓜一十雪 committed 2026-05-25 11:42:03 +08:00
1 parent 40c51bcd02
commit 93850ec11c
8 files changed
+95 -54

No files matched your search

+2
View File
@@ -294,6 +294,8 @@ src/
subclass-wrapper.ts extends 链遍历 + 类型参数解析
file-pipeline.ts 插件 transform() 使用的单文件胶水层
transform/ Vite 插件字符串编辑
replacer.ts protobuf 调用替换编辑收集
text-edits.ts 通用倒序文本编辑应用
index.ts 插件入口 (./vite)
runtime.ts 运行时桩代码 (.)
+1 -1
View File
@@ -55,7 +55,7 @@ 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 sf = imported?.sourceFile ?? ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true);
const concrete: ProtobufMessage[] = [];
const templates = new Map<string, GenericProtobufTemplate>();
const mono = new Map<string, ProtobufMessage>();
+21 -2
View File
@@ -11,6 +11,7 @@ export type { WrapperBinding } from './wrapper-binding.js';
export interface ParsedFileEntry {
filePath: string;
sourceFile: ts.SourceFile;
concrete: ProtobufMessage[];
templates: Map<string, GenericProtobufTemplate>;
importedTypeSources: Map<string, string>;
@@ -20,6 +21,7 @@ export interface ParsedFileEntry {
}
export interface ImportedDefinitions {
sourceFile: ts.SourceFile;
concrete: ProtobufMessage[];
templates: Map<string, GenericProtobufTemplate>;
wrapperBindings: Map<string, WrapperBinding>;
@@ -31,8 +33,15 @@ interface ImportClause {
specifier: string;
}
const importClausesCache = new WeakMap<ts.SourceFile, ImportClause[]>();
const valueImportClausesCache = new WeakMap<ts.SourceFile, ImportClause[]>();
const exportAllSpecifiersCache = new WeakMap<ts.SourceFile, string[]>();
/** Extract all named imports from the source file (both type and value imports). */
function extractImports(sf: ts.SourceFile): ImportClause[] {
const cached = importClausesCache.get(sf);
if (cached) return cached;
const result: ImportClause[] = [];
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
@@ -51,6 +60,7 @@ function extractImports(sf: ts.SourceFile): ImportClause[] {
}
}
}
importClausesCache.set(sf, result);
return result;
}
@@ -58,6 +68,9 @@ function extractImports(sf: ts.SourceFile): ImportClause[] {
* 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 cached = valueImportClausesCache.get(sf);
if (cached) return cached;
const result: ImportClause[] = [];
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
@@ -78,16 +91,21 @@ function extractValueImports(sf: ts.SourceFile): ImportClause[] {
}
}
}
valueImportClausesCache.set(sf, result);
return result;
}
function extractExportAllSpecifiers(sf: ts.SourceFile): string[] {
const cached = exportAllSpecifiersCache.get(sf);
if (cached) return cached;
const result: string[] = [];
for (const stmt of sf.statements) {
if (!ts.isExportDeclaration(stmt) || stmt.exportClause) continue;
const spec = stmt.moduleSpecifier;
if (spec && ts.isStringLiteral(spec)) result.push(spec.text);
}
exportAllSpecifiersCache.set(sf, result);
return result;
}
@@ -523,6 +541,7 @@ function parseFileForDefinitions(
return {
filePath: absolutePath,
sourceFile: sf,
concrete,
templates,
importedTypeSources,
@@ -685,7 +704,7 @@ export function resolveImports(
}
}
const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true);
const entrySourceFile = entry.sourceFile;
const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(entrySourceFile)
.map(typeNode => ({ typeNode, from: entry }));
const wrapperBindings = collectWrapperBindings(entry, entrySourceFile);
@@ -719,5 +738,5 @@ export function resolveImports(
resolveTypeNode(root.typeNode, root.from);
}
return { concrete: [...concrete.values()], templates, wrapperBindings };
return { sourceFile: entrySourceFile, concrete: [...concrete.values()], templates, wrapperBindings };
}
+12 -10
View File
@@ -3,9 +3,9 @@ import { analyze, analyzeSource, selectUsedRegistry, typeNodeToMangledName } fro
import { fileHasExtendingClass } from './ast/ast-helpers.js';
import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
import { generateCode } from './codegen/generator.js';
import { applyReplacements, replaceCallSites } from './transform/replacer.js';
import { applyReplacements, collectReplacementEdits, replaceCallSites } from './transform/replacer.js';
import { applyTextEdits, type TextEdit } from './transform/text-edits.js';
import {
applyOverrideInsertions,
runSubclassWrapperPipeline,
type SubclassWrapperPipelineResult,
} from './typecheck/file-pipeline.js';
@@ -52,17 +52,19 @@ export default function protobufVitePlugin(_options: ProtobufVitePluginOptions =
if (used.registry.size === 0) return null;
const generatedCode = generateCode(used.registry);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
// Splice per-subclass overrides immediately after each subclass
// declaration so any user-side `Sub.method(...)` call later in the
// file sees the override on the constructor, not the inherited
// abstract body that would erase R/B at runtime.
const codeWithOverrides = applyOverrideInsertions(transformedCode, subclassWrappers.insertions);
const hasOverrides = codeWithOverrides !== transformedCode;
const replacementEdits = collectReplacementEdits(sourceFile, callSites, used.registry);
const overrideEdits: TextEdit[] = subclassWrappers.insertions.map(i => ({
start: i.position,
end: i.position,
replacement: i.code,
}));
const hasReplacements = replacementEdits.length > 0;
const hasOverrides = overrideEdits.length > 0;
if (!hasReplacements && generatedCode === '' && !hasOverrides) return null;
const transformedCode = applyTextEdits(code, [...replacementEdits, ...overrideEdits]);
return {
code: generatedCode + '\n' + codeWithOverrides,
code: generatedCode + '\n' + transformedCode,
map: null,
};
},
+27 -24
View File
@@ -1,10 +1,30 @@
import type { MessageRegistry } from '../ast/types.js';
import type { CallSiteRecord } from '../ast/analyzer.js';
import { createImportedTypeNameResolver, typeNodeToMangledName } from '../ast/utils.js';
import { collectProtobufImportBindings, matchProtobufCallSite } from '../ast/callsite.js';
import ts from 'typescript';
import type { CallSiteRecord } from '../ast/analyzer.js';
import { collectProtobufImportBindings, matchProtobufCallSite } from '../ast/callsite.js';
import type { MessageRegistry } from '../ast/types.js';
import { createImportedTypeNameResolver, typeNodeToMangledName } from '../ast/utils.js';
import { applyTextEdits, type TextEdit } from './text-edits.js';
interface TextEdit { start: number; end: number; replacement: string }
export function collectReplacementEdits(
sf: ts.SourceFile,
callSites: CallSiteRecord[],
registry: MessageRegistry,
): TextEdit[] {
const edits: TextEdit[] = [];
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
for (const cs of callSites) {
const mangled = typeNodeToMangledName(cs.firstTypeArg, sf, resolveImportedTypeName);
if (!registry.has(mangled)) continue;
edits.push({
start: cs.exprStart,
end: cs.typeArgsEnd,
replacement: `${cs.fnName}_${mangled}`,
});
}
return edits;
}
/**
* Apply replacements using pre-recorded call-sites from analyze().
@@ -16,26 +36,9 @@ export function applyReplacements(
callSites: CallSiteRecord[],
registry: MessageRegistry,
): { transformedCode: string; hasReplacements: boolean } {
const edits: TextEdit[] = [];
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
for (const cs of callSites) {
const mangled = typeNodeToMangledName(cs.firstTypeArg, sf, resolveImportedTypeName);
if (registry.has(mangled)) {
edits.push({
start: cs.exprStart,
end: cs.typeArgsEnd,
replacement: `${cs.fnName}_${mangled}`,
});
}
}
const edits = collectReplacementEdits(sf, callSites, registry);
if (!edits.length) return { transformedCode: code, hasReplacements: false };
edits.sort((a, b) => b.start - a.start);
let result = code;
for (const ed of edits) result = result.slice(0, ed.start) + ed.replacement + result.slice(ed.end);
return { transformedCode: result, hasReplacements: true };
return { transformedCode: applyTextEdits(code, edits), hasReplacements: true };
}
/**
@@ -0,0 +1,15 @@
export interface TextEdit {
start: number;
end: number;
replacement: string;
}
export function applyTextEdits(code: string, edits: TextEdit[]): string {
if (edits.length === 0) return code;
const sorted = [...edits].sort((a, b) => b.start - a.start);
let out = code;
for (const edit of sorted) {
out = out.slice(0, edit.start) + edit.replacement + out.slice(edit.end);
}
return out;
}
@@ -46,20 +46,6 @@ export interface SubclassWrapperPipelineResult {
insertions: SubclassOverrideInsertion[];
}
/** Splice each rendered override into `code` at its captured position.
* Insertions are sorted in reverse so earlier offsets stay valid as we
* apply later edits — same pattern the replacer uses for codec call-site
* rewriting. Returns `code` unchanged when there's nothing to insert. */
export function applyOverrideInsertions(code: string, insertions: SubclassOverrideInsertion[]): string {
if (insertions.length === 0) return code;
const sorted = [...insertions].sort((a, b) => b.position - a.position);
let out = code;
for (const ins of sorted) {
out = out.slice(0, ins.position) + ins.code + out.slice(ins.position);
}
return out;
}
export function runSubclassWrapperPipeline(filePath: string): SubclassWrapperPipelineResult {
const empty: SubclassWrapperPipelineResult = {
resolvedWrappers: [],
+17 -3
View File
@@ -1,6 +1,6 @@
import ts from 'typescript';
import { existsSync } from 'fs';
import { dirname, resolve } from 'path';
import ts from 'typescript';
/**
* Lazy ts.Program cache, keyed by tsconfig path.
@@ -31,6 +31,7 @@ interface CacheEntry extends ProgramContext {
}
const programCache = new Map<string, CacheEntry>();
const tsconfigLookupCache = new Map<string, string | null>();
/** Cap upward walk; keeps the lookup loop bounded if we end up at a
* monorepo root with no tsconfig (rare in this repo, but possible if a
@@ -39,13 +40,25 @@ const TSCONFIG_WALK_MAX_DEPTH = 24;
function findTsconfigUpwards(startDir: string): string | null {
let dir = resolve(startDir);
const cached = tsconfigLookupCache.get(dir);
if (cached !== undefined) return cached;
const visited: string[] = [];
for (let i = 0; i < TSCONFIG_WALK_MAX_DEPTH; i++) {
visited.push(dir);
const candidate = resolve(dir, 'tsconfig.json');
if (existsSync(candidate)) return candidate;
if (existsSync(candidate)) {
for (const v of visited) tsconfigLookupCache.set(v, candidate);
return candidate;
}
const parent = resolve(dir, '..');
if (parent === dir) return null;
if (parent === dir) {
for (const v of visited) tsconfigLookupCache.set(v, null);
return null;
}
dir = parent;
}
for (const v of visited) tsconfigLookupCache.set(v, null);
return null;
}
@@ -113,6 +126,7 @@ export function getProgramForFile(filePath: string): ProgramContext | null {
export function invalidateProgramCache(filePath?: string): void {
if (!filePath) {
programCache.clear();
tsconfigLookupCache.clear();
return;
}
const normalized = normalizePath(filePath);