Add transform + program caching to plugin
Introduce disk caching and startup program preparation for the Proton Vite plugin. Add ProtobufVitePluginOptions (root, tsconfig, cache) and configResolved hook to prebuild/prepare a TypeScript Program (program cache) and create a transform cache per-file (transform cache) keyed by source/config hashes and dependency mtimes. Track dependencyFiles in import-resolver so transform cache can validate mtimes. Update program-cache to support incremental tsbuildinfo and expose prepareProgramForTsconfig. Add cache read/write, hashing, path normalization and scope checks in the plugin; update tests and README to cover scope and cache behavior. Also add ts-morph dependency and update lockfile.
This commit is contained in:
1 parent
93850ec11c
commit
868f4a5798
7 files changed
+364
-12
No files matched your search
@@ -48,11 +48,27 @@ import { defineConfig } from 'vite';
|
||||
import protobufVitePlugin from '@snowluma/proton/vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [protobufVitePlugin()],
|
||||
plugins: [
|
||||
protobufVitePlugin({
|
||||
root: 'src', // 可选:限制插件只处理该目录下的 .ts 文件
|
||||
tsconfig: 'tsconfig.json', // 可选:configResolved 时预加载整个 TS Program
|
||||
cache: true, // 可选:默认启用,缓存写入 Vite cacheDir/proton
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
```
|
||||
|
||||
插件会在 Vite `configResolved` 阶段完成项目级初始化:解析作用目录、解析 `tsconfig`、预构建并缓存 TypeChecker 所需的 `ts.Program`。如果启用缓存(默认),Proton 会在 Vite 的 `cacheDir` 下维护两类缓存:
|
||||
|
||||
```text
|
||||
node_modules/.vite/proton/
|
||||
program/ TypeScript 增量 Program 缓存(tsBuildInfoFile)
|
||||
transform/ 按源码 hash + 配置 hash + 依赖 mtime 命中的 transform 结果
|
||||
```
|
||||
|
||||
这样普通文件的 transform 可以先走作用域过滤与 hash cache;未命中时才执行 AST 分析、跨文件导入解析和必要的 TypeChecker 子类解析。
|
||||
|
||||
添加工作区依赖:
|
||||
|
||||
```json
|
||||
@@ -266,7 +282,7 @@ qualified names (ns.Type), or a missing import.
|
||||
|
||||
```bash
|
||||
pnpm --filter @snowluma/proton build # 打包 src/index.ts → dist/index.js
|
||||
pnpm --filter @snowluma/proton test # 运行 vitest (107 个测试)
|
||||
pnpm --filter @snowluma/proton test # 运行 vitest (109 个测试)
|
||||
pnpm --filter @snowluma/proton typecheck # 运行 tsc --noEmit
|
||||
|
||||
```
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"prepare": "test -f dist/index.js || pnpm build"
|
||||
},
|
||||
"dependencies": {
|
||||
"ts-morph": "^28.0.0",
|
||||
"typescript": "catalog:"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -12,6 +12,7 @@ export type { WrapperBinding } from './wrapper-binding.js';
|
||||
export interface ParsedFileEntry {
|
||||
filePath: string;
|
||||
sourceFile: ts.SourceFile;
|
||||
dependencyFiles: string[];
|
||||
concrete: ProtobufMessage[];
|
||||
templates: Map<string, GenericProtobufTemplate>;
|
||||
importedTypeSources: Map<string, string>;
|
||||
@@ -22,6 +23,7 @@ export interface ParsedFileEntry {
|
||||
|
||||
export interface ImportedDefinitions {
|
||||
sourceFile: ts.SourceFile;
|
||||
dependencyFiles: string[];
|
||||
concrete: ProtobufMessage[];
|
||||
templates: Map<string, GenericProtobufTemplate>;
|
||||
wrapperBindings: Map<string, WrapperBinding>;
|
||||
@@ -474,6 +476,7 @@ function parseFileForDefinitions(
|
||||
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
|
||||
const importedTypeSources = new Map<string, string>();
|
||||
const exportAllTypeSources = new Map<string, string>();
|
||||
const dependencyFiles = new Set<string>([absolutePath]);
|
||||
|
||||
// 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
|
||||
@@ -495,6 +498,8 @@ function parseFileForDefinitions(
|
||||
entry = parseFileForDefinitions(resolved, undefined, cache, inProgress);
|
||||
cache.set(resolved, entry);
|
||||
}
|
||||
dependencyFiles.add(resolved);
|
||||
for (const dep of entry.dependencyFiles) dependencyFiles.add(dep);
|
||||
const wrapperFn = entry.exportedWrappers.get(imp.importedName);
|
||||
if (wrapperFn) importedKnownWrappers.set(imp.localName, wrapperFn);
|
||||
}
|
||||
@@ -521,6 +526,8 @@ function parseFileForDefinitions(
|
||||
entry = parseFileForDefinitions(resolved, undefined, cache, inProgress);
|
||||
cache.set(resolved, entry);
|
||||
}
|
||||
dependencyFiles.add(resolved);
|
||||
for (const dep of entry.dependencyFiles) dependencyFiles.add(dep);
|
||||
for (const msg of entry.concrete) exportAllTypeSources.set(msg.name, resolved);
|
||||
for (const name of entry.templates.keys()) exportAllTypeSources.set(name, resolved);
|
||||
for (const [name, source] of entry.exportAllTypeSources) exportAllTypeSources.set(name, source);
|
||||
@@ -542,6 +549,7 @@ function parseFileForDefinitions(
|
||||
return {
|
||||
filePath: absolutePath,
|
||||
sourceFile: sf,
|
||||
dependencyFiles: [...dependencyFiles],
|
||||
concrete,
|
||||
templates,
|
||||
importedTypeSources,
|
||||
@@ -738,5 +746,14 @@ export function resolveImports(
|
||||
resolveTypeNode(root.typeNode, root.from);
|
||||
}
|
||||
|
||||
return { sourceFile: entrySourceFile, concrete: [...concrete.values()], templates, wrapperBindings };
|
||||
const dependencyFiles = new Set<string>(entry.dependencyFiles);
|
||||
for (const filePath of fileEntries.keys()) dependencyFiles.add(filePath);
|
||||
|
||||
return {
|
||||
sourceFile: entrySourceFile,
|
||||
dependencyFiles: [...dependencyFiles],
|
||||
concrete: [...concrete.values()],
|
||||
templates,
|
||||
wrapperBindings,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import { createHash } from 'crypto';
|
||||
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'fs';
|
||||
import { dirname, isAbsolute, resolve } from 'path';
|
||||
import type { Plugin, ResolvedConfig } from 'vite';
|
||||
import { analyze, analyzeSource, selectUsedRegistry, typeNodeToMangledName } from './ast/analyzer.js';
|
||||
import { fileHasExtendingClass } from './ast/ast-helpers.js';
|
||||
import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
|
||||
@@ -9,20 +12,75 @@ import {
|
||||
runSubclassWrapperPipeline,
|
||||
type SubclassWrapperPipelineResult,
|
||||
} from './typecheck/file-pipeline.js';
|
||||
import { invalidateProgramCache } from './typecheck/program-cache.js';
|
||||
import { invalidateProgramCache, prepareProgramForTsconfig } from './typecheck/program-cache.js';
|
||||
|
||||
export type ProtobufVitePluginOptions = Record<string, never>;
|
||||
export interface ProtobufVitePluginOptions {
|
||||
root?: string;
|
||||
tsconfig?: string;
|
||||
cache?: boolean | {
|
||||
dir?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface ProtonPluginContext {
|
||||
viteRoot: string;
|
||||
scopeRoot: string;
|
||||
tsconfigPath: string;
|
||||
cacheEnabled: boolean;
|
||||
transformCacheDir: string;
|
||||
programCacheDir: string;
|
||||
programPrepared: boolean;
|
||||
}
|
||||
|
||||
interface TransformDiskCacheEntry {
|
||||
version: number;
|
||||
sourceHash: string;
|
||||
configHash: string;
|
||||
dependencyMtims: Record<string, number>;
|
||||
result: { code: string; map: null } | null;
|
||||
}
|
||||
|
||||
const TRANSFORM_CACHE_VERSION = 2;
|
||||
|
||||
export default function protobufVitePlugin(_options: ProtobufVitePluginOptions = {}): Plugin {
|
||||
const fileCache = new Map<string, ParsedFileEntry>();
|
||||
let ctx: ProtonPluginContext | null = null;
|
||||
|
||||
return {
|
||||
name: 'vite-plugin-protobuf',
|
||||
enforce: 'pre',
|
||||
|
||||
configResolved(config) {
|
||||
const nextCtx = createPluginContext(config, _options);
|
||||
ctx = nextCtx;
|
||||
if (nextCtx.cacheEnabled) {
|
||||
mkdirSync(nextCtx.transformCacheDir, { recursive: true });
|
||||
mkdirSync(nextCtx.programCacheDir, { recursive: true });
|
||||
}
|
||||
const prepared = prepareProgramForTsconfig(nextCtx.tsconfigPath, {
|
||||
cacheDir: nextCtx.cacheEnabled ? nextCtx.programCacheDir : undefined,
|
||||
});
|
||||
nextCtx.programPrepared = !!prepared;
|
||||
},
|
||||
|
||||
transform(code, id) {
|
||||
const cleanId = id.split('?')[0];
|
||||
if (!cleanId.endsWith('.ts') || cleanId.endsWith('.d.ts')) return null;
|
||||
const activeCtx = ctx ?? createStandaloneContext(_options);
|
||||
if (!isInScope(cleanId, activeCtx.scopeRoot)) return null;
|
||||
|
||||
const sourceHash = hashString(code);
|
||||
const configHash = hashString(JSON.stringify({
|
||||
scopeRoot: normalizePath(activeCtx.scopeRoot),
|
||||
tsconfigPath: normalizePath(activeCtx.tsconfigPath),
|
||||
tsconfigMtime: safeMtime(activeCtx.tsconfigPath),
|
||||
version: TRANSFORM_CACHE_VERSION,
|
||||
}));
|
||||
const cachePath = activeCtx.cacheEnabled
|
||||
? transformCachePath(activeCtx.transformCacheDir, cleanId)
|
||||
: null;
|
||||
const cached = cachePath ? readTransformCache(cachePath, sourceHash, configHash) : undefined;
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
const imported = resolveImports(code, cleanId, fileCache);
|
||||
const { registry, callSites, sourceFile } = analyze(code, cleanId, imported);
|
||||
@@ -40,6 +98,7 @@ export default function protobufVitePlugin(_options: ProtobufVitePluginOptions =
|
||||
callSites.length === 0 &&
|
||||
subclassWrappers.resolvedWrappers.length === 0
|
||||
) {
|
||||
if (cachePath) writeTransformCache(cachePath, sourceHash, configHash, imported.dependencyFiles, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -49,7 +108,10 @@ export default function protobufVitePlugin(_options: ProtobufVitePluginOptions =
|
||||
sourceFile,
|
||||
subclassWrappers.extraRootTypeNames,
|
||||
);
|
||||
if (used.registry.size === 0) return null;
|
||||
if (used.registry.size === 0) {
|
||||
if (cachePath) writeTransformCache(cachePath, sourceHash, configHash, imported.dependencyFiles, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
const generatedCode = generateCode(used.registry);
|
||||
const replacementEdits = collectReplacementEdits(sourceFile, callSites, used.registry);
|
||||
@@ -60,13 +122,18 @@ export default function protobufVitePlugin(_options: ProtobufVitePluginOptions =
|
||||
}));
|
||||
const hasReplacements = replacementEdits.length > 0;
|
||||
const hasOverrides = overrideEdits.length > 0;
|
||||
if (!hasReplacements && generatedCode === '' && !hasOverrides) return null;
|
||||
if (!hasReplacements && generatedCode === '' && !hasOverrides) {
|
||||
if (cachePath) writeTransformCache(cachePath, sourceHash, configHash, imported.dependencyFiles, null);
|
||||
return null;
|
||||
}
|
||||
const transformedCode = applyTextEdits(code, [...replacementEdits, ...overrideEdits]);
|
||||
|
||||
return {
|
||||
const result = {
|
||||
code: generatedCode + '\n' + transformedCode,
|
||||
map: null,
|
||||
};
|
||||
if (cachePath) writeTransformCache(cachePath, sourceHash, configHash, imported.dependencyFiles, result);
|
||||
|
||||
return result;
|
||||
},
|
||||
|
||||
handleHotUpdate({ file }) {
|
||||
@@ -78,6 +145,136 @@ export default function protobufVitePlugin(_options: ProtobufVitePluginOptions =
|
||||
};
|
||||
}
|
||||
|
||||
function createPluginContext(config: ResolvedConfig, options: ProtobufVitePluginOptions): ProtonPluginContext {
|
||||
const viteRoot = resolve(config.root);
|
||||
const scopeRoot = resolveOptionPath(options.root, viteRoot, viteRoot);
|
||||
const tsconfigPath = resolveOptionPath(options.tsconfig, viteRoot, resolve(scopeRoot, 'tsconfig.json'));
|
||||
const cacheBase = resolveCacheBase(options, viteRoot, config.cacheDir);
|
||||
return {
|
||||
viteRoot,
|
||||
scopeRoot,
|
||||
tsconfigPath,
|
||||
cacheEnabled: options.cache !== false,
|
||||
transformCacheDir: resolve(cacheBase, 'transform'),
|
||||
programCacheDir: resolve(cacheBase, 'program'),
|
||||
programPrepared: false,
|
||||
};
|
||||
}
|
||||
|
||||
function createStandaloneContext(options: ProtobufVitePluginOptions): ProtonPluginContext {
|
||||
const viteRoot = process.cwd();
|
||||
const scopeRoot = resolveOptionPath(options.root, viteRoot, viteRoot);
|
||||
const tsconfigPath = resolveOptionPath(options.tsconfig, viteRoot, resolve(scopeRoot, 'tsconfig.json'));
|
||||
const cacheBase = resolveCacheBase(options, viteRoot, resolve(viteRoot, 'node_modules', '.vite'));
|
||||
const cacheEnabled = options.cache === true || typeof options.cache === 'object';
|
||||
return {
|
||||
viteRoot,
|
||||
scopeRoot,
|
||||
tsconfigPath,
|
||||
cacheEnabled,
|
||||
transformCacheDir: resolve(cacheBase, 'transform'),
|
||||
programCacheDir: resolve(cacheBase, 'program'),
|
||||
programPrepared: false,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveOptionPath(value: string | undefined, base: string, fallback: string): string {
|
||||
if (!value) return fallback;
|
||||
return isAbsolute(value) ? resolve(value) : resolve(base, value);
|
||||
}
|
||||
|
||||
function resolveCacheBase(options: ProtobufVitePluginOptions, viteRoot: string, viteCacheDir: string): string {
|
||||
const configured = typeof options.cache === 'object' ? options.cache.dir : undefined;
|
||||
if (configured) return resolveOptionPath(configured, viteRoot, configured);
|
||||
return isAbsolute(viteCacheDir)
|
||||
? resolve(viteCacheDir, 'proton')
|
||||
: resolve(viteRoot, viteCacheDir, 'proton');
|
||||
}
|
||||
|
||||
function isInScope(filePath: string, scopeRoot: string): boolean {
|
||||
const file = normalizePath(filePath);
|
||||
const root = normalizePath(scopeRoot);
|
||||
return file === root || file.startsWith(root.endsWith('/') ? root : root + '/');
|
||||
}
|
||||
|
||||
function transformCachePath(cacheDir: string, filePath: string): string {
|
||||
return resolve(cacheDir, `${hashString(normalizePath(filePath))}.json`);
|
||||
}
|
||||
|
||||
function readTransformCache(
|
||||
cachePath: string,
|
||||
sourceHash: string,
|
||||
configHash: string,
|
||||
): { code: string; map: null } | null | undefined {
|
||||
if (!existsSync(cachePath)) return undefined;
|
||||
try {
|
||||
const entry = JSON.parse(readFileSync(cachePath, 'utf-8')) as TransformDiskCacheEntry;
|
||||
if (entry.version !== TRANSFORM_CACHE_VERSION) return undefined;
|
||||
if (entry.sourceHash !== sourceHash || entry.configHash !== configHash) return undefined;
|
||||
if (!dependencyMtimsMatch(entry.dependencyMtims)) return undefined;
|
||||
return entry.result;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeTransformCache(
|
||||
cachePath: string,
|
||||
sourceHash: string,
|
||||
configHash: string,
|
||||
dependencyFiles: readonly string[],
|
||||
result: { code: string; map: null } | null,
|
||||
): void {
|
||||
try {
|
||||
mkdirSync(dirname(cachePath), { recursive: true });
|
||||
const entry: TransformDiskCacheEntry = {
|
||||
version: TRANSFORM_CACHE_VERSION,
|
||||
sourceHash,
|
||||
configHash,
|
||||
dependencyMtims: collectDependencyMtims(dependencyFiles),
|
||||
result,
|
||||
};
|
||||
writeFileSync(cachePath, JSON.stringify(entry));
|
||||
} catch {
|
||||
// Cache failures must never break the transform path.
|
||||
}
|
||||
}
|
||||
|
||||
function collectDependencyMtims(files: readonly string[]): Record<string, number> {
|
||||
const out: Record<string, number> = {};
|
||||
for (const file of files) {
|
||||
try {
|
||||
out[normalizePath(file)] = statSync(file).mtimeMs;
|
||||
} catch {
|
||||
out[normalizePath(file)] = -1;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function dependencyMtimsMatch(mtims: Record<string, number>): boolean {
|
||||
for (const [file, previous] of Object.entries(mtims)) {
|
||||
if (safeMtime(file) !== previous) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function safeMtime(file: string): number {
|
||||
try {
|
||||
return statSync(file).mtimeMs;
|
||||
} catch {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
function hashString(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
function normalizePath(value: string): string {
|
||||
return resolve(value).replace(/\\/g, '/');
|
||||
}
|
||||
|
||||
export {
|
||||
analyze,
|
||||
analyzeSource,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { existsSync } from 'fs';
|
||||
import { existsSync, mkdirSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
import ts from 'typescript';
|
||||
|
||||
@@ -62,7 +62,11 @@ function findTsconfigUpwards(startDir: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildProgram(tsconfigPath: string): CacheEntry | null {
|
||||
export interface BuildProgramOptions {
|
||||
cacheDir?: string;
|
||||
}
|
||||
|
||||
function buildProgram(tsconfigPath: string, buildOptions: BuildProgramOptions = {}): CacheEntry | null {
|
||||
const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
|
||||
if (configFile.error) return null;
|
||||
|
||||
@@ -81,6 +85,14 @@ function buildProgram(tsconfigPath: string): CacheEntry | null {
|
||||
noEmit: true,
|
||||
skipLibCheck: parsedConfig.options.skipLibCheck ?? true,
|
||||
};
|
||||
if (buildOptions.cacheDir) {
|
||||
mkdirSync(buildOptions.cacheDir, { recursive: true });
|
||||
options.incremental = true;
|
||||
options.tsBuildInfoFile = resolve(
|
||||
buildOptions.cacheDir,
|
||||
`program-${safeFileName(tsconfigPath)}.tsbuildinfo`,
|
||||
);
|
||||
}
|
||||
|
||||
const program = ts.createProgram({
|
||||
rootNames: parsedConfig.fileNames,
|
||||
@@ -96,6 +108,15 @@ function buildProgram(tsconfigPath: string): CacheEntry | null {
|
||||
return { tsconfigPath, program, checker, fileSet };
|
||||
}
|
||||
|
||||
export function prepareProgramForTsconfig(tsconfigPath: string, options: BuildProgramOptions = {}): ProgramContext | null {
|
||||
const abs = resolve(tsconfigPath);
|
||||
const built = buildProgram(abs, options);
|
||||
if (!built) return null;
|
||||
programCache.set(abs, built);
|
||||
tsconfigLookupCache.set(dirname(abs), abs);
|
||||
return { tsconfigPath: built.tsconfigPath, program: built.program, checker: built.checker };
|
||||
}
|
||||
|
||||
/** Locate (or build) the program that contains `filePath`. Returns null if
|
||||
* no tsconfig is reachable, or if the file isn't part of any program — in
|
||||
* which case the caller MUST fall back to the AST-only pipeline. */
|
||||
@@ -140,3 +161,7 @@ export function invalidateProgramCache(filePath?: string): void {
|
||||
function normalizePath(p: string): string {
|
||||
return resolve(p).replace(/\\/g, '/');
|
||||
}
|
||||
|
||||
function safeFileName(value: string): string {
|
||||
return normalizePath(value).replace(/[^a-zA-Z0-9_.-]/g, '_');
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { resolve } from 'path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer';
|
||||
import { generateCode } from '../../src/codegen/generator';
|
||||
import protobufVitePlugin from '../../src/index';
|
||||
import { replaceCallSites } from '../../src/transform/replacer';
|
||||
import { execAndGet, loadFixture } from '../helpers';
|
||||
|
||||
@@ -214,4 +218,66 @@ const buf = protobuf_encode<UsedMsg>({ inner: { id: 1 } });
|
||||
expect(gen).not.toContain('protobuf_encode_UnusedMsg');
|
||||
});
|
||||
|
||||
it('respects the configured Vite transform scope root', () => {
|
||||
const scope = mkdtempSync(resolve(tmpdir(), 'proton-scope-'));
|
||||
try {
|
||||
const plugin = protobufVitePlugin({ root: scope, cache: false });
|
||||
const code = `interface Msg { id: pb<1, uint_32>; }\nconst buf = protobuf_encode<Msg>({ id: 1 });\n`;
|
||||
expect(runPluginTransform(plugin, code, resolve(tmpdir(), 'outside.ts'))).toBeNull();
|
||||
const inside = runPluginTransform(plugin, code, resolve(scope, 'inside.ts'));
|
||||
expect(inside?.code).toContain('protobuf_encode_Msg');
|
||||
} finally {
|
||||
rmSync(scope, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('uses Vite cacheDir for transform hash cache and startup program cache', () => {
|
||||
const root = mkdtempSync(resolve(tmpdir(), 'proton-cache-'));
|
||||
try {
|
||||
const sourcePath = resolve(root, 'entry.ts');
|
||||
const tsconfigPath = resolve(root, 'tsconfig.json');
|
||||
const cacheDir = resolve(root, '.vite');
|
||||
const code = `interface Msg { id: pb<1, uint_32>; }\nconst buf = protobuf_encode<Msg>({ id: 1 });\n`;
|
||||
writeFileSync(sourcePath, code);
|
||||
writeFileSync(tsconfigPath, JSON.stringify({
|
||||
compilerOptions: { noEmit: true, target: 'ES2022' },
|
||||
files: ['entry.ts'],
|
||||
}));
|
||||
|
||||
const firstPlugin = protobufVitePlugin({ root, tsconfig: tsconfigPath });
|
||||
runConfigResolved(firstPlugin, root, cacheDir);
|
||||
const first = runPluginTransform(firstPlugin, code, sourcePath);
|
||||
expect(first?.code).toContain('protobuf_encode_Msg');
|
||||
|
||||
const transformCacheDir = resolve(cacheDir, 'proton', 'transform');
|
||||
const programCacheDir = resolve(cacheDir, 'proton', 'program');
|
||||
expect(existsSync(transformCacheDir)).toBe(true);
|
||||
expect(existsSync(programCacheDir)).toBe(true);
|
||||
expect(readdirSync(transformCacheDir).some(name => name.endsWith('.json'))).toBe(true);
|
||||
|
||||
const secondPlugin = protobufVitePlugin({ root, tsconfig: tsconfigPath });
|
||||
runConfigResolved(secondPlugin, root, cacheDir);
|
||||
const second = runPluginTransform(secondPlugin, code, sourcePath);
|
||||
expect(second).toEqual(first);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
function runPluginTransform(
|
||||
plugin: ReturnType<typeof protobufVitePlugin>,
|
||||
code: string,
|
||||
id: string,
|
||||
): { code: string; map: null } | null {
|
||||
const transformHook = plugin.transform!;
|
||||
const transformFn = typeof transformHook === 'function' ? transformHook : transformHook.handler;
|
||||
return transformFn.call({} as never, code, id) as { code: string; map: null } | null;
|
||||
}
|
||||
|
||||
function runConfigResolved(plugin: ReturnType<typeof protobufVitePlugin>, root: string, cacheDir: string): void {
|
||||
const hook = plugin.configResolved!;
|
||||
const fn = typeof hook === 'function' ? hook : hook.handler;
|
||||
fn.call({} as never, { root, cacheDir } as never);
|
||||
}
|
||||
Generated
+30
@@ -220,6 +220,9 @@ importers:
|
||||
|
||||
packages/proton:
|
||||
dependencies:
|
||||
ts-morph:
|
||||
specifier: ^28.0.0
|
||||
version: 28.0.0
|
||||
typescript:
|
||||
specifier: 'catalog:'
|
||||
version: 6.0.2
|
||||
@@ -1692,6 +1695,9 @@ packages:
|
||||
'@tanstack/store@0.9.3':
|
||||
resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==}
|
||||
|
||||
'@ts-morph/common@0.29.0':
|
||||
resolution: {integrity: sha512-35oUmphHbJvQ/+UTwFNme/t2p3FoKiGJ5auTjjpNTop2dyREspirjMy82PLSC1pnDJ8ah1GU98hwpVt64YXQsg==}
|
||||
|
||||
'@tybys/wasm-util@0.10.1':
|
||||
resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==}
|
||||
|
||||
@@ -1958,6 +1964,9 @@ packages:
|
||||
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
code-block-writer@13.0.3:
|
||||
resolution: {integrity: sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==}
|
||||
|
||||
commander@14.0.3:
|
||||
resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==}
|
||||
engines: {node: '>=20'}
|
||||
@@ -2538,6 +2547,9 @@ packages:
|
||||
resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
path-browserify@1.0.1:
|
||||
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
|
||||
|
||||
path-exists@4.0.0:
|
||||
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -2820,6 +2832,9 @@ packages:
|
||||
ts-interface-checker@0.1.13:
|
||||
resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==}
|
||||
|
||||
ts-morph@28.0.0:
|
||||
resolution: {integrity: sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g==}
|
||||
|
||||
tslib@2.8.1:
|
||||
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
|
||||
|
||||
@@ -4070,6 +4085,12 @@ snapshots:
|
||||
|
||||
'@tanstack/store@0.9.3': {}
|
||||
|
||||
'@ts-morph/common@0.29.0':
|
||||
dependencies:
|
||||
minimatch: 10.2.5
|
||||
path-browserify: 1.0.1
|
||||
tinyglobby: 0.2.16
|
||||
|
||||
'@tybys/wasm-util@0.10.1':
|
||||
dependencies:
|
||||
tslib: 2.8.1
|
||||
@@ -4400,6 +4421,8 @@ snapshots:
|
||||
|
||||
clsx@2.1.1: {}
|
||||
|
||||
code-block-writer@13.0.3: {}
|
||||
|
||||
commander@14.0.3: {}
|
||||
|
||||
commander@4.1.1: {}
|
||||
@@ -4917,6 +4940,8 @@ snapshots:
|
||||
dependencies:
|
||||
p-limit: 3.1.0
|
||||
|
||||
path-browserify@1.0.1: {}
|
||||
|
||||
path-exists@4.0.0: {}
|
||||
|
||||
path-key@3.1.1: {}
|
||||
@@ -5211,6 +5236,11 @@ snapshots:
|
||||
|
||||
ts-interface-checker@0.1.13: {}
|
||||
|
||||
ts-morph@28.0.0:
|
||||
dependencies:
|
||||
'@ts-morph/common': 0.29.0
|
||||
code-block-writer: 13.0.3
|
||||
|
||||
tslib@2.8.1: {}
|
||||
|
||||
tsup@8.5.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)(typescript@6.0.2):
|
||||
|
||||
Reference in new issue
Block a user