@angular/build 19.2.0-next.2 → 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 (36) hide show
  1. package/builders.json +5 -0
  2. package/package.json +14 -9
  3. package/src/builders/application/execute-build.js +0 -4
  4. package/src/builders/application/options.d.ts +5 -1
  5. package/src/builders/application/options.js +9 -1
  6. package/src/builders/dev-server/vite-server.js +4 -0
  7. package/src/builders/karma/application_builder.d.ts +15 -0
  8. package/src/builders/karma/application_builder.js +490 -0
  9. package/src/builders/karma/find-tests.d.ts +15 -0
  10. package/src/builders/karma/find-tests.js +144 -0
  11. package/src/builders/karma/index.d.ts +23 -0
  12. package/src/builders/karma/index.js +135 -0
  13. package/src/builders/karma/polyfills/init_sourcemaps.js +10 -0
  14. package/src/builders/karma/polyfills/init_test_bed.js +19 -0
  15. package/src/builders/karma/polyfills/jasmine_global.js +18 -0
  16. package/src/builders/karma/polyfills/jasmine_global_cleanup.js +14 -0
  17. package/src/builders/karma/schema.d.ts +248 -0
  18. package/src/builders/karma/schema.js +15 -0
  19. package/src/builders/karma/schema.json +347 -0
  20. package/src/private.d.ts +2 -0
  21. package/src/private.js +6 -1
  22. package/src/tools/esbuild/angular/compiler-plugin.js +1 -1
  23. package/src/tools/esbuild/index-html-generator.js +1 -8
  24. package/src/tools/vite/middlewares/html-fallback-middleware.js +2 -1
  25. package/src/utils/error.js +2 -2
  26. package/src/utils/index-file/auto-csp.js +1 -1
  27. package/src/utils/index-file/index-html-generator.js +3 -2
  28. package/src/utils/index-file/inline-critical-css.d.ts +1 -0
  29. package/src/utils/index-file/inline-critical-css.js +11 -7
  30. package/src/utils/load-translations.js +3 -3
  31. package/src/utils/normalize-asset-patterns.js +3 -3
  32. package/src/utils/normalize-cache.js +1 -1
  33. package/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.js +1 -2
  34. package/src/utils/server-rendering/render-worker.js +2 -2
  35. package/src/utils/server-rendering/routes-extractor-worker.js +2 -2
  36. package/src/utils/service-worker.js +2 -2
package/builders.json CHANGED
@@ -15,6 +15,11 @@
15
15
  "schema": "./src/builders/extract-i18n/schema.json",
16
16
  "description": "Extract i18n messages from an application."
17
17
  },
