@angular/build 19.2.0-next.1 → 19.2.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/builders.json +5 -0
  2. package/package.json +18 -13
  3. package/src/builders/application/build-action.js +6 -1
  4. package/src/builders/application/execute-build.js +1 -5
  5. package/src/builders/application/execute-post-bundle.js +2 -2
  6. package/src/builders/application/i18n.js +6 -3
  7. package/src/builders/application/options.d.ts +5 -1
  8. package/src/builders/application/options.js +9 -1
  9. package/src/builders/dev-server/schema.d.ts +4 -4
  10. package/src/builders/dev-server/schema.json +2 -2
  11. package/src/builders/dev-server/vite-server.js +45 -4
  12. package/src/builders/karma/application_builder.d.ts +15 -0
  13. package/src/builders/karma/application_builder.js +490 -0
  14. package/src/builders/karma/find-tests.d.ts +15 -0
  15. package/src/builders/karma/find-tests.js +144 -0
  16. package/src/builders/karma/index.d.ts +23 -0
  17. package/src/builders/karma/index.js +135 -0
  18. package/src/builders/karma/polyfills/init_sourcemaps.js +10 -0
  19. package/src/builders/karma/polyfills/init_test_bed.js +19 -0
  20. package/src/builders/karma/polyfills/jasmine_global.js +18 -0
  21. package/src/builders/karma/polyfills/jasmine_global_cleanup.js +14 -0
  22. package/src/builders/karma/schema.d.ts +248 -0
  23. package/src/builders/karma/schema.js +15 -0
  24. package/src/builders/karma/schema.json +347 -0
  25. package/src/private.d.ts +2 -0
  26. package/src/private.js +6 -1
  27. package/src/tools/angular/compilation/hmr-candidates.js +43 -12
  28. package/src/tools/babel/plugins/add-code-coverage.js +8 -1
  29. package/src/tools/esbuild/angular/compiler-plugin.js +8 -3
  30. package/src/tools/esbuild/i18n-inliner.d.ts +9 -0
  31. package/src/tools/esbuild/i18n-inliner.js +110 -21
  32. package/src/tools/esbuild/index-html-generator.js +1 -8
  33. package/src/tools/esbuild/stylesheets/less-language.js +16 -4
  34. package/src/tools/esbuild/stylesheets/sass-language.js +2 -5
  35. package/src/tools/esbuild/utils.js +4 -1
  36. package/src/tools/vite/middlewares/html-fallback-middleware.js +2 -1
  37. package/src/tools/vite/plugins/angular-memory-plugin.d.ts +1 -1
  38. package/src/tools/vite/plugins/angular-memory-plugin.js +11 -16
  39. package/src/utils/error.js +2 -2
  40. package/src/utils/index-file/auto-csp.js +1 -1
  41. package/src/utils/index-file/index-html-generator.js +3 -2
  42. package/src/utils/index-file/inline-critical-css.d.ts +1 -0
  43. package/src/utils/index-file/inline-critical-css.js +11 -7
  44. package/src/utils/load-translations.js +3 -3
  45. package/src/utils/normalize-asset-patterns.js +3 -3
  46. package/src/utils/normalize-cache.js +1 -1
  47. package/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.js +1 -2
  48. package/src/utils/server-rendering/manifest.js +7 -2
  49. package/src/utils/server-rendering/prerender.js +3 -3
  50. package/src/utils/server-rendering/render-worker.js +2 -2
  51. package/src/utils/server-rendering/routes-extractor-worker.js +2 -2
  52. package/src/utils/service-worker.js +2 -2
  53. package/src/utils/version.js +2 -2
