forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplugins.ts
More file actions
390 lines (346 loc) · 13.1 KB
/
plugins.ts
File metadata and controls
390 lines (346 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import assert from 'node:assert';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { platform } from 'node:os';
import path from 'node:path';
import type {
BrowserConfigOptions,
InlineConfig,
UserWorkspaceConfig,
VitestPlugin,
} from 'vitest/node';
import { createBuildAssetsMiddleware } from '../../../../tools/vite/middlewares/assets-middleware';
import { toPosixPath } from '../../../../utils/path';
import type { ResultFile } from '../../../application/results';
import type { NormalizedUnitTestBuilderOptions } from '../../options';
type VitestPlugins = Awaited<ReturnType<typeof VitestPlugin>>;
interface PluginOptions {
workspaceRoot: string;
projectSourceRoot: string;
projectName: string;
buildResultFiles: ReadonlyMap<string, ResultFile>;
testFileToEntryPoint: ReadonlyMap<string, string>;
}
type VitestCoverageOption = Exclude<InlineConfig['coverage'], undefined>;
interface VitestConfigPluginOptions {
browser: BrowserConfigOptions | undefined;
coverage: NormalizedUnitTestBuilderOptions['coverage'];
projectName: string;
projectSourceRoot: string;
reporters?: string[] | [string, object][];
setupFiles: string[];
projectPlugins: Exclude<UserWorkspaceConfig['plugins'], undefined>;
include: string[];
optimizeDepsInclude: string[];
}
async function findTestEnvironment(
projectResolver: NodeJS.RequireResolve,
): Promise<'jsdom' | 'happy-dom'> {
try {
projectResolver('happy-dom');
return 'happy-dom';
} catch {
// happy-dom is not installed, fallback to jsdom
return 'jsdom';
}
}
export async function createVitestConfigPlugin(
options: VitestConfigPluginOptions,
): Promise<VitestPlugins[0]> {
const {
include,
browser,
projectName,
reporters,
setupFiles,
projectPlugins,
projectSourceRoot,
} = options;
const { mergeConfig } = await import('vitest/config');
return {
name: 'angular:vitest-configuration',
async config(config) {
const testConfig = config.test;
if (testConfig?.projects?.length) {
this.warn(
'The "test.projects" option in the Vitest configuration file is not supported. ' +
'The Angular CLI Test system will construct its own project configuration.',
);
delete testConfig.projects;
}
if (testConfig?.include) {
this.warn(
'The "test.include" option in the Vitest configuration file is not supported. ' +
'The Angular CLI Test system will manage test file discovery.',
);
delete testConfig.include;
}
// Merge user-defined plugins from the Vitest config with the CLI's internal plugins.
if (config.plugins) {
const userPlugins = config.plugins.filter(
(plugin) =>
// Only inspect objects with a `name` property as these would be the internal injected plugins
!plugin ||
typeof plugin !== 'object' ||
!('name' in plugin) ||
(!plugin.name.startsWith('angular:') && !plugin.name.startsWith('vitest')),
);
if (userPlugins.length > 0) {
projectPlugins.push(...userPlugins);
}
delete config.plugins;
}
// Add browser source map support
if (browser || testConfig?.browser?.enabled) {
projectPlugins.unshift(createSourcemapSupportPlugin());
setupFiles.unshift('virtual:source-map-support');
}
const projectResolver = createRequire(projectSourceRoot + '/').resolve;
const projectDefaults: UserWorkspaceConfig = {
test: {
setupFiles,
globals: true,
// Default to `false` to align with the Karma/Jasmine experience.
isolate: false,
sequence: { setupFiles: 'list' },
},
optimizeDeps: {
noDiscovery: true,
include: options.optimizeDepsInclude,
},
resolve: {
mainFields: ['es2020', 'module', 'main'],
conditions: ['es2015', 'es2020', 'module', ...(browser ? ['browser'] : [])],
},
};
const { optimizeDeps, resolve } = config;
const projectOverrides: UserWorkspaceConfig = {
test: {
name: projectName,
include,
// CLI provider browser options override, if present
...(browser ? { browser } : {}),
// If the user has not specified an environment, use a smart default.
...(!testConfig?.environment
? { environment: await findTestEnvironment(projectResolver) }
: {}),
},
plugins: projectPlugins,
optimizeDeps,
resolve,
};
const projectBase = mergeConfig(projectDefaults, testConfig ? { test: testConfig } : {});
const projectConfig = mergeConfig(projectBase, projectOverrides);
return {
test: {
coverage: await generateCoverageOption(
options.coverage,
testConfig?.coverage,
projectName,
),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...(reporters ? ({ reporters } as any) : {}),
projects: [projectConfig],
},
};
},
};
}
async function loadResultFile(file: ResultFile): Promise<string> {
if (file.origin === 'memory') {
return new TextDecoder('utf-8').decode(file.contents);
}
return readFile(file.inputPath, 'utf-8');
}
export function createVitestPlugins(pluginOptions: PluginOptions): VitestPlugins {
const { workspaceRoot, buildResultFiles, testFileToEntryPoint } = pluginOptions;
const isWindows = platform() === 'win32';
return [
{
name: 'angular:test-in-memory-provider',
enforce: 'pre',
resolveId: (id, importer) => {
// Fast path for test entry points.
if (testFileToEntryPoint.has(id)) {
return id;
}
// Workaround for Vitest in Windows when a fully qualified absolute path is provided with
// a superfluous leading slash. This can currently occur with the `@vitest/coverage-v8` provider
// when it uses `removeStartsWith(url, FILE_PROTOCOL)` to convert a file URL resulting in
// `/D:/tmp_dir/...` instead of `D:/tmp_dir/...`.
if (id[0] === '/' && isWindows) {
const slicedId = id.slice(1);
if (path.isAbsolute(slicedId)) {
return slicedId;
}
}
if (importer && (id[0] === '.' || id[0] === '/')) {
let fullPath;
if (testFileToEntryPoint.has(importer)) {
fullPath = toPosixPath(path.join(workspaceRoot, id));
} else {
fullPath = toPosixPath(path.join(path.dirname(importer), id));
}
const relativePath = path.relative(workspaceRoot, fullPath);
if (buildResultFiles.has(toPosixPath(relativePath))) {
return fullPath;
}
}
// Determine the base directory for resolution.
let baseDir: string;
if (importer) {
// If the importer is a test entry point, resolve relative to the workspace root.
// Otherwise, resolve relative to the importer's directory.
baseDir = testFileToEntryPoint.has(importer) ? workspaceRoot : path.dirname(importer);
} else {
// If there's no importer, assume the id is relative to the workspace root.
baseDir = workspaceRoot;
}
// Construct the full, absolute path and normalize it to POSIX format.
const fullPath = toPosixPath(path.join(baseDir, id));
if (testFileToEntryPoint.has(fullPath)) {
return fullPath;
}
// Check if the resolved path corresponds to a known build artifact.
const relativePath = path.relative(workspaceRoot, fullPath);
if (buildResultFiles.has(toPosixPath(relativePath))) {
return fullPath;
}
// If the module cannot be resolved from the build artifacts, let other plugins handle it.
return undefined;
},
load: async (id) => {
assert(buildResultFiles.size > 0, 'buildResult must be available for in-memory loading.');
// Attempt to load as a source test file.
const entryPoint = testFileToEntryPoint.get(id);
let outputPath;
if (entryPoint) {
outputPath = entryPoint + '.js';
// To support coverage exclusion of the actual test file, the virtual
// test entry point only references the built and bundled intermediate file.
return {
code: `import "./${outputPath}";`,
};
} else {
// Attempt to load as a built artifact.
const relativePath = path.relative(workspaceRoot, id);
outputPath = toPosixPath(relativePath);
}
const outputFile = buildResultFiles.get(outputPath);
if (outputFile) {
const code = await loadResultFile(outputFile);
const sourceMapPath = outputPath + '.map';
const sourceMapFile = buildResultFiles.get(sourceMapPath);
const sourceMapText = sourceMapFile ? await loadResultFile(sourceMapFile) : undefined;
// Vitest will include files in the coverage report if the sourcemap contains no sources.
// For builder-internal generated code chunks, which are typically helper functions,
// a virtual source is added to the sourcemap to prevent them from being incorrectly
// included in the final coverage report.
const map = sourceMapText ? JSON.parse(sourceMapText) : undefined;
if (map) {
if (!map.sources?.length && !map.sourcesContent?.length && !map.mappings) {
map.sources = ['virtual:builder'];
}
}
return {
code,
map,
};
}
},
configureServer: (server) => {
server.middlewares.use(createBuildAssetsMiddleware(server.config.base, buildResultFiles));
},
},
{
name: 'angular:html-index',
transformIndexHtml: () => {
// Add all global stylesheets
if (buildResultFiles.has('styles.css')) {
return [
{
tag: 'link',
attrs: { href: 'styles.css', rel: 'stylesheet' },
injectTo: 'head',
},
];
}
return [];
},
},
];
}
function createSourcemapSupportPlugin(): VitestPlugins[0] {
return {
name: 'angular:source-map-support',
enforce: 'pre',
resolveId(source) {
if (source.includes('virtual:source-map-support')) {
return '\0source-map-support';
}
},
async load(id) {
if (id !== '\0source-map-support') {
return;
}
const packageResolve = createRequire(__filename).resolve;
const supportPath = packageResolve('source-map-support/browser-source-map-support.js');
const content = await readFile(supportPath, 'utf-8');
// The `source-map-support` library currently relies on `this` being defined in the global scope.
// However, when running in an ESM environment, `this` is undefined.
// To workaround this, we patch the library to use `globalThis` instead of `this`.
return (
content.replaceAll(/this\.(define|sourceMapSupport|base64js)/g, 'globalThis.$1') +
'\n;globalThis.sourceMapSupport.install();'
);
},
};
}
async function generateCoverageOption(
optionsCoverage: NormalizedUnitTestBuilderOptions['coverage'],
configCoverage: VitestCoverageOption | undefined,
projectName: string,
): Promise<VitestCoverageOption> {
let defaultExcludes: string[] = [];
if (optionsCoverage.exclude) {
try {
const vitestConfig = await import('vitest/config');
defaultExcludes = vitestConfig.coverageConfigDefaults.exclude;
} catch {}
}
return {
excludeAfterRemap: true,
reportsDirectory:
configCoverage?.reportsDirectory ?? toPosixPath(path.join('coverage', projectName)),
...(optionsCoverage.enabled !== undefined ? { enabled: optionsCoverage.enabled } : {}),
// Vitest performs a pre-check and a post-check for sourcemaps.
// The pre-check uses the bundled files, so specific bundled entry points and chunks need to be included.
// The post-check uses the original source files, so the user's include is used.
...(optionsCoverage.include
? { include: ['spec-*.js', 'chunk-*.js', ...optionsCoverage.include] }
: {}),
thresholds: optionsCoverage.thresholds,
watermarks: optionsCoverage.watermarks,
// Special handling for `exclude`/`reporters` due to an undefined value causing upstream failures
...(optionsCoverage.exclude
? {
exclude: [
// Augment the default exclude https://vitest.dev/config/#coverage-exclude
// with the user defined exclusions
...optionsCoverage.exclude,
...defaultExcludes,
],
}
: {}),
...(optionsCoverage.reporters
? ({ reporter: optionsCoverage.reporters } satisfies VitestCoverageOption)
: {}),
};
}