Skip to content

Commit df3016c

Browse files
committed
fix(@angular/build): invalidate inline stylesheet load cache and support persistent cache
Ensure `ComponentStylesheetBundler.invalidate()` always invalidates `#loadCache` for all modified files, including evicting `angular:styles/component:${entry}` keys when an inline stylesheet's containing component `.ts` file is invalidated. Previously, invalidating a component `.ts` file deleted the inline `BundlerContext` without invalidating `#loadCache`, leaving stale errors (such as missing `@use` partials), stale Tailwind utility CSS, and unreferenced inline stylesheet entries in memory. Additionally, allow `ComponentStylesheetBundler` to accept an optional `LoadResultCache` and wire `PersistentLoadResultCache` in `createComponentStylesheetBundlerForLibrary` when persistent disk caching is enabled.
1 parent 0fd4404 commit df3016c

5 files changed

Lines changed: 365 additions & 80 deletions

File tree

‎packages/angular/build/src/builders/library/pipeline/stylesheet-bundler.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
*/
88

99
import { ComponentStylesheetBundler } from '../../../tools/esbuild/angular/component-stylesheets';
10+
import { PersistentLoadResultCache } from '../../../tools/esbuild/persistent-load-result-cache';
1011
import type { BundleStylesheetOptions } from '../../../tools/esbuild/stylesheets/bundle-options';
12+
import { calculateGlobalStylesheetConfigHash } from '../../../tools/esbuild/stylesheets/stylesheet-cache-key';
1113
import type { NormalizedLibraryOptions } from '../types';
1214

1315
/**
@@ -65,5 +67,13 @@ export function createComponentStylesheetBundlerForLibrary(
6567
tailwindConfiguration,
6668
};
6769

68-
return new ComponentStylesheetBundler(bundleOptions, inlineStyleLanguage, incremental);
70+
const loadCache =
71+
cacheOptions.enabled && cacheOptions.path
72+
? new PersistentLoadResultCache(
73+
cacheOptions.path,
74+
calculateGlobalStylesheetConfigHash(bundleOptions),
75+
)
76+
: undefined;
77+
78+
return new ComponentStylesheetBundler(bundleOptions, inlineStyleLanguage, incremental, loadCache);
6979
}

‎packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts‎

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ import { MemoryCache } from '../../../utils/cache';
1212
import { createContentHash } from '../../../utils/hash';
1313
import { BundleContextResult, BundlerContext } from '../bundler-context';
1414
import { type BuildOutputFile, BuildOutputFileType } from '../bundler-files';
15-
import { MemoryLoadResultCache } from '../load-result-cache';
15+
import { type LoadResultCache, MemoryLoadResultCache } from '../load-result-cache';
16+
import { PersistentLoadResultCache } from '../persistent-load-result-cache';
1617
import {
1718
BundleStylesheetOptions,
1819
createStylesheetBundleOptions,
1920
} from '../stylesheets/bundle-options';
21+
import { calculateGlobalStylesheetConfigHash } from '../stylesheets/stylesheet-cache-key';
2022

2123
export type ComponentStylesheetResult = BundleContextResult & {
2224
contents: string;
@@ -31,18 +33,29 @@ export type ComponentStylesheetResult = BundleContextResult & {
3133
export class ComponentStylesheetBundler {
3234
readonly #fileContexts = new MemoryCache<BundlerContext>();
3335
readonly #inlineContexts = new MemoryCache<BundlerContext>();
34-
readonly #loadCache = new MemoryLoadResultCache();
36+
readonly #loadCache: LoadResultCache;
3537

3638
/**
3739
* @param options An object containing the stylesheet bundling options.
3840
* @param defaultInlineLanguage The default language to use for inline component styles.
3941
* @param incremental True if incremental watch mode is enabled.
42+
* @param loadCache Optional cache instance to use for stylesheet load results.
4043
*/
4144
constructor(
4245
private readonly options: BundleStylesheetOptions,
4346
private readonly defaultInlineLanguage: string,
4447
private readonly incremental: boolean,
45-
) {}
48+
loadCache?: LoadResultCache,
49+
) {
50+
this.#loadCache =
51+
loadCache ??
52+
(options.cacheOptions.enabled && options.cacheOptions.path
53+
? new PersistentLoadResultCache(
54+
options.cacheOptions.path,
55+
calculateGlobalStylesheetConfigHash(options),
56+
)
57+
: new MemoryLoadResultCache());
58+
}
4659

4760
/**
4861
* Bundle a file-based component stylesheet for use within an AOT compiled Angular application.
@@ -217,14 +230,27 @@ export class ComponentStylesheetBundler {
217230
const firstSemi = entry.indexOf(';');
218231
const secondSemi = firstSemi !== -1 ? entry.indexOf(';', firstSemi + 1) : -1;
219232
const filename = secondSemi !== -1 ? entry.slice(secondSemi + 1) : '';
220-
if (filename && normalizedFiles.has(path.normalize(filename))) {
233+
const normalizedFilename = filename ? path.normalize(filename) : '';
234+
if (
235+
normalizedFilename &&
236+
(normalizedFiles.has(normalizedFilename) ||
237+
(!path.isAbsolute(normalizedFilename) &&
238+
normalizedFiles.has(
239+
path.normalize(path.join(this.options.workspaceRoot, normalizedFilename)),
240+
)))
241+
) {
221242
this.#inlineContexts.delete(entry);
243+
this.#loadCache.invalidate(`angular:styles/component:${entry}`);
222244
void bundler.dispose().catch(() => {});
223245
} else {
224246
bundler.invalidate(normalizedFiles);
225247
}
226248
}
227249

250+
for (const file of normalizedFiles) {
251+
this.#loadCache.invalidate(file);
252+
}
253+
228254
return entries;
229255
}
230256

@@ -244,9 +270,12 @@ export class ComponentStylesheetBundler {
244270
const contexts = [...this.#fileContexts.values(), ...this.#inlineContexts.values()];
245271
this.#fileContexts.clear();
246272
this.#inlineContexts.clear();
247-
this.#loadCache.clear();
273+
this.#loadCache.clear?.();
248274

249-
await Promise.allSettled(contexts.map((context) => context.dispose()));
275+
await Promise.allSettled([
276+
...contexts.map((context) => context.dispose()),
277+
this.#loadCache.dispose?.(),
278+
]);
250279
}
251280

252281
private extractResult(
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import assert from 'node:assert';
10+
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
11+
import { join } from 'node:path';
12+
import { createComponentStylesheetBundlerForLibrary } from '../../../builders/library/pipeline/stylesheet-bundler';
13+
import { initializeHash } from '../../../utils/hash';
14+
import { MemoryLoadResultCache } from '../load-result-cache';
15+
import { resetSassWorkerPoolCaches, shutdownSassWorkerPool } from '../stylesheets/sass-language';
16+
import { ComponentStylesheetBundler } from './component-stylesheets';
17+
18+
describe('ComponentStylesheetBundler', () => {
19+
let tempRoot: string;
20+
21+
beforeAll(async () => {
22+
await initializeHash();
23+
const baseTmpDir = process.env['TEST_TMPDIR'];
24+
assert(baseTmpDir, 'TEST_TMPDIR is not set');
25+
tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-component-stylesheets-'));
26+
});
27+
28+
afterAll(async () => {
29+
shutdownSassWorkerPool();
30+
await rm(tempRoot, { force: true, recursive: true });
31+
});
32+
33+
it('invalidates cached inline stylesheet errors when the containing component .ts file is invalidated', async () => {
34+
const testDir = await mkdtemp(join(tempRoot, 'inline-error-recovery-'));
35+
const componentFile = join(testDir, 'comp.ts');
36+
const partialFile = join(testDir, '_missing.scss');
37+
const loadCache = new MemoryLoadResultCache();
38+
39+
const bundler = new ComponentStylesheetBundler(
40+
{
41+
workspaceRoot: testDir,
42+
optimization: false,
43+
inlineFonts: false,
44+
sourcemap: false,
45+
outputNames: { bundles: '[name]', media: 'media/[name]' },
46+
target: ['es2022'],
47+
cacheOptions: { enabled: false, path: '', basePath: testDir },
48+
},
49+
'scss',
50+
true,
51+
loadCache,
52+
);
53+
54+
try {
55+
const initialResult = await bundler.bundleInline('@use "./missing";', componentFile, 'scss');
56+
assert(
57+
initialResult.errors,
58+
'Expected initial bundleInline to fail when _missing.scss does not exist',
59+
);
60+
expect(initialResult.errors.length).toBeGreaterThan(0);
61+
62+
await writeFile(partialFile, '.recovered { color: green; }');
63+
resetSassWorkerPoolCaches();
64+
65+
bundler.invalidate([componentFile]);
66+
67+
const recoveredResult = await bundler.bundleInline(
68+
'@use "./missing";',
69+
componentFile,
70+
'scss',
71+
);
72+
expect(recoveredResult.errors).toBeUndefined();
73+
expect(recoveredResult.contents).toContain('.recovered');
74+
expect(recoveredResult.contents).toContain('green');
75+
} finally {
76+
await bundler.dispose();
77+
}
78+
});
79+
80+
it('evicts angular:styles/component loadCache entries when the containing component .ts file is invalidated', async () => {
81+
const testDir = await mkdtemp(join(tempRoot, 'inline-evict-'));
82+
const componentFile = join(testDir, 'comp.ts');
83+
const loadCache = new MemoryLoadResultCache();
84+
const putSpy = spyOn(loadCache, 'put').and.callThrough();
85+
86+
const bundler = new ComponentStylesheetBundler(
87+
{
88+
workspaceRoot: testDir,
89+
optimization: false,
90+
inlineFonts: false,
91+
sourcemap: false,
92+
outputNames: { bundles: '[name]', media: 'media/[name]' },
93+
target: ['es2022'],
94+
cacheOptions: { enabled: false, path: '', basePath: testDir },
95+
},
96+
'scss',
97+
true,
98+
loadCache,
99+
);
100+
101+
try {
102+
const result = await bundler.bundleInline('.btn { color: red; }', componentFile, 'scss');
103+
expect(result.errors).toBeUndefined();
104+
expect(putSpy).toHaveBeenCalledTimes(1);
105+
106+
const cacheKey = putSpy.calls.mostRecent().args[0];
107+
expect(cacheKey).toMatch(/^angular:styles\/component:scss;/);
108+
expect(loadCache.get(cacheKey)).toBeDefined();
109+
110+
bundler.invalidate([componentFile]);
111+
112+
expect(loadCache.get(cacheKey)).toBeUndefined();
113+
} finally {
114+
await bundler.dispose();
115+
}
116+
});
117+
118+
it('persists and reuses stylesheet load results across builds when persistent cache is enabled', async () => {
119+
const testDir = await mkdtemp(join(tempRoot, 'persistent-cache-'));
120+
const cacheDir = join(testDir, '.angular', 'cache');
121+
await mkdir(testDir, { recursive: true });
122+
const styleFile = join(testDir, 'comp.scss');
123+
await writeFile(styleFile, '$primary: blue;\n.card { color: $primary; }\n');
124+
125+
const options = {
126+
workspaceRoot: testDir,
127+
preserveSymlinks: false,
128+
styleIncludePaths: [],
129+
sass: undefined,
130+
cacheOptions: {
131+
enabled: true,
132+
path: cacheDir,
133+
basePath: cacheDir,
134+
},
135+
inlineStyleLanguage: 'scss' as const,
136+
postcssConfiguration: undefined,
137+
tailwindConfiguration: undefined,
138+
};
139+
140+
const firstBundler = createComponentStylesheetBundlerForLibrary(options, false, ['es2022']);
141+
try {
142+
const firstResult = await firstBundler.bundleFile(styleFile);
143+
expect(firstResult.errors).toBeUndefined();
144+
expect(firstResult.contents).toContain('.card{color:#00f}');
145+
} finally {
146+
await firstBundler.dispose();
147+
}
148+
149+
const secondBundler = createComponentStylesheetBundlerForLibrary(options, false, ['es2022']);
150+
try {
151+
const secondResult = await secondBundler.bundleFile(styleFile);
152+
expect(secondResult.errors).toBeUndefined();
153+
expect(secondResult.contents).toContain('.card{color:#00f}');
154+
} finally {
155+
await secondBundler.dispose();
156+
}
157+
});
158+
});

‎packages/angular/build/src/tools/esbuild/load-result-cache.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ export interface LoadResultCache {
1313
get(path: string): OnLoadResult | Promise<OnLoadResult | undefined> | undefined;
1414
put(path: string, result: OnLoadResult): Promise<void>;
1515
invalidate(path: string): boolean;
16+
clear?(): void;
17+
dispose?(): Promise<void> | void;
1618
readonly watchFiles: ReadonlyArray<string>;
1719
}
1820

@@ -108,16 +110,16 @@ export class MemoryLoadResultCache implements LoadResultCache {
108110
}
109111

110112
invalidate(path: string): boolean {
113+
let invalidated = this.#loadResults.delete(path);
111114
const affectedPaths = this.#fileDependencies.get(path);
112-
if (!affectedPaths) {
113-
return false;
114-
}
115-
116-
for (const affected of affectedPaths) {
117-
this.#loadResults.delete(affected);
115+
if (affectedPaths) {
116+
for (const affected of affectedPaths) {
117+
this.#loadResults.delete(affected);
118+
}
119+
invalidated = true;
118120
}
119121

120-
return true;
122+
return invalidated;
121123
}
122124

123125
get watchFiles(): string[] {

0 commit comments

Comments
 (0)