18
+ "karma": {
19
+ "implementation": "./src/builders/karma",
20
+ "schema": "./src/builders/karma/schema.json",
21
+ "description": "Run Karma unit tests."
22
+ },
18
23
  "ng-packagr": {
19
24
  "implementation": "./src/builders/ng-packagr/index",
20
25
  "schema": "./src/builders/ng-packagr/schema.json",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@angular/build",
3
- "version": "19.2.0-next.2",
3
+ "version": "19.2.0-rc.0",
4
4
  "description": "Official build system for Angular",
5
5
  "keywords": [
6
6
  "Angular CLI",
@@ -23,12 +23,12 @@
23
23
  "builders": "builders.json",
24
24
  "dependencies": {
25
25
  "@ampproject/remapping": "2.3.0",
26
- "@angular-devkit/architect": "0.1902.0-next.2",
27
- "@babel/core": "7.26.8",
26
+ "@angular-devkit/architect": "0.1902.0-rc.0",
27
+ "@babel/core": "7.26.9",
28
28
  "@babel/helper-annotate-as-pure": "7.25.9",
29
29
  "@babel/helper-split-export-declaration": "7.24.7",
30
30
  "@babel/plugin-syntax-import-attributes": "7.26.0",
31
- "@inquirer/confirm": "5.1.5",
31
+ "@inquirer/confirm": "5.1.6",
32
32
  "@vitejs/plugin-basic-ssl": "1.2.0",
33
33
  "beasties": "0.2.0",
34
34
  "browserslist": "^4.23.0",
@@ -38,13 +38,14 @@
38
38
  "istanbul-lib-instrument": "6.0.3",
39
39
  "listr2": "8.2.5",
40
40
  "magic-string": "0.30.17",
41
- "mrmime": "2.0.0",
41
+ "mrmime": "2.0.1",
42
42
  "parse5-html-rewriting-stream": "7.0.0",
43
43
  "picomatch": "4.0.2",
44
44
  "piscina": "4.8.0",
45
- "rollup": "4.34.6",
46
- "sass": "1.84.0",
45
+ "rollup": "4.34.8",
46
+ "sass": "1.85.0",
47
47
  "semver": "7.7.1",
48
+ "source-map-support": "0.5.21",
48
49
  "vite": "6.1.0",
49
50
  "watchpack": "2.4.2"
50
51
  },
@@ -57,12 +58,13 @@
57
58
  "@angular/localize": "^19.0.0 || ^19.2.0-next.0",
58
59
  "@angular/platform-server": "^19.0.0 || ^19.2.0-next.0",
59
60
  "@angular/service-worker": "^19.0.0 || ^19.2.0-next.0",
60
- "@angular/ssr": "^19.2.0-next.2",
61
+ "@angular/ssr": "^19.2.0-rc.0",
62
+ "karma": "^6.4.0",
61
63
  "less": "^4.2.0",
62
64
  "ng-packagr": "^19.0.0 || ^19.2.0-next.0",
63
65
  "postcss": "^8.4.0",
64
66
  "tailwindcss": "^2.0.0 || ^3.0.0 || ^4.0.0",
65
- "typescript": ">=5.5 <5.8"
67
+ "typescript": ">=5.5 <5.9"
66
68
  },
67
69
  "peerDependenciesMeta": {
68
70
  "@angular/localize": {
@@ -77,6 +79,9 @@
77
79
  "@angular/ssr": {
78
80
  "optional": true
79
81
  },
82
+ "karma": {
83
+ "optional": true
84
+ },
80
85
  "less": {
81
86
  "optional": true
82
87
  },
@@ -190,10 +190,6 @@ async function executeBuild(options, context, rebuildState) {
190
190
  if (serverEntryPoint) {
191
191
  executionResult.addOutputFile(manifest_1.SERVER_APP_ENGINE_MANIFEST_FILENAME, (0, manifest_1.generateAngularServerAppEngineManifest)(i18nOptions, baseHref), bundler_context_1.BuildOutputFileType.ServerRoot);
192
192
  }
193
- // Override auto-CSP settings if we are serving through Vite middleware.
194
- if (context.builder.builderName === 'dev-server' && options.security) {
195
- options.security.autoCsp = false;
196
- }
197
193
  // Perform i18n translation inlining if enabled
198
194
  if (i18nOptions.shouldInline) {
199
195
  const result = await (0, i18n_1.inlineI18n)(metafile, options, executionResult, initialFiles);
@@ -196,7 +196,11 @@ export declare function normalizeOptions(context: BuilderContext, projectName: s
196
196
  partialSSRBuild: boolean;
197
197
  externalRuntimeStyles: boolean | undefined;
198
198
  instrumentForCoverage: ((filename: string) => boolean) | undefined;
199
- security: import("./schema").Security | undefined;
199
+ security: {
200
+ autoCsp: {
201
+ unsafeEval: boolean;
202
+ } | undefined;
203
+ };
200
204
  templateUpdates: boolean;
201
205
  incrementalResults: boolean;
202
206
  }>;
@@ -236,8 +236,16 @@ async function normalizeOptions(context, projectName, options, extensions) {
236
236
  throw new Error('The "index" option cannot be set to false when enabling "ssr", "prerender" or "app-shell".');
237
237
  }
238
238
  }
239
+ const autoCsp = options.security?.autoCsp;
240
+ const security = {
241
+ autoCsp: autoCsp
242
+ ? {
243
+ unsafeEval: autoCsp === true ? false : !!autoCsp.unsafeEval,
244
+ }
245
+ : undefined,
246
+ };
239
247
  // Initial options to keep
240
- const { allowedCommonJsDependencies, aot = true, baseHref, crossOrigin, externalDependencies, extractLicenses, inlineStyleLanguage = 'css', outExtension, serviceWorker, poll, polyfills, statsJson, outputMode, stylePreprocessorOptions, subresourceIntegrity, verbose, watch, progress = true, externalPackages, namedChunks, budgets, deployUrl, clearScreen, define, partialSSRBuild = false, externalRuntimeStyles, instrumentForCoverage, security, } = options;
248
+ const { allowedCommonJsDependencies, aot = true, baseHref, crossOrigin, externalDependencies, extractLicenses, inlineStyleLanguage = 'css', outExtension, serviceWorker, poll, polyfills, statsJson, outputMode, stylePreprocessorOptions, subresourceIntegrity, verbose, watch, progress = true, externalPackages, namedChunks, budgets, deployUrl, clearScreen, define, partialSSRBuild = false, externalRuntimeStyles, instrumentForCoverage, } = options;
241
249
  // Return all the normalized options
242
250
  return {
243
251
  advancedOptimizations: !!aot && optimizationOptions.scripts,
@@ -82,6 +82,10 @@ async function* serveWithVite(serverOptions, builderName, builderAction, context
82
82
  browserOptions.prerender = undefined;
83
83
  browserOptions.ssr ||= true;
84
84
  }
85
+ // Disable auto CSP.
86
+ browserOptions.security = {
87
+ autoCsp: false,
88
+ };
85
89
  // Set all packages as external to support Vite's prebundle caching
86
90
  browserOptions.externalPackages = serverOptions.prebundle;
87
91
  // Disable generating a full manifest with routes.
@@ -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
+ import { ResultFile } from '@angular/build/private';
9
+ import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect';
10
+ import type { ConfigOptions } from 'karma';
11
+ import { Schema as KarmaBuilderOptions } from './schema';
12
+ export declare function execute(options: KarmaBuilderOptions, context: BuilderContext, karmaOptions: ConfigOptions, transforms?: {
13
+ karmaOptions?: (options: ConfigOptions) => ConfigOptions;
14
+ }): AsyncIterable<BuilderOutput>;
15
+ export declare function writeTestFiles(files: Record<string, ResultFile>, testDir: string): Promise<void>;
@@ -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 {};