@@ -0,0 +1,490 @@
1
+ "use strict";
2
+ /**
3
+ * @license
4
+ * Copyright Google LLC All Rights Reserved.
5
+ *
6
+ * Use of this source code is governed by an MIT-style license that can be
7
+ * found in the LICENSE file at https://angular.dev/license
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
42
+ var __importDefault = (this && this.__importDefault) || function (mod) {
43
+ return (mod && mod.__esModule) ? mod : { "default": mod };
44
+ };
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.execute = execute;
47
+ exports.writeTestFiles = writeTestFiles;
48
+ const private_1 = require("@angular/build/private");
49
+ const fast_glob_1 = __importDefault(require("fast-glob"));
50
+ const node_crypto_1 = require("node:crypto");
51
+ const fs = __importStar(require("node:fs/promises"));
52
+ const node_module_1 = require("node:module");
53
+ const path = __importStar(require("node:path"));
54
+ const bundler_context_1 = require("../../tools/esbuild/bundler-context");
55
+ const schema_1 = require("../application/schema");
56
+ const find_tests_1 = require("./find-tests");
57
+ const localResolve = (0, node_module_1.createRequire)(__filename).resolve;
58
+ class ApplicationBuildError extends Error {
59
+ constructor(message) {
60
+ super(message);
61
+ this.name = 'ApplicationBuildError';
62
+ }
63
+ }
64
+ const LATEST_BUILD_FILES_TOKEN = 'angularLatestBuildFiles';
65
+ class AngularAssetsMiddleware {
66
+ serveFile;
67
+ latestBuildFiles;
68
+ static $inject = ['serveFile', LATEST_BUILD_FILES_TOKEN];
69
+ static NAME = 'angular-test-assets';
70
+ constructor(serveFile, latestBuildFiles) {
71
+ this.serveFile = serveFile;
72
+ this.latestBuildFiles = latestBuildFiles;
73
+ }
74
+ handle(req, res, next) {
75
+ let err = null;
76
+ try {
77
+ const url = new URL(`http://${req.headers['host']}${req.url}`);
78
+ const file = this.latestBuildFiles.files[url.pathname.slice(1)];
79
+ if (file?.origin === 'disk') {
80
+ this.serveFile(file.inputPath, undefined, res);
81
+ return;
82
+ }
83
+ else if (file?.origin === 'memory') {
84
+ // Include pathname to help with Content-Type headers.
85
+ this.serveFile(`/unused/${url.pathname}`, undefined, res, undefined, file.contents, true);
86
+ return;
87
+ }
88
+ }
89
+ catch (e) {
90
+ err = e;
91
+ }
92
+ next(err);
93
+ }
94
+ static createPlugin(initialFiles) {
95
+ return {
96
+ [LATEST_BUILD_FILES_TOKEN]: ['value', { files: { ...initialFiles.files } }],
97
+ [`middleware:${AngularAssetsMiddleware.NAME}`]: [
98
+ 'factory',
99
+ Object.assign((...args) => {
100
+ const inst = new AngularAssetsMiddleware(...args);
101
+ return inst.handle.bind(inst);
102
+ }, AngularAssetsMiddleware),
103
+ ],
104
+ };
105
+ }
106
+ }
107
+ class AngularPolyfillsPlugin {
108
+ static $inject = ['config.files'];
109
+ static NAME = 'angular-polyfills';
110
+ static createPlugin(polyfillsFile, jasmineCleanupFiles) {
111
+ return {
112
+ // This has to be a "reporter" because reporters run _after_ frameworks
113
+ // and karma-jasmine-html-reporter injects additional scripts that may
114
+ // depend on Jasmine but aren't modules - which means that they would run
115
+ // _before_ all module code (including jasmine).
116
+ [`reporter:${AngularPolyfillsPlugin.NAME}`]: [
117
+ 'factory',
118
+ Object.assign((files) => {
119
+ // The correct order is zone.js -> jasmine -> zone.js/testing.
120
+ // Jasmine has to see the patched version of the global `setTimeout`
121
+ // function so it doesn't cache the unpatched version. And /testing
122
+ // needs to see the global `jasmine` object so it can patch it.
123
+ const polyfillsIndex = 0;
124
+ files.splice(polyfillsIndex, 0, polyfillsFile);
125
+ // Insert just before test_main.js.
126
+ const zoneTestingIndex = files.findIndex((f) => {
127
+ if (typeof f === 'string') {
128
+ return false;
129
+ }
130
+ return f.pattern.endsWith('/test_main.js');
131
+ });
132
+ if (zoneTestingIndex === -1) {
133
+ throw new Error('Could not find test entrypoint file.');
134
+ }
135
+ files.splice(zoneTestingIndex, 0, jasmineCleanupFiles);
136
+ // We need to ensure that all files are served as modules, otherwise
137
+ // the order in the files list gets really confusing: Karma doesn't
138
+ // set defer on scripts, so all scripts with type=js will run first,
139
+ // even if type=module files appeared earlier in `files`.
140
+ for (const f of files) {
141
+ if (typeof f === 'string') {
142
+ throw new Error(`Unexpected string-based file: "${f}"`);
143
+ }
144
+ if (f.included === false) {
145
+ // Don't worry about files that aren't included on the initial
146
+ // page load. `type` won't affect them.
147
+ continue;
148
+ }
149
+ if (f.pattern.endsWith('.js') && 'js' === (f.type ?? 'js')) {
150
+ f.type = 'module';
151
+ }
152
+ }
153
+ // Add browser sourcemap support as a classic script
154
+ files.unshift({
155
+ pattern: localResolve('source-map-support/browser-source-map-support.js'),
156
+ included: true,
157
+ watched: false,
158
+ });
159
+ }, AngularPolyfillsPlugin),
160
+ ],
161
+ };
162
+ }
163
+ }
164
+ function injectKarmaReporter(buildOptions, buildIterator, karmaConfig, controller) {
165
+ const reporterName = 'angular-progress-notifier';
166
+ class ProgressNotifierReporter {
167
+ emitter;
168
+ latestBuildFiles;
169
+ static $inject = ['emitter', LATEST_BUILD_FILES_TOKEN];
170
+ constructor(emitter, latestBuildFiles) {
171
+ this.emitter = emitter;
172
+ this.latestBuildFiles = latestBuildFiles;
173
+ this.startWatchingBuild();
174
+ }
175
+ startWatchingBuild() {
176
+ void (async () => {
177
+ // This is effectively "for await of but skip what's already consumed".
178
+ let isDone = false; // to mark the loop condition as "not constant".
179
+ while (!isDone) {
180
+ const { done, value: buildOutput } = await buildIterator.next();
181
+ if (done) {
182
+ isDone = true;
183
+ break;
184
+ }
185
+ if (buildOutput.kind === private_1.ResultKind.Failure) {
186
+ controller.enqueue({ success: false, message: 'Build failed' });
187
+ }
188
+ else if (buildOutput.kind === private_1.ResultKind.Incremental ||
189
+ buildOutput.kind === private_1.ResultKind.Full) {
190
+ if (buildOutput.kind === private_1.ResultKind.Full) {
191
+ this.latestBuildFiles.files = buildOutput.files;
192
+ }
193
+ else {
194
+ this.latestBuildFiles.files = {
195
+ ...this.latestBuildFiles.files,
196
+ ...buildOutput.files,
197
+ };
198
+ }
199
+ await writeTestFiles(buildOutput.files, buildOptions.outputPath);
200
+ this.emitter.refreshFiles();
201
+ }
202
+ }
203
+ })();
204
+ }
205
+ onRunComplete = function (_browsers, results) {
206
+ if (results.exitCode === 0) {
207
+ controller.enqueue({ success: true });
208
+ }
209
+ else {
210
+ controller.enqueue({ success: false });
211
+ }
212
+ };
213
+ }
214
+ karmaConfig.reporters ??= [];
215
+ karmaConfig.reporters.push(reporterName);
216
+ karmaConfig.plugins ??= [];
217
+ karmaConfig.plugins.push({
218
+ [`reporter:${reporterName}`]: [
219
+ 'factory',
220
+ Object.assign((...args) => new ProgressNotifierReporter(...args), ProgressNotifierReporter),
221
+ ],
222
+ });
223
+ }
224
+ function execute(options, context, karmaOptions, transforms = {}) {
225
+ let karmaServer;
226
+ return new ReadableStream({
227
+ async start(controller) {
228
+ let init;
229
+ try {
230
+ init = await initializeApplication(options, context, karmaOptions, transforms);
231
+ }
232
+ catch (err) {
233
+ if (err instanceof ApplicationBuildError) {
234
+ controller.enqueue({ success: false, message: err.message });
235
+ controller.close();
236
+ return;
237
+ }
238
+ throw err;
239
+ }
240
+ const [karma, karmaConfig, buildOptions, buildIterator] = init;
241
+ // If `--watch` is explicitly enabled or if we are keeping the Karma
242
+ // process running, we should hook Karma into the build.
243
+ if (buildIterator) {
244
+ injectKarmaReporter(buildOptions, buildIterator, karmaConfig, controller);
245
+ }
246
+ // Close the stream once the Karma server returns.
247
+ karmaServer = new karma.Server(karmaConfig, (exitCode) => {
248
+ controller.enqueue({ success: exitCode === 0 });
249
+ controller.close();
250
+ });
251
+ await karmaServer.start();
252
+ },
253
+ async cancel() {
254
+ await karmaServer?.stop();
255
+ },
256
+ });
257
+ }
258
+ async function getProjectSourceRoot(context) {
259
+ // We have already validated that the project name is set before calling this function.
260
+ const projectName = context.target?.project;
261
+ if (!projectName) {
262
+ return context.workspaceRoot;
263
+ }
264
+ const projectMetadata = await context.getProjectMetadata(projectName);
265
+ const sourceRoot = (projectMetadata.sourceRoot ?? projectMetadata.root ?? '');
266
+ return path.join(context.workspaceRoot, sourceRoot);
267
+ }
268
+ function normalizePolyfills(polyfills) {
269
+ if (typeof polyfills === 'string') {
270
+ polyfills = [polyfills];
271
+ }
272
+ else if (!polyfills) {
273
+ polyfills = [];
274
+ }
275
+ const jasmineGlobalEntryPoint = localResolve('./polyfills/jasmine_global.js');
276
+ const jasmineGlobalCleanupEntrypoint = localResolve('./polyfills/jasmine_global_cleanup.js');
277
+ const sourcemapEntrypoint = localResolve('./polyfills/init_sourcemaps.js');
278
+ const zoneTestingEntryPoint = 'zone.js/testing';
279
+ const polyfillsExludingZoneTesting = polyfills.filter((p) => p !== zoneTestingEntryPoint);
280
+ return [
281
+ polyfillsExludingZoneTesting.concat([jasmineGlobalEntryPoint, sourcemapEntrypoint]),
282
+ polyfillsExludingZoneTesting.length === polyfills.length
283
+ ? [jasmineGlobalCleanupEntrypoint]
284
+ : [jasmineGlobalCleanupEntrypoint, zoneTestingEntryPoint],
285
+ ];
286
+ }
287
+ async function collectEntrypoints(options, context, projectSourceRoot) {
288
+ // Glob for files to test.
289
+ const testFiles = await (0, find_tests_1.findTests)(options.include ?? [], options.exclude ?? [], context.workspaceRoot, projectSourceRoot);
290
+ return (0, find_tests_1.getTestEntrypoints)(testFiles, { projectSourceRoot, workspaceRoot: context.workspaceRoot });
291
+ }
292
+ async function initializeApplication(options, context, karmaOptions, transforms = {}) {
293
+ const outputPath = path.join(context.workspaceRoot, 'dist/test-out', (0, node_crypto_1.randomUUID)());
294
+ const projectSourceRoot = await getProjectSourceRoot(context);
295
+ const [karma, entryPoints] = await Promise.all([
296
+ Promise.resolve().then(() => __importStar(require('karma'))),
297
+ collectEntrypoints(options, context, projectSourceRoot),
298
+ fs.rm(outputPath, { recursive: true, force: true }),
299
+ ]);
300
+ const mainName = 'test_main';
301
+ if (options.main) {
302
+ entryPoints.set(mainName, options.main);
303
+ }
304
+ else {
305
+ entryPoints.set(mainName, localResolve('./polyfills/init_test_bed.js'));
306
+ }
307
+ const instrumentForCoverage = options.codeCoverage
308
+ ? createInstrumentationFilter(projectSourceRoot, getInstrumentationExcludedPaths(context.workspaceRoot, options.codeCoverageExclude ?? []))
309
+ : undefined;
310
+ const [polyfills, jasmineCleanup] = normalizePolyfills(options.polyfills);
311
+ for (let idx = 0; idx < jasmineCleanup.length; ++idx) {
312
+ entryPoints.set(`jasmine-cleanup-${idx}`, jasmineCleanup[idx]);
313
+ }
314
+ const buildOptions = {
315
+ assets: options.assets,
316
+ entryPoints,
317
+ tsConfig: options.tsConfig,
318
+ outputPath,
319
+ aot: options.aot,
320
+ index: false,
321
+ outputHashing: schema_1.OutputHashing.None,
322
+ optimization: false,
323
+ sourceMap: options.codeCoverage
324
+ ? {
325
+ scripts: true,
326
+ styles: true,
327
+ vendor: true,
328
+ }
329
+ : options.sourceMap,
330
+ instrumentForCoverage,
331
+ styles: options.styles,
332
+ scripts: options.scripts,
333
+ polyfills,
334
+ webWorkerTsConfig: options.webWorkerTsConfig,
335
+ watch: options.watch ?? !karmaOptions.singleRun,
336
+ stylePreprocessorOptions: options.stylePreprocessorOptions,
337
+ inlineStyleLanguage: options.inlineStyleLanguage,
338
+ fileReplacements: options.fileReplacements,
339
+ define: options.define,
340
+ loader: options.loader,
341
+ externalDependencies: options.externalDependencies,
342
+ };
343
+ // Build tests with `application` builder, using test files as entry points.
344
+ const [buildOutput, buildIterator] = await first((0, private_1.buildApplicationInternal)(buildOptions, context), { cancel: !buildOptions.watch });
345
+ if (buildOutput.kind === private_1.ResultKind.Failure) {
346
+ throw new ApplicationBuildError('Build failed');
347
+ }
348
+ else if (buildOutput.kind !== private_1.ResultKind.Full) {
349
+ throw new ApplicationBuildError('A full build result is required from the application builder.');
350
+ }
351
+ // Write test files
352
+ await writeTestFiles(buildOutput.files, buildOptions.outputPath);
353
+ // We need to add this to the beginning *after* the testing framework has
354
+ // prepended its files.
355
+ const polyfillsFile = {
356
+ pattern: `${outputPath}/polyfills.js`,
357
+ included: true,
358
+ served: true,
359
+ type: 'module',
360
+ watched: false,
361
+ };
362
+ const jasmineCleanupFiles = {
363
+ pattern: `${outputPath}/jasmine-cleanup-*.js`,
364
+ included: true,
365
+ served: true,
366
+ type: 'module',
367
+ watched: false,
368
+ };
369
+ karmaOptions.files ??= [];
370
+ if (options.scripts?.length) {
371
+ // This should be more granular to support named bundles.
372
+ // However, it replicates the behavior of the Karma Webpack-based builder.
373
+ karmaOptions.files.push({
374
+ pattern: `${outputPath}/scripts.js`,
375
+ watched: false,
376
+ type: 'js',
377
+ });
378
+ }
379
+ karmaOptions.files.push(
380
+ // Serve global setup script.
381
+ { pattern: `${outputPath}/${mainName}.js`, type: 'module', watched: false },
382
+ // Serve all source maps.
383
+ { pattern: `${outputPath}/*.map`, included: false, watched: false },
384
+ // These are the test entrypoints.
385
+ { pattern: `${outputPath}/spec-*.js`, type: 'module', watched: false });
386
+ if (hasChunkOrWorkerFiles(buildOutput.files)) {
387
+ karmaOptions.files.push(
388
+ // Allow loading of chunk-* files but don't include them all on load.
389
+ {
390
+ pattern: `${outputPath}/{chunk,worker}-*.js`,
391
+ type: 'module',
392
+ included: false,
393
+ watched: false,
394
+ });
395
+ }
396
+ if (options.styles?.length) {
397
+ // Serve CSS outputs on page load, these are the global styles.
398
+ karmaOptions.files.push({ pattern: `${outputPath}/*.css`, type: 'css', watched: false });
399
+ }
400
+ const parsedKarmaConfig = await karma.config.parseConfig(options.karmaConfig && path.resolve(context.workspaceRoot, options.karmaConfig), transforms.karmaOptions ? transforms.karmaOptions(karmaOptions) : karmaOptions, { promiseConfig: true, throwErrors: true });
401
+ // Remove the webpack plugin/framework:
402
+ // Alternative would be to make the Karma plugin "smart" but that's a tall order
403
+ // with managing unneeded imports etc..
404
+ parsedKarmaConfig.plugins ??= [];
405
+ const pluginLengthBefore = parsedKarmaConfig.plugins.length;
406
+ parsedKarmaConfig.plugins = parsedKarmaConfig.plugins.filter((plugin) => {
407
+ if (typeof plugin === 'string') {
408
+ return plugin !== 'framework:@angular-devkit/build-angular';
409
+ }
410
+ return !plugin['framework:@angular-devkit/build-angular'];
411
+ });
412
+ parsedKarmaConfig.frameworks ??= [];
413
+ parsedKarmaConfig.frameworks = parsedKarmaConfig.frameworks.filter((framework) => framework !== '@angular-devkit/build-angular');
414
+ const pluginLengthAfter = parsedKarmaConfig.plugins.length;
415
+ if (pluginLengthBefore !== pluginLengthAfter) {
416
+ context.logger.warn(`Ignoring framework "@angular-devkit/build-angular" from karma config file because it's not compatible with the application builder.`);
417
+ }
418
+ parsedKarmaConfig.plugins.push(AngularAssetsMiddleware.createPlugin(buildOutput));
419
+ parsedKarmaConfig.middleware ??= [];
420
+ parsedKarmaConfig.middleware.push(AngularAssetsMiddleware.NAME);
421
+ parsedKarmaConfig.plugins.push(AngularPolyfillsPlugin.createPlugin(polyfillsFile, jasmineCleanupFiles));
422
+ parsedKarmaConfig.reporters ??= [];
423
+ parsedKarmaConfig.reporters.push(AngularPolyfillsPlugin.NAME);
424
+ // When using code-coverage, auto-add karma-coverage.
425
+ // This was done as part of the karma plugin for webpack.
426
+ if (options.codeCoverage &&
427
+ !parsedKarmaConfig.reporters?.some((r) => r === 'coverage' || r === 'coverage-istanbul')) {
428
+ parsedKarmaConfig.reporters = (parsedKarmaConfig.reporters ?? []).concat(['coverage']);
429
+ }
430
+ return [karma, parsedKarmaConfig, buildOptions, buildIterator];
431
+ }
432
+ function hasChunkOrWorkerFiles(files) {
433
+ return Object.keys(files).some((filename) => {
434
+ return /(?:^|\/)(?:worker|chunk)[^/]+\.js$/.test(filename);
435
+ });
436
+ }
437
+ async function writeTestFiles(files, testDir) {
438
+ const directoryExists = new Set();
439
+ // Writes the test related output files to disk and ensures the containing directories are present
440
+ await (0, private_1.emitFilesToDisk)(Object.entries(files), async ([filePath, file]) => {
441
+ if (file.type !== bundler_context_1.BuildOutputFileType.Browser && file.type !== bundler_context_1.BuildOutputFileType.Media) {
442
+ return;
443
+ }
444
+ const fullFilePath = path.join(testDir, filePath);
445
+ // Ensure output subdirectories exist
446
+ const fileBasePath = path.dirname(fullFilePath);
447
+ if (fileBasePath && !directoryExists.has(fileBasePath)) {
448
+ await fs.mkdir(fileBasePath, { recursive: true });
449
+ directoryExists.add(fileBasePath);
450
+ }
451
+ if (file.origin === 'memory') {
452
+ // Write file contents
453
+ await fs.writeFile(fullFilePath, file.contents);
454
+ }
455
+ else {
456
+ // Copy file contents
457
+ await fs.copyFile(file.inputPath, fullFilePath, fs.constants.COPYFILE_FICLONE);
458
+ }
459
+ });
460
+ }
461
+ /** Returns the first item yielded by the given generator and cancels the execution. */
462
+ async function first(generator, { cancel }) {
463
+ if (!cancel) {
464
+ const iterator = generator[Symbol.asyncIterator]();
465
+ const firstValue = await iterator.next();
466
+ if (firstValue.done) {
467
+ throw new Error('Expected generator to emit at least once.');
468
+ }
469
+ return [firstValue.value, iterator];
470
+ }
471
+ for await (const value of generator) {
472
+ return [value, null];
473
+ }
474
+ throw new Error('Expected generator to emit at least once.');
475
+ }
476
+ function createInstrumentationFilter(includedBasePath, excludedPaths) {
477
+ return (request) => {
478
+ return (!excludedPaths.has(request) &&
479
+ !/\.(e2e|spec)\.tsx?$|[\\/]node_modules[\\/]/.test(request) &&
480
+ request.startsWith(includedBasePath));
481
+ };
482
+ }
483
+ function getInstrumentationExcludedPaths(root, excludedPaths) {
484
+ const excluded = new Set();
485
+ for (const excludeGlob of excludedPaths) {
486
+ const excludePath = excludeGlob[0] === '/' ? excludeGlob.slice(1) : excludeGlob;
487
+ fast_glob_1.default.sync(excludePath, { cwd: root }).forEach((p) => excluded.add(path.join(root, p)));
488
+ }
489
+ return excluded;
490
+ }
@@ -0,0 +1,15 @@
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
+ export declare function findTests(include: string[], exclude: string[], workspaceRoot: string, projectSourceRoot: string): Promise<string[]>;
9
+ interface TestEntrypointsOptions {
10
+ projectSourceRoot: string;
11
+ workspaceRoot: string;
12
+ }
13
+ /** Generate unique bundle names for a set of test files. */
14
+ export declare function getTestEntrypoints(testFiles: string[], { projectSourceRoot, workspaceRoot }: TestEntrypointsOptions): Map<string, string>;
15
+ export {};
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ /**
3
+ * @license
4
+ * Copyright Google LLC All Rights Reserved.
5
+ *
6
+ * Use of this source code is governed by an MIT-style license that can be
7
+ * found in the LICENSE file at https://angular.dev/license
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.findTests = findTests;
44
+ exports.getTestEntrypoints = getTestEntrypoints;
45
+ const fast_glob_1 = __importStar(require("fast-glob"));
46
+ const node_fs_1 = require("node:fs");
47
+ const node_path_1 = require("node:path");
48
+ /* Go through all patterns and find unique list of files */
49
+ async function findTests(include, exclude, workspaceRoot, projectSourceRoot) {
50
+ const matchingTestsPromises = include.map((pattern) => findMatchingTests(pattern, exclude, workspaceRoot, projectSourceRoot));
51
+ const files = await Promise.all(matchingTestsPromises);
52
+ // Unique file names
53
+ return [...new Set(files.flat())];
54
+ }
55
+ /** Generate unique bundle names for a set of test files. */
56
+ function getTestEntrypoints(testFiles, { projectSourceRoot, workspaceRoot }) {
57
+ const seen = new Set();
58
+ return new Map(Array.from(testFiles, (testFile) => {
59
+ const relativePath = removeRoots(testFile, [projectSourceRoot, workspaceRoot])
60
+ // Strip leading dots and path separators.
61
+ .replace(/^[./\\]+/, '')
62
+ // Replace any path separators with dashes.
63
+ .replace(/[/\\]/g, '-');
64
+ const baseName = `spec-${(0, node_path_1.basename)(relativePath, (0, node_path_1.extname)(relativePath))}`;
65
+ let uniqueName = baseName;
66
+ let suffix = 2;
67
+ while (seen.has(uniqueName)) {
68
+ uniqueName = `${baseName}-${suffix}`.replace(/([^\w](?:spec|test))-([\d]+)$/, '-$2$1');
69
+ ++suffix;
70
+ }
71
+ seen.add(uniqueName);
72
+ return [uniqueName, testFile];
73
+ }));
74
+ }
75
+ const normalizePath = (path) => path.replace(/\\/g, '/');
76
+ const removeLeadingSlash = (pattern) => {
77
+ if (pattern.charAt(0) === '/') {
78
+ return pattern.substring(1);
79
+ }
80
+ return pattern;
81
+ };
82
+ const removeRelativeRoot = (path, root) => {
83
+ if (path.startsWith(root)) {
84
+ return path.substring(root.length);
85
+ }
86
+ return path;
87
+ };
88
+ function removeRoots(path, roots) {
89
+ for (const root of roots) {
90
+ if (path.startsWith(root)) {
91
+ return path.substring(root.length);
92
+ }
93
+ }
94
+ return (0, node_path_1.basename)(path);
95
+ }
96
+ async function findMatchingTests(pattern, ignore, workspaceRoot, projectSourceRoot) {
97
+ // normalize pattern, glob lib only accepts forward slashes
98
+ let normalizedPattern = normalizePath(pattern);
99
+ normalizedPattern = removeLeadingSlash(normalizedPattern);
100
+ const relativeProjectRoot = normalizePath((0, node_path_1.relative)(workspaceRoot, projectSourceRoot) + '/');
101
+ // remove relativeProjectRoot to support relative paths from root
102
+ // such paths are easy to get when running scripts via IDEs
103
+ normalizedPattern = removeRelativeRoot(normalizedPattern, relativeProjectRoot);
104
+ // special logic when pattern does not look like a glob
105
+ if (!(0, fast_glob_1.isDynamicPattern)(normalizedPattern)) {
106
+ if (await isDirectory((0, node_path_1.join)(projectSourceRoot, normalizedPattern))) {
107
+ normalizedPattern = `${normalizedPattern}/**/*.spec.@(ts|tsx)`;
108
+ }
109
+ else {
110
+ // see if matching spec file exists
111
+ const fileExt = (0, node_path_1.extname)(normalizedPattern);
112
+ // Replace extension to `.spec.ext`. Example: `src/app/app.component.ts`-> `src/app/app.component.spec.ts`
113
+ const potentialSpec = (0, node_path_1.join)(projectSourceRoot, (0, node_path_1.dirname)(normalizedPattern), `${(0, node_path_1.basename)(normalizedPattern, fileExt)}.spec${fileExt}`);
114
+ if (await exists(potentialSpec)) {
115
+ return [potentialSpec];
116
+ }
117
+ }
118
+ }
119
+ // normalize the patterns in the ignore list
120
+ const normalizedIgnorePatternList = ignore.map((pattern) => removeRelativeRoot(removeLeadingSlash(normalizePath(pattern)), relativeProjectRoot));
121
+ return (0, fast_glob_1.default)(normalizedPattern, {
122
+ cwd: projectSourceRoot,
123
+ absolute: true,
124
+ ignore: ['**/node_modules/**', ...normalizedIgnorePatternList],
125
+ });
126
+ }
127
+ async function isDirectory(path) {
128
+ try {
129
+ const stats = await node_fs_1.promises.stat(path);
130
+ return stats.isDirectory();
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ }
136
+ async function exists(path) {
137
+ try {
138
+ await node_fs_1.promises.access(path, node_fs_1.constants.F_OK);
139
+ return true;
140
+ }
141
+ catch {
142
+ return false;
143
+ }
144
+ }
@@ -0,0 +1,23 @@
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
+ import { type Builder, type BuilderContext, type BuilderOutput } from '@angular-devkit/architect';
9
+ import type { ConfigOptions } from 'karma';
10
+ import type { Schema as KarmaBuilderOptions } from './schema';
11
+ export type KarmaConfigOptions = ConfigOptions & {
12
+ buildWebpack?: unknown;
13
+ configFile?: string;
14
+ };
15
+ /**
16
+ * @experimental Direct usage of this function is considered experimental.
17
+ */
18
+ export declare function execute(options: KarmaBuilderOptions, context: BuilderContext, transforms?: {
19
+ karmaOptions?: (options: KarmaConfigOptions) => KarmaConfigOptions;
20
+ }): AsyncIterable<BuilderOutput>;
21
+ export type { KarmaBuilderOptions };
22
+ declare const builder: Builder<KarmaBuilderOptions>;
23
+ export default builder;