Skip to content

Commit dc95070

Browse files
authored
fix(vite-plugin-angular): release compiler state when watched projects close (#2739)
1 parent dfa2401 commit dc95070

2 files changed

Lines changed: 140 additions & 29 deletions

File tree

‎packages/vite-plugin-angular/src/lib/angular-vite-plugin.spec.ts‎

Lines changed: 93 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
22
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
33
import * as realFs from 'node:fs';
4-
import { SourceMap } from 'node:module';
4+
import { createRequire, SourceMap } from 'node:module';
55
import { tmpdir } from 'node:os';
66
import path, { join } from 'node:path';
77
import { normalizePath, preprocessCSS, resolveConfig, type Plugin } from 'vite';
@@ -1453,7 +1453,7 @@ export class AppComponent {}
14531453
60_000,
14541454
);
14551455

1456-
it('keeps AOT output for environments still building after another ends', async () => {
1456+
it('keeps AOT output for environments still building after another ends and closes', async () => {
14571457
const plugin = createAppBuildPlugin({ jit: false });
14581458
await plugin.config({ root: fixtureDir, build: {} }, { command: 'build' });
14591459
const config = await resolveConfig(
@@ -1471,6 +1471,7 @@ export class AppComponent {}
14711471
await plugin.buildStart.call(ctx);
14721472
await plugin.buildStart.call(ctx);
14731473
await plugin.buildEnd.call(ctx);
1474+
await plugin.closeBundle();
14741475

14751476
const code = realFs.readFileSync(componentPath, 'utf-8');
14761477
const result = await plugin.transform.handler.call(
@@ -1481,6 +1482,10 @@ export class AppComponent {}
14811482
expect(result?.code).toContain('ɵcmp');
14821483

14831484
await plugin.buildEnd.call(ctx);
1485+
await plugin.closeBundle();
1486+
expect(
1487+
await plugin.transform.handler.call(ctx, code, componentPath),
1488+
).toBeUndefined();
14841489
}, 60_000);
14851490

14861491
it.each([
@@ -1809,7 +1814,7 @@ export class AppComponent {}
18091814
expect(ctx.error).not.toHaveBeenCalled();
18101815
} finally {
18111816
await mainPlugin.buildEnd.call(ctx);
1812-
mainPlugin.closeBundle();
1817+
await mainPlugin.closeBundle();
18131818
}
18141819
}, 60_000);
18151820

@@ -1976,6 +1981,91 @@ export class AppComponent {}
19761981
expect(ctx.error).not.toHaveBeenCalled();
19771982
}, 60_000);
19781983

1984+
it.each([
1985+
{ jit: false, closeBeforeEnd: false },
1986+
{ jit: true, closeBeforeEnd: false },
1987+
{ jit: false, closeBeforeEnd: true },
1988+
{ jit: true, closeBeforeEnd: true },
1989+
])(
1990+
'reuses the watched builder and releases it on close (jit=$jit, closeBeforeEnd=$closeBeforeEnd)',
1991+
async ({ jit, closeBeforeEnd }) => {
1992+
const require = createRequire(import.meta.url);
1993+
const ts = require('typescript');
1994+
const tsModule = require.cache[require.resolve('typescript')]!;
1995+
const createBuilder = vi.fn(
1996+
ts.createEmitAndSemanticDiagnosticsBuilderProgram,
1997+
);
1998+
tsModule.exports = new Proxy(ts, {
1999+
get(target, property, receiver) {
2000+
return property === 'createEmitAndSemanticDiagnosticsBuilderProgram'
2001+
? createBuilder
2002+
: Reflect.get(target, property, receiver);
2003+
},
2004+
});
2005+
let plugin;
2006+
try {
2007+
plugin = createAppBuildPlugin({ jit });
2008+
} finally {
2009+
tsModule.exports = ts;
2010+
}
2011+
await plugin.config({ root: fixtureDir }, { command: 'serve' });
2012+
const config = await resolveConfig(
2013+
{ configFile: false, root: fixtureDir },
2014+
'serve',
2015+
);
2016+
plugin.configResolved(config);
2017+
const ctx = {
2018+
environment: { config },
2019+
warn: vi.fn(),
2020+
error: vi.fn(),
2021+
addWatchFile: vi.fn(),
2022+
};
2023+
const code = realFs.readFileSync(componentPath, 'utf-8');
2024+
2025+
await plugin.buildStart.call(ctx);
2026+
await plugin.buildEnd.call(ctx);
2027+
const firstBuilder = createBuilder.mock.results.at(-1)?.value;
2028+
expect(firstBuilder).toBeDefined();
2029+
await plugin.buildStart.call(ctx);
2030+
await plugin.buildEnd.call(ctx);
2031+
expect(createBuilder.mock.calls.at(-1)?.[jit ? 3 : 2]).toBe(firstBuilder);
2032+
2033+
const retained = await plugin.transform.handler.call(
2034+
ctx,
2035+
code,
2036+
componentPath,
2037+
);
2038+
expect(retained?.code).toContain('AppComponent');
2039+
2040+
if (closeBeforeEnd) {
2041+
await plugin.buildStart.call(ctx);
2042+
await plugin.closeBundle();
2043+
const active = await plugin.transform.handler.call(
2044+
ctx,
2045+
code,
2046+
componentPath,
2047+
);
2048+
expect(active?.code).toContain('AppComponent');
2049+
await plugin.buildEnd.call(ctx);
2050+
} else {
2051+
await plugin.closeBundle();
2052+
}
2053+
const released = await plugin.transform.handler.call(
2054+
ctx,
2055+
code,
2056+
componentPath,
2057+
);
2058+
expect(released).toBeUndefined();
2059+
await plugin.closeBundle();
2060+
await plugin.buildStart.call(ctx);
2061+
expect(createBuilder.mock.calls.at(-1)?.[jit ? 3 : 2]).toBeUndefined();
2062+
await plugin.buildEnd.call(ctx);
2063+
await plugin.closeBundle();
2064+
expect(ctx.error).not.toHaveBeenCalled();
2065+
},
2066+
60_000,
2067+
);
2068+
19792069
it('releases production compilation output at buildEnd', async () => {
19802070
const mainPlugin = createAppBuildPlugin();
19812071

‎packages/vite-plugin-angular/src/lib/angular-vite-plugin.ts‎

Lines changed: 47 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,10 @@ export function angular(options?: PluginOptions): Plugin[] {
301301
let tsConfigResolutionContext: TsConfigResolutionContext | null = null;
302302

303303
const ts = require('typescript');
304-
let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;
304+
let cachedBuilder:
305+
| ts.BuilderProgram
306+
| ts.EmitAndSemanticDiagnosticsBuilderProgram
307+
| undefined;
305308
let nextProgram: NgtscProgram | undefined;
306309
let cachedHost: ts.CompilerHost | undefined;
307310
let cachedHostKey: string | undefined;
@@ -422,6 +425,7 @@ export function angular(options?: PluginOptions): Plugin[] {
422425
};
423426
let initialCompilation = false;
424427
let activeBuilds = 0;
428+
let closeRequested = false;
425429
const declarationFiles: DeclarationFile[] = [];
426430
const fileTransformMap = new Map<string, string>();
427431
let styleTransform: (
@@ -433,6 +437,38 @@ export function angular(options?: PluginOptions): Plugin[] {
433437
const hotUpdates = createHotUpdateBatcher((ids) =>
434438
performCompilation(resolvedConfig, ids),
435439
);
440+
function releaseCompilation() {
441+
cachedBuilder = undefined;
442+
nextProgram = undefined;
443+
cachedHost = undefined;
444+
cachedHostKey = undefined;
445+
outputFile = undefined;
446+
outputFiles.clear();
447+
fileTransformMap.clear();
448+
tsSourceFileCache.clear();
449+
sourceFileCache.clear();
450+
sourceFileCache.modifiedFiles.clear();
451+
sourceFileCache.babelFileCache?.clear();
452+
sourceFileCache.typeScriptFileCache?.clear();
453+
sourceFileCache.referencedFiles = undefined;
454+
tsconfigResolver.invalidateAll();
455+
releaseCssPreprocessorWorkers();
456+
stylesheetRegistry = undefined;
457+
}
458+
459+
async function closeCompilation() {
460+
hotUpdates.close();
461+
await compilationLock;
462+
declarationFiles.forEach(
463+
({ declarationFileDir, declarationPath, data }) => {
464+
mkdirSync(declarationFileDir, { recursive: true });
465+
writeFileSync(declarationPath, data, 'utf-8');
466+
},
467+
);
468+
declarationFiles.length = 0;
469+
releaseCompilation();
470+
}
471+
436472
function angularPlugin(): Plugin {
437473
let isProd = false;
438474

@@ -635,21 +671,9 @@ export function angular(options?: PluginOptions): Plugin[] {
635671
// Environments (e.g. client and ssr) build in parallel and share this
636672
// plugin's compilation state, so only reset after the last one ends.
637673
activeBuilds = Math.max(0, activeBuilds - 1);
638-
if (watchMode || activeBuilds > 0) return;
639-
nextProgram = undefined;
640-
cachedHost = undefined;
641-
cachedHostKey = undefined;
642-
outputFile = undefined;
643-
outputFiles.clear();
644-
fileTransformMap.clear();
645-
tsSourceFileCache.clear();
646-
sourceFileCache.clear();
647-
sourceFileCache.modifiedFiles.clear();
648-
sourceFileCache.babelFileCache?.clear();
649-
sourceFileCache.typeScriptFileCache?.clear();
650-
sourceFileCache.referencedFiles = undefined;
651-
tsconfigResolver.invalidateAll();
652-
releaseCssPreprocessorWorkers();
674+
if (activeBuilds > 0) return;
675+
if (closeRequested) return closeCompilation();
676+
if (!watchMode) releaseCompilation();
653677
},
654678
async handleHotUpdate(ctx) {
655679
if (isIgnoredHmrFile(ctx.file)) {
@@ -1413,15 +1437,8 @@ export function angular(options?: PluginOptions): Plugin[] {
14131437
},
14141438
},
14151439
closeBundle() {
1416-
hotUpdates.close();
1417-
declarationFiles.forEach(
1418-
({ declarationFileDir, declarationPath, data }) => {
1419-
mkdirSync(declarationFileDir, { recursive: true });
1420-
writeFileSync(declarationPath, data, 'utf-8');
1421-
},
1422-
);
1423-
declarationFiles.length = 0;
1424-
if (!watchMode) releaseCssPreprocessorWorkers();
1440+
closeRequested = true;
1441+
if (activeBuilds === 0) return closeCompilation();
14251442
},
14261443
};
14271444
}
@@ -1669,9 +1686,12 @@ export function angular(options?: PluginOptions): Plugin[] {
16691686
let typeScriptProgram: ts.Program;
16701687
let angularCompiler: NgtscProgram['compiler'];
16711688
// Declaration changes can invalidate diagnostics in unchanged consumers.
1689+
let builder:
1690+
| ts.BuilderProgram
1691+
| ts.EmitAndSemanticDiagnosticsBuilderProgram;
16721692
const oldBuilder = ids?.some((id) => EXCLUDED_TS_EXT_REGEX.test(id))
16731693
? undefined
1674-
: (builder ?? ts.readBuilderProgram(tsCompilerOptions, host));
1694+
: (cachedBuilder ?? ts.readBuilderProgram(tsCompilerOptions, host));
16751695

16761696
if (!jit) {
16771697
// Create the Angular specific program that contains the Angular compiler
@@ -1708,6 +1728,7 @@ export function angular(options?: PluginOptions): Plugin[] {
17081728
// using an abstract builder that only wraps a TypeScript program.
17091729
builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);
17101730
}
1731+
cachedBuilder = builder;
17111732

17121733
if (angularCompiler!) {
17131734
await angularCompiler.analyzeAsync();

0 commit comments

Comments
 (0)