Skip to content

Commit 18d6b4f

Browse files
committed
perf(@angular/build): deduplicate PostCSS dir-dependency glob scans across stylesheets
Cache in-flight and resolved PostCSS `dir-dependency` `glob()` promises per `${dir}\0${globPattern}` key within `StylesheetPluginFactory` and across instances sharing a `LoadResultCache`, clearing the cache on invalidation. This prevents redundant concurrent directory scans across component stylesheets (e.g., with Tailwind CSS).
1 parent 0fd4404 commit 18d6b4f

2 files changed

Lines changed: 270 additions & 5 deletions

File tree

‎packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts‎

Lines changed: 65 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -111,14 +111,54 @@ export interface StylesheetLanguage {
111111
*/
112112
const postcssProcessors = new Map<string, WeakRef<PostcssProcessor>>();
113113

114+
/**
115+
* Cached PostCSS `dir-dependency` glob results keyed by `LoadResultCache` instance, allowing
116+
* multiple `StylesheetPluginFactory` instances sharing a load cache to deduplicate directory scans.
117+
*/
118+
const dirDependencyCaches = new WeakMap<LoadResultCache, Map<string, Promise<string[]>>>();
119+
120+
function getDirDependencyCache(cache?: LoadResultCache): Map<string, Promise<string[]>> {
121+
if (!cache) {
122+
return new Map();
123+
}
124+
125+
let dirDependencyCache = dirDependencyCaches.get(cache);
126+
if (!dirDependencyCache) {
127+
dirDependencyCache = new Map();
128+
dirDependencyCaches.set(cache, dirDependencyCache);
129+
130+
const originalInvalidate = cache.invalidate.bind(cache);
131+
cache.invalidate = (path: string) => {
132+
dirDependencyCache?.clear();
133+
134+
return originalInvalidate(path);
135+
};
136+
137+
if ('clear' in cache && typeof cache.clear === 'function') {
138+
const originalClear = cache.clear.bind(cache);
139+
cache.clear = () => {
140+
dirDependencyCache?.clear();
141+
originalClear();
142+
};
143+
}
144+
}
145+
146+
return dirDependencyCache;
147+
}
148+
114149
export class StylesheetPluginFactory {
150+
readonly #dirDependencyCache: Map<string, Promise<string[]>>;
151+
115152
constructor(
116153
private readonly options: StylesheetPluginOptions,
117154
private readonly cache?: LoadResultCache,
118-
) {}
155+
) {
156+
this.#dirDependencyCache = getDirDependencyCache(cache);
157+
}
119158

120159
create(language: Readonly<StylesheetLanguage>): Plugin {
121160
const { cache, options, setupPostcss } = this;
161+
const dirDependencyCache = this.#dirDependencyCache;
122162

123163
// Return a noop plugin if no load actions are required
124164
if (!language.process && !options.postcssConfiguration && !options.tailwindConfiguration) {
@@ -134,6 +174,10 @@ export class StylesheetPluginFactory {
134174
// Setup postcss if needed
135175
let postcssProcessor: PostcssProcessor | undefined;
136176
build.onStart(async () => {
177+
if (!cache) {
178+
dirDependencyCache.clear();
179+
}
180+
137181
try {
138182
postcssProcessor = await setupPostcss;
139183
} catch {
@@ -175,6 +219,7 @@ export class StylesheetPluginFactory {
175219
options,
176220
build,
177221
postcssProcessor,
222+
dirDependencyCache,
178223
);
179224
}),
180225
);
@@ -193,6 +238,7 @@ export class StylesheetPluginFactory {
193238
options,
194239
build,
195240
postcssProcessor,
241+
dirDependencyCache,
196242
);
197243
}),
198244
);
@@ -264,6 +310,7 @@ async function processStylesheet(
264310
options: StylesheetPluginOptions,
265311
build: PluginBuild,
266312
postcssProcessor: PostcssProcessor | undefined,
313+
dirDependencyCache: Map<string, Promise<string[]>>,
267314
) {
268315
let result: OnLoadResult;
269316

@@ -292,6 +339,7 @@ async function processStylesheet(
292339
filename,
293340
postcssProcessor,
294341
options,
342+
dirDependencyCache,
295343
);
296344

297345
// Merge results
@@ -348,6 +396,7 @@ async function compileString(
348396
filename: string,
349397
postcssProcessor: import('postcss').Processor,
350398
options: StylesheetPluginOptions,
399+
dirDependencyCache: Map<string, Promise<string[]>>,
351400
): Promise<OnLoadResult> {
352401
try {
353402
const postcssResult = await postcssProcessor.process(data, {
@@ -401,10 +450,21 @@ async function compileString(
401450
typeof resultMessage['glob'] === 'string'
402451
) {
403452
loadResult.watchFiles ??= [];
404-
const dependencies = await glob(resultMessage['glob'], {
405-
absolute: true,
406-
cwd: resultMessage['dir'],
407-
});
453+
const dir = resultMessage['dir'];
454+
const globPattern = resultMessage['glob'];
455+
const cacheKey = `${dir}\0${globPattern}`;
456+
let dependenciesPromise = dirDependencyCache.get(cacheKey);
457+
if (!dependenciesPromise) {
458+
dependenciesPromise = glob(globPattern, {
459+
absolute: true,
460+
cwd: dir,
461+
}).catch((error) => {
462+
dirDependencyCache.delete(cacheKey);
463+
throw error;
464+
});
465+
dirDependencyCache.set(cacheKey, dependenciesPromise);
466+
}
467+
const dependencies = await dependenciesPromise;
408468
loadResult.watchFiles.push(...dependencies);
409469
}
410470
}
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
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 type { OnLoadArgs, OnLoadResult, PluginBuild } from 'esbuild';
10+
import assert from 'node:assert';
11+
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
12+
import { join } from 'node:path';
13+
import { MemoryLoadResultCache } from '../load-result-cache';
14+
import { CssStylesheetLanguage } from './css-language';
15+
import { StylesheetPluginFactory, type StylesheetPluginOptions } from './stylesheet-plugin-factory';
16+
17+
describe('StylesheetPluginFactory dir-dependency caching', () => {
18+
let tempRoot: string;
19+
let pluginPath: string;
20+
21+
beforeAll(async () => {
22+
const baseTmpDir = process.env['TEST_TMPDIR'];
23+
assert(baseTmpDir, 'TEST_TMPDIR is not set');
24+
tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-stylesheet-plugin-factory-'));
25+
pluginPath = join(tempRoot, 'dir-dep-plugin.cjs');
26+
27+
await writeFile(
28+
pluginPath,
29+
`
30+
module.exports = (opts = {}) => ({
31+
postcssPlugin: 'dir-dep-test-plugin',
32+
Once(root, { result }) {
33+
result.messages.push({
34+
type: 'dir-dependency',
35+
plugin: 'dir-dep-test-plugin',
36+
dir: opts.dir,
37+
glob: opts.glob || '**/*.html',
38+
});
39+
},
40+
});
41+
module.exports.postcss = true;
42+
`,
43+
);
44+
});
45+
46+
afterAll(async () => {
47+
await rm(tempRoot, { force: true, recursive: true });
48+
});
49+
50+
async function setupPluginAndGetComponentLoad(
51+
options: StylesheetPluginOptions,
52+
cache?: MemoryLoadResultCache,
53+
): Promise<(path: string) => Promise<OnLoadResult | null | undefined>> {
54+
const factory = new StylesheetPluginFactory(options, cache);
55+
const plugin = factory.create(CssStylesheetLanguage);
56+
57+
let onStartCallback: (() => Promise<unknown>) | undefined;
58+
let componentLoadCallback:
59+
| ((
60+
args: OnLoadArgs,
61+
) => OnLoadResult | null | undefined | Promise<OnLoadResult | null | undefined>)
62+
| undefined;
63+
64+
const buildStub = {
65+
onStart(cb: () => Promise<unknown>) {
66+
onStartCallback = cb;
67+
},
68+
onLoad(
69+
opts: { filter: RegExp; namespace?: string },
70+
cb: (
71+
args: OnLoadArgs,
72+
) => OnLoadResult | null | undefined | Promise<OnLoadResult | null | undefined>,
73+
) {
74+
if (opts.namespace === 'angular:styles/component') {
75+
componentLoadCallback = cb;
76+
}
77+
},
78+
} as unknown as PluginBuild;
79+
80+
await plugin.setup(buildStub);
81+
await onStartCallback?.();
82+
assert(componentLoadCallback, 'Expected component onLoad callback to be registered');
83+
const load = componentLoadCallback;
84+
85+
return (path: string) =>
86+
Promise.resolve(
87+
load({
88+
path,
89+
namespace: 'angular:styles/component',
90+
suffix: '',
91+
pluginData: undefined,
92+
with: {},
93+
}),
94+
);
95+
}
96+
97+
it('should resolve watchFiles from PostCSS dir-dependency messages and reuse cached glob results across stylesheets', async () => {
98+
const scanDir = await mkdtemp(join(tempRoot, 'scan-single-'));
99+
await mkdir(join(scanDir, 'nested'), { recursive: true });
100+
const fileA = join(scanDir, 'a.html');
101+
const fileB = join(scanDir, 'nested', 'b.html');
102+
await writeFile(fileA, '<div>A</div>');
103+
await writeFile(fileB, '<div>B</div>');
104+
await writeFile(join(scanDir, 'ignored.txt'), 'ignore me');
105+
106+
const comp1Key = `css;1;${join(scanDir, 'comp1.css')}`;
107+
const comp2Key = `css;2;${join(scanDir, 'comp2.css')}`;
108+
109+
const loadComponent = await setupPluginAndGetComponentLoad({
110+
sourcemap: false,
111+
inlineComponentData: {
112+
[comp1Key]: '.a { color: red; }',
113+
[comp2Key]: '.b { color: blue; }',
114+
},
115+
postcssConfiguration: {
116+
configPath: join(tempRoot, 'postcss.config.json'),
117+
config: {
118+
plugins: [[pluginPath, { dir: scanDir, glob: '**/*.html' }]],
119+
},
120+
},
121+
});
122+
123+
const result1 = await loadComponent(comp1Key);
124+
expect(result1?.watchFiles).toBeDefined();
125+
expect(result1?.watchFiles).toContain(fileA);
126+
expect(result1?.watchFiles).toContain(fileB);
127+
expect(result1?.watchFiles).not.toContain(join(scanDir, 'ignored.txt'));
128+
129+
// Add a new matching file on disk without starting a new build or invalidating cache.
130+
const fileC = join(scanDir, 'c.html');
131+
await writeFile(fileC, '<div>C</div>');
132+
133+
// Second stylesheet in the same build should reuse the cached glob result without re-scanning.
134+
const result2 = await loadComponent(comp2Key);
135+
expect(result2?.watchFiles).toContain(fileA);
136+
expect(result2?.watchFiles).toContain(fileB);
137+
expect(result2?.watchFiles).not.toContain(fileC);
138+
});
139+
140+
it('should share cached dir-dependency glob results across StylesheetPluginFactory instances sharing a LoadResultCache and invalidate on cache.invalidate', async () => {
141+
const scanDir = await mkdtemp(join(tempRoot, 'scan-shared-'));
142+
const fileA = join(scanDir, 'a.html');
143+
await writeFile(fileA, '<div>A</div>');
144+
145+
const sharedCache = new MemoryLoadResultCache();
146+
const postcssConfiguration = {
147+
configPath: join(tempRoot, 'postcss.config.json'),
148+
config: {
149+
plugins: [[pluginPath, { dir: scanDir, glob: '**/*.html' }]] as [
150+
string,
151+
Record<string, unknown>,
152+
][],
153+
},
154+
};
155+
156+
const comp1Key = `css;1;${join(scanDir, 'comp1.css')}`;
157+
const loadComp1 = await setupPluginAndGetComponentLoad(
158+
{
159+
sourcemap: false,
160+
inlineComponentData: { [comp1Key]: '.a { color: red; }' },
161+
postcssConfiguration,
162+
},
163+
sharedCache,
164+
);
165+
166+
const result1 = await loadComp1(comp1Key);
167+
expect(result1?.watchFiles).toContain(fileA);
168+
169+
// Write a new file after the first component was compiled.
170+
const fileB = join(scanDir, 'b.html');
171+
await writeFile(fileB, '<div>B</div>');
172+
173+
// A second StylesheetPluginFactory sharing the same LoadResultCache should reuse the cached glob promise.
174+
const comp2Key = `css;2;${join(scanDir, 'comp2.css')}`;
175+
const loadComp2 = await setupPluginAndGetComponentLoad(
176+
{
177+
sourcemap: false,
178+
inlineComponentData: { [comp2Key]: '.b { color: blue; }' },
179+
postcssConfiguration,
180+
},
181+
sharedCache,
182+
);
183+
184+
const result2 = await loadComp2(comp2Key);
185+
expect(result2?.watchFiles).toContain(fileA);
186+
expect(result2?.watchFiles).not.toContain(fileB);
187+
188+
// Invalidating the shared LoadResultCache should clear the dir-dependency glob cache.
189+
sharedCache.invalidate(fileA);
190+
191+
const comp3Key = `css;3;${join(scanDir, 'comp3.css')}`;
192+
const loadComp3 = await setupPluginAndGetComponentLoad(
193+
{
194+
sourcemap: false,
195+
inlineComponentData: { [comp3Key]: '.c { color: green; }' },
196+
postcssConfiguration,
197+
},
198+
sharedCache,
199+
);
200+
201+
const result3 = await loadComp3(comp3Key);
202+
expect(result3?.watchFiles).toContain(fileA);
203+
expect(result3?.watchFiles).toContain(fileB);
204+
});
205+
});

0 commit comments

Comments
 (0)