This commit is contained in:
手瓜一十雪 committed 2026-10-24 17:28:58 +08:00
1 parent 8e28bca775
commit 1172a6bd3d
100 files changed
+8305 -6025

No files matched your search

+50 -116
View File
@@ -1,140 +1,74 @@
import type { Plugin } from 'vite';
import {
analyze,
analyzeSource,
selectUsedRegistry,
typeNodeToMangledName,
} from './ast/analyzer.js';
import { generateCode } from './codegen/generator.js';
import { applyReplacements, replaceCallSites } from './transform/replacer.js';
import type { MessageRegistry } from './ast/types.js';
import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
import { createRuntimeMap, type RuntimeMapCallSite } from './runtime-map.js';
import type { Plugin, ResolvedConfig } from 'vite';
import { ProtobufCompiler } from './compiler/compiler.js';
import { buildEntries } from './source/entries.js';
import { packageName } from './package.js';
export interface ProtobufRuntimeMapPluginOptions {
enabled?: boolean;
fileName?: string;
}
export default function protobufVitePlugin(): Plugin {
const compiler = new ProtobufCompiler();
const transformedFiles = new Set<string>();
let config: ResolvedConfig | undefined;
let needsPreparation = true;
export interface ProtobufVitePluginOptions {
runtimeMap?: ProtobufRuntimeMapPluginOptions;
}
interface RuntimeMapFileEntry {
messages: MessageRegistry;
callSites: RuntimeMapCallSite[];
}
export default function protobufVitePlugin(options: ProtobufVitePluginOptions = {}): Plugin {
const fileCache = new Map<string, ParsedFileEntry>();
const runtimeMapByFile = new Map<string, RuntimeMapFileEntry>();
const runtimeMapEnabled = options.runtimeMap?.enabled === true;
const runtimeMapFileName = options.runtimeMap?.fileName ?? 'snowluma-proton.runtime-map.json';
const invalidate = () => {
compiler.clear();
needsPreparation = true;
};
return {
name: 'vite-plugin-protobuf',
name: `${packageName}:vite`,
enforce: 'pre',
configResolved(resolved) {
config = resolved;
},
buildStart() {
invalidate();
transformedFiles.clear();
},
watchChange() {
invalidate();
},
transform(code, id) {
const cleanId = id.split('?')[0];
if (!cleanId.endsWith('.ts') || cleanId.endsWith('.d.ts')) {
if (!/\.[cm]?tsx?$/.test(cleanId) || /\.d\.[cm]?ts$/.test(cleanId)) {
return null;
}
const imported = resolveImports(code, cleanId, fileCache);
const { registry, callSites, sourceFile } = analyze(code, cleanId, imported);
if (needsPreparation) {
if (config) {
compiler.prepare(buildEntries(config));
}
if (registry.size === 0 && callSites.length === 0) {
return null;
needsPreparation = false;
}
const used = selectUsedRegistry(registry, callSites, sourceFile);
const transformed = compiler.compile(code, cleanId);
if (used.registry.size === 0) {
runtimeMapByFile.delete(cleanId);
return null;
if (transformed !== null) {
transformedFiles.add(cleanId);
for (const dependency of compiler.context.files.keys()) {
this.addWatchFile?.(dependency);
}
}
if (runtimeMapEnabled) {
runtimeMapByFile.set(cleanId, {
messages: used.registry,
callSites: used.callSites.map((cs) => ({
file: cleanId,
line: cs.line,
column: cs.column,
fnName: cs.fnName as RuntimeMapCallSite['fnName'],
typeName: cs.typeName,
})),
return transformed === null ? null : { code: transformed, map: null };
},
handleHotUpdate({ file, server }) {
if (/\.[cm]?tsx?$/.test(file)) {
invalidate();
return [...transformedFiles].flatMap((id) => {
const module = server.moduleGraph.getModuleById(id);
return module ? [module] : [];
});
}
const generatedCode = generateCode(used.registry);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
used.registry,
);
if (!hasReplacements && generatedCode === '') {
return null;
}
return { code: generatedCode + '\n' + transformedCode, map: null };
},
handleHotUpdate({ file }) {
if (file.endsWith('.ts')) {
fileCache.delete(file);
runtimeMapByFile.delete(file);
}
},
generateBundle() {
if (!runtimeMapEnabled) {
return;
}
const mergedMessages: MessageRegistry = new Map();
const mergedCallSites: RuntimeMapCallSite[] = [];
for (const entry of runtimeMapByFile.values()) {
for (const [name, msg] of entry.messages) {
mergedMessages.set(name, msg);
}
mergedCallSites.push(...entry.callSites);
}
if (mergedMessages.size === 0 || mergedCallSites.length === 0) {
return;
}
const runtimeMap = createRuntimeMap({
messages: mergedMessages,
callSites: mergedCallSites,
});
this.emitFile({
type: 'asset',
fileName: runtimeMapFileName,
source: JSON.stringify(runtimeMap, null, 2),
});
return;
},
};
}
export {
analyze,
analyzeSource,
generateCode,
replaceCallSites,
applyReplacements,
typeNodeToMangledName,
resolveImports,
selectUsedRegistry,
createRuntimeMap,
};
export type { ProtobufRuntimeMap, RuntimeMapCallSite } from './runtime-map.js';