@ngrs/build 0.0.0-stage → 0.1.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.
@@ -0,0 +1,850 @@
1
+ import fs from 'node:fs';
2
+ import { lstat, readdir, readFile, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';
5
+ import picomatch from 'picomatch';
6
+
7
+ const WORKSPACE_FILENAMES = ['angular.json', 'workspace.json'];
8
+ const NX_WORKSPACE_FILENAME = 'nx.json';
9
+ const NX_SCAN_IGNORE_DIRS = new Set([
10
+ 'node_modules',
11
+ 'dist',
12
+ '.nx',
13
+ '.angular',
14
+ '.git',
15
+ 'target',
16
+ 'coverage',
17
+ 'out-tsc',
18
+ '_submodules',
19
+ ]);
20
+ const DEFAULT_ASSET_IGNORE_FILES = new Set(['.gitkeep', '.DS_Store', 'Thumbs.db']);
21
+
22
+ export function isSubDirectory(parentDir, candidatePath) {
23
+ const resolvedParent = path.resolve(parentDir);
24
+ const resolvedCandidate = path.resolve(resolvedParent, candidatePath);
25
+ const rel = path.relative(resolvedParent, resolvedCandidate);
26
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
27
+ }
28
+
29
+ export function toPosixPath(p) {
30
+ return p.replace(/\\/g, '/');
31
+ }
32
+
33
+ /**
34
+ * Walks up from `startDir` to locate `angular.json`, `workspace.json`, or `nx.json`.
35
+ *
36
+ * @param {string} [startDir]
37
+ * @returns {string | null}
38
+ */
39
+ export function findWorkspaceFile(startDir = process.cwd()) {
40
+ let current = path.resolve(startDir);
41
+ let foundNxJson = null;
42
+ while (true) {
43
+ for (const name of WORKSPACE_FILENAMES) {
44
+ const candidate = path.join(current, name);
45
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
46
+ return candidate;
47
+ }
48
+ }
49
+ if (!foundNxJson) {
50
+ const nxCandidate = path.join(current, NX_WORKSPACE_FILENAME);
51
+ if (fs.existsSync(nxCandidate) && fs.statSync(nxCandidate).isFile()) {
52
+ foundNxJson = nxCandidate;
53
+ }
54
+ }
55
+ const parent = path.dirname(current);
56
+ if (parent === current) {
57
+ return foundNxJson;
58
+ }
59
+ current = parent;
60
+ }
61
+ }
62
+
63
+ async function discoverNxProjectJsonFiles(workspaceRoot) {
64
+ const found = [];
65
+
66
+ async function scanDir(absDir) {
67
+ let entries;
68
+ try {
69
+ entries = await readdir(absDir, { withFileTypes: true });
70
+ } catch {
71
+ return;
72
+ }
73
+ for (const entry of entries) {
74
+ if (entry.isDirectory()) {
75
+ if (NX_SCAN_IGNORE_DIRS.has(entry.name) || entry.name.startsWith('.')) {
76
+ continue;
77
+ }
78
+ await scanDir(path.join(absDir, entry.name));
79
+ } else if (entry.isFile() && entry.name === 'project.json') {
80
+ found.push(path.join(absDir, entry.name));
81
+ }
82
+ }
83
+ }
84
+
85
+ await scanDir(workspaceRoot);
86
+ return found.sort();
87
+ }
88
+
89
+ /**
90
+ * Reads and parses `angular.json` / `workspace.json` OR an Nx `nx.json` + `project.json`
91
+ * monorepo workspace (supporting JSONC comments and trailing commas).
92
+ *
93
+ * @param {string} [startDirOrFile]
94
+ */
95
+ export async function loadWorkspace(startDirOrFile = process.cwd()) {
96
+ let workspaceFile = null;
97
+ const resolvedArg = path.resolve(startDirOrFile);
98
+ if (fs.existsSync(resolvedArg) && fs.statSync(resolvedArg).isFile()) {
99
+ workspaceFile = resolvedArg;
100
+ } else {
101
+ workspaceFile = findWorkspaceFile(resolvedArg);
102
+ }
103
+
104
+ if (!workspaceFile) {
105
+ throw new Error(
106
+ `Could not find an Angular or Nx workspace file ('angular.json', 'workspace.json', or 'nx.json') starting from "${resolvedArg}".`,
107
+ );
108
+ }
109
+
110
+ const workspaceRoot = path.dirname(workspaceFile);
111
+ const raw = await readFile(workspaceFile, 'utf8');
112
+ const errors = [];
113
+ const parsedRoot = parseJsonc(raw, errors, { allowTrailingComma: true }) || {};
114
+ if (errors.length > 0) {
115
+ const first = errors[0];
116
+ throw new Error(
117
+ `Failed to parse workspace file "${workspaceFile}": ${printParseErrorCode(first.error)} at offset ${first.offset}.`,
118
+ );
119
+ }
120
+
121
+ const isNxRootFile = path.basename(workspaceFile) === NX_WORKSPACE_FILENAME;
122
+ const workspace = isNxRootFile
123
+ ? {
124
+ version: 2,
125
+ defaultProject: parsedRoot.defaultProject,
126
+ projects: {},
127
+ nxJson: parsedRoot,
128
+ }
129
+ : parsedRoot;
130
+
131
+ workspace.projects ??= {};
132
+
133
+ // Discover standalone Nx `project.json` files when running in an Nx or hybrid workspace
134
+ if (isNxRootFile || fs.existsSync(path.join(workspaceRoot, NX_WORKSPACE_FILENAME))) {
135
+ const projectJsonFiles = await discoverNxProjectJsonFiles(workspaceRoot);
136
+ for (const projFile of projectJsonFiles) {
137
+ const projRaw = await readFile(projFile, 'utf8');
138
+ const projErrs = [];
139
+ const projCfg = parseJsonc(projRaw, projErrs, { allowTrailingComma: true });
140
+ if (projErrs.length > 0 || !projCfg || typeof projCfg !== 'object') {
141
+ continue;
142
+ }
143
+ const relRoot = toPosixPath(path.relative(workspaceRoot, path.dirname(projFile)));
144
+ let inferredName = projCfg.name;
145
+ if (!inferredName) {
146
+ if (!relRoot || relRoot === '.') {
147
+ try {
148
+ const rootPkg = JSON.parse(
149
+ await readFile(path.join(workspaceRoot, 'package.json'), 'utf8'),
150
+ );
151
+ inferredName = rootPkg.name;
152
+ } catch {
153
+ inferredName = path.basename(workspaceRoot);
154
+ }
155
+ } else {
156
+ inferredName = path.basename(relRoot);
157
+ }
158
+ }
159
+ if (!workspace.projects[inferredName] || typeof workspace.projects[inferredName] === 'string') {
160
+ workspace.projects[inferredName] = {
161
+ ...projCfg,
162
+ root: projCfg.root ?? relRoot,
163
+ };
164
+ }
165
+ }
166
+ }
167
+
168
+ // Expand string project pointers (`"my-app": "apps/my-app"`) used in some Nx `workspace.json` files
169
+ for (const [projName, projVal] of Object.entries(workspace.projects)) {
170
+ if (typeof projVal === 'string') {
171
+ const candidateProjJson = path.join(workspaceRoot, projVal, 'project.json');
172
+ if (fs.existsSync(candidateProjJson)) {
173
+ const projRaw = await readFile(candidateProjJson, 'utf8');
174
+ const projCfg = parseJsonc(projRaw, [], { allowTrailingComma: true }) || {};
175
+ workspace.projects[projName] = {
176
+ ...projCfg,
177
+ root: projCfg.root ?? toPosixPath(projVal),
178
+ };
179
+ }
180
+ }
181
+ }
182
+
183
+ return {
184
+ workspaceFile,
185
+ workspaceRoot,
186
+ workspace,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Resolves the target project name from an explicit CLI argument, `defaultProject`, or the first
192
+ * application project in `projects`.
193
+ */
194
+ export function resolveProjectName(workspace, requestedProject) {
195
+ const projects = workspace?.projects || {};
196
+ const names = Object.keys(projects);
197
+ if (names.length === 0) {
198
+ throw new Error('No projects are defined in angular.json.');
199
+ }
200
+
201
+ if (requestedProject) {
202
+ if (!projects[requestedProject]) {
203
+ throw new Error(
204
+ `Project "${requestedProject}" does not exist in angular.json. Available projects: ${names.join(', ')}.`,
205
+ );
206
+ }
207
+ return requestedProject;
208
+ }
209
+
210
+ if (workspace.defaultProject && projects[workspace.defaultProject]) {
211
+ return workspace.defaultProject;
212
+ }
213
+
214
+ const firstApp = names.find((name) => {
215
+ const p = projects[name];
216
+ return (
217
+ p?.projectType === 'application' ||
218
+ Boolean((p?.architect || p?.targets)?.build)
219
+ );
220
+ });
221
+
222
+ return firstApp || names[0];
223
+ }
224
+
225
+ /**
226
+ * Parses an Angular target string (`project:target[:configuration]`, supporting abbreviated forms
227
+ * like `::development` or `:build:production,fr`).
228
+ */
229
+ export function parseTargetString(
230
+ specifier,
231
+ defaultProject = '',
232
+ defaultTarget = 'build',
233
+ ) {
234
+ const parts = specifier.split(':');
235
+ if (parts.length < 2 || parts.length > 3) {
236
+ throw new Error(`Invalid Angular target specifier: "${specifier}".`);
237
+ }
238
+ const project = parts[0] || defaultProject;
239
+ const target = parts[1] || defaultTarget;
240
+ const configuration = parts.length === 3 && parts[2] !== '' ? parts[2] : undefined;
241
+ return {
242
+ project,
243
+ target,
244
+ ...(configuration !== undefined ? { configuration } : {}),
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Merges `architect[target].options` with one or more comma-separated `configurations[name]`
250
+ * entries, falling back to `defaultConfiguration` or `fallbackConfiguration` (`'production'` for
251
+ * `build`, `'development'` for `serve`).
252
+ */
253
+ export function resolveTargetOptions(
254
+ workspace,
255
+ targetSpec,
256
+ fallbackConfiguration = undefined,
257
+ ) {
258
+ const project = workspace?.projects?.[targetSpec.project];
259
+ if (!project) {
260
+ throw new Error(`Project "${targetSpec.project}" not found in workspace.`);
261
+ }
262
+
263
+ const targets = project.architect || project.targets || {};
264
+ const targetDef = targets[targetSpec.target];
265
+ if (!targetDef) {
266
+ throw new Error(
267
+ `Target "${targetSpec.target}" is not configured for project "${targetSpec.project}".`,
268
+ );
269
+ }
270
+
271
+ const baseOptions = structuredClone(targetDef.options || {});
272
+ const configurations = targetDef.configurations || {};
273
+
274
+ let configNames = [];
275
+ if (targetSpec.configuration) {
276
+ configNames = targetSpec.configuration
277
+ .split(',')
278
+ .map((s) => s.trim())
279
+ .filter(Boolean);
280
+ } else if (targetDef.defaultConfiguration) {
281
+ configNames = targetDef.defaultConfiguration
282
+ .split(',')
283
+ .map((s) => s.trim())
284
+ .filter(Boolean);
285
+ } else if (fallbackConfiguration && configurations[fallbackConfiguration]) {
286
+ configNames = [fallbackConfiguration];
287
+ }
288
+
289
+ let merged = baseOptions;
290
+ for (const configName of configNames) {
291
+ const configObj = configurations[configName];
292
+ if (!configObj) {
293
+ throw new Error(
294
+ `Configuration "${configName}" is not defined on target "${targetSpec.project}:${targetSpec.target}".`,
295
+ );
296
+ }
297
+ merged = {
298
+ ...merged,
299
+ ...structuredClone(configObj),
300
+ };
301
+ }
302
+
303
+ return merged;
304
+ }
305
+
306
+ /**
307
+ * 1:1 port of `@angular/build` `normalizeOptimization`.
308
+ */
309
+ export function normalizeOptimization(optimization = true) {
310
+ if (typeof optimization === 'object' && optimization !== null) {
311
+ const styleOpt = Boolean(optimization.styles ?? true);
312
+ return {
313
+ scripts: Boolean(optimization.scripts ?? true),
314
+ styles:
315
+ typeof optimization.styles === 'object' && optimization.styles !== null
316
+ ? {
317
+ minify: Boolean(optimization.styles.minify ?? true),
318
+ inlineCritical: Boolean(optimization.styles.inlineCritical ?? true),
319
+ removeSpecialComments: Boolean(optimization.styles.removeSpecialComments ?? true),
320
+ }
321
+ : {
322
+ minify: styleOpt,
323
+ inlineCritical: styleOpt,
324
+ removeSpecialComments: styleOpt,
325
+ },
326
+ fonts:
327
+ typeof optimization.fonts === 'object' && optimization.fonts !== null
328
+ ? { inline: Boolean(optimization.fonts.inline ?? true) }
329
+ : { inline: Boolean(optimization.fonts ?? true) },
330
+ };
331
+ }
332
+
333
+ const flag = Boolean(optimization);
334
+ return {
335
+ scripts: flag,
336
+ styles: {
337
+ minify: flag,
338
+ inlineCritical: flag,
339
+ removeSpecialComments: flag,
340
+ },
341
+ fonts: {
342
+ inline: flag,
343
+ },
344
+ };
345
+ }
346
+
347
+ /**
348
+ * 1:1 port of `@angular/build` `normalizeSourceMaps`.
349
+ */
350
+ export function normalizeSourceMaps(sourceMap = false) {
351
+ if (typeof sourceMap === 'object' && sourceMap !== null) {
352
+ return {
353
+ scripts: Boolean(sourceMap.scripts ?? true),
354
+ styles: Boolean(sourceMap.styles ?? true),
355
+ hidden: Boolean(sourceMap.hidden ?? false),
356
+ vendor: Boolean(sourceMap.vendor ?? false),
357
+ sourcesContent: Boolean(sourceMap.sourcesContent ?? true),
358
+ };
359
+ }
360
+ const flag = Boolean(sourceMap);
361
+ return {
362
+ scripts: flag,
363
+ styles: flag,
364
+ hidden: false,
365
+ vendor: false,
366
+ sourcesContent: flag,
367
+ };
368
+ }
369
+
370
+ /**
371
+ * 1:1 port of `@angular/build` `normalizeGlobalEntries` (`styles` and `scripts`).
372
+ */
373
+ export function normalizeGlobalEntries(rawEntries, defaultName) {
374
+ if (!rawEntries?.length) {
375
+ return [];
376
+ }
377
+
378
+ const bundles = new Map();
379
+ for (const rawEntry of rawEntries) {
380
+ const entry = typeof rawEntry === 'string' ? { input: rawEntry } : rawEntry;
381
+ const { bundleName, input, inject = true } = entry;
382
+ const name =
383
+ bundleName || (inject ? defaultName : path.basename(input, path.extname(input)));
384
+
385
+ const existing = bundles.get(name);
386
+ if (!existing) {
387
+ bundles.set(name, { name, files: [input], initial: Boolean(inject) });
388
+ continue;
389
+ }
390
+
391
+ if (existing.initial !== Boolean(inject)) {
392
+ throw new Error(
393
+ `The "${name}" bundle is mixing injected and non-injected entries. Verify that the project options are correct.`,
394
+ );
395
+ }
396
+ existing.files.push(input);
397
+ }
398
+
399
+ return [...bundles.values()];
400
+ }
401
+
402
+ /**
403
+ * 1:1 port of `@angular/build` `normalizeAssetPatterns` supporting both string shorthand
404
+ * (e.g. `"public"`, `"src/assets"`, `"src/favicon.ico"`) and `{ glob, input, output, ignore }`.
405
+ */
406
+ export function normalizeAssetPatterns(
407
+ assetPatterns,
408
+ workspaceRoot,
409
+ projectRoot,
410
+ projectSourceRoot,
411
+ ) {
412
+ if (!assetPatterns?.length) {
413
+ return [];
414
+ }
415
+
416
+ const resolvedWorkspaceRoot = path.resolve(workspaceRoot);
417
+ const resolvedProjectRoot = path.resolve(resolvedWorkspaceRoot, projectRoot || '');
418
+ const resolvedSourceRoot = projectSourceRoot
419
+ ? path.resolve(resolvedWorkspaceRoot, projectSourceRoot)
420
+ : path.join(resolvedProjectRoot, 'src');
421
+
422
+ return assetPatterns.map((assetPattern) => {
423
+ let normalized;
424
+ if (typeof assetPattern === 'string') {
425
+ const assetPath = path.normalize(assetPattern);
426
+ const resolvedAssetPath = path.resolve(resolvedWorkspaceRoot, assetPath);
427
+
428
+ let root;
429
+ if (isSubDirectory(resolvedSourceRoot, resolvedAssetPath)) {
430
+ root = resolvedSourceRoot;
431
+ } else if (isSubDirectory(resolvedProjectRoot, resolvedAssetPath)) {
432
+ root = resolvedProjectRoot;
433
+ } else if (isSubDirectory(resolvedWorkspaceRoot, resolvedAssetPath)) {
434
+ root = resolvedWorkspaceRoot;
435
+ } else {
436
+ throw new Error(`The ${assetPattern} asset path must be within the workspace root.`);
437
+ }
438
+
439
+ let isDirectory = true;
440
+ try {
441
+ isDirectory =
442
+ fs.statSync(resolvedAssetPath, { throwIfNoEntry: false })?.isDirectory() ?? true;
443
+ } catch {
444
+ isDirectory = true;
445
+ }
446
+
447
+ const globPattern = isDirectory ? '**/*' : path.basename(assetPath);
448
+ const input = isDirectory ? assetPath : path.dirname(assetPath);
449
+ const isProjectPublicDir =
450
+ isDirectory && path.resolve(resolvedProjectRoot, 'public') === resolvedAssetPath;
451
+ const output = isProjectPublicDir
452
+ ? ''
453
+ : path.relative(root, path.resolve(resolvedWorkspaceRoot, input));
454
+
455
+ normalized = { glob: globPattern, input, output };
456
+ } else {
457
+ if (!isSubDirectory(resolvedWorkspaceRoot, assetPattern.input)) {
458
+ throw new Error(
459
+ `The ${assetPattern.input} asset path must be within the workspace root.`,
460
+ );
461
+ }
462
+ const cleanOut = (assetPattern.output ?? '').replace(/^\/+/, '');
463
+ normalized = {
464
+ ...assetPattern,
465
+ output: cleanOut === '.' ? '' : path.normalize(cleanOut === '' ? '' : cleanOut),
466
+ };
467
+ }
468
+
469
+ if (normalized.output === '..' || normalized.output.startsWith(`..${path.sep}`)) {
470
+ throw new Error('An asset cannot be written to a location outside of the output path.');
471
+ }
472
+ if (normalized.output === '.') {
473
+ normalized.output = '';
474
+ }
475
+ return normalized;
476
+ });
477
+ }
478
+
479
+ async function walkDirectoryFiles(rootDir, followSymlinks = false) {
480
+ const results = [];
481
+
482
+ async function visit(currentAbs, relPrefix) {
483
+ let dirEntries;
484
+ try {
485
+ dirEntries = await readdir(currentAbs, { withFileTypes: true });
486
+ } catch {
487
+ return;
488
+ }
489
+
490
+ for (const dirent of dirEntries) {
491
+ if (DEFAULT_ASSET_IGNORE_FILES.has(dirent.name)) {
492
+ continue;
493
+ }
494
+ const fullPath = path.join(currentAbs, dirent.name);
495
+ const relPosix = relPrefix ? `${relPrefix}/${dirent.name}` : dirent.name;
496
+
497
+ if (dirent.isDirectory()) {
498
+ await visit(fullPath, relPosix);
499
+ } else if (dirent.isFile()) {
500
+ results.push({ fullPath, relPosix });
501
+ } else if (dirent.isSymbolicLink() && followSymlinks) {
502
+ try {
503
+ const st = await stat(fullPath);
504
+ if (st.isDirectory()) {
505
+ await visit(fullPath, relPosix);
506
+ } else if (st.isFile()) {
507
+ results.push({ fullPath, relPosix });
508
+ }
509
+ } catch {
510
+ // Ignore broken symlink
511
+ }
512
+ }
513
+ }
514
+ }
515
+
516
+ await visit(rootDir, '');
517
+ return results;
518
+ }
519
+
520
+ /**
521
+ * Resolves normalized asset patterns on disk into `{ source, destination }[]` pairs.
522
+ */
523
+ export async function resolveAssets(entries, workspaceRoot) {
524
+ if (!entries?.length) {
525
+ return [];
526
+ }
527
+
528
+ const out = [];
529
+ for (const entry of entries) {
530
+ if (!entry.glob || entry.glob.endsWith('/')) {
531
+ continue;
532
+ }
533
+ const cwd = path.resolve(workspaceRoot, entry.input);
534
+ if (!fs.existsSync(cwd)) {
535
+ continue;
536
+ }
537
+
538
+ const st = await (entry.followSymlinks ? stat(cwd) : lstat(cwd)).catch(() => null);
539
+ if (!st) {
540
+ continue;
541
+ }
542
+ if (st.isFile()) {
543
+ const base = path.basename(cwd);
544
+ if (!DEFAULT_ASSET_IGNORE_FILES.has(base)) {
545
+ out.push({
546
+ source: cwd,
547
+ destination: toPosixPath(path.join(entry.output || '', base)),
548
+ });
549
+ }
550
+ continue;
551
+ }
552
+
553
+ const matchGlob = picomatch(toPosixPath(entry.glob), { dot: true });
554
+ const ignoreMatchers = (entry.ignore || []).flatMap((ig) => {
555
+ const norm = toPosixPath(ig).replace(/\/+$/, '');
556
+ return [
557
+ picomatch(norm, { dot: true }),
558
+ picomatch(`${norm}/**`, { dot: true }),
559
+ ];
560
+ });
561
+
562
+ const candidates = await walkDirectoryFiles(cwd, Boolean(entry.followSymlinks));
563
+ for (const { fullPath, relPosix } of candidates) {
564
+ if (!matchGlob(relPosix)) {
565
+ continue;
566
+ }
567
+ if (ignoreMatchers.some((fn) => fn(relPosix))) {
568
+ continue;
569
+ }
570
+ const destRel = entry.flatten ? path.basename(relPosix) : relPosix;
571
+ const destination = toPosixPath(path.posix.join(toPosixPath(entry.output || ''), destRel));
572
+ if (destination === '..' || destination.startsWith('../')) {
573
+ throw new Error('An asset cannot be written to a location outside of the output path.');
574
+ }
575
+ out.push({
576
+ source: fullPath,
577
+ destination: destination.replace(/^\/+/, ''),
578
+ });
579
+ }
580
+ }
581
+
582
+ return out;
583
+ }
584
+
585
+ function normalizeExternals(externalDependencies) {
586
+ if (!externalDependencies?.length) {
587
+ return [];
588
+ }
589
+ return [
590
+ ...new Set(
591
+ externalDependencies.map((dep) =>
592
+ dep.endsWith('/*') && !/^\.{0,2}\//.test(dep) ? dep.slice(0, -2) : dep,
593
+ ),
594
+ ),
595
+ ];
596
+ }
597
+
598
+ /**
599
+ * Normalizes both modern `@angular/build:application` options (`browser`, `server`, `polyfills`
600
+ * array, `outputPath` string/object) and legacy `@angular-devkit/build-angular:browser` /
601
+ * `browser-esbuild` options (`main`, `polyfills` string, `outputPath` string) into a single
602
+ * canonical configuration object.
603
+ */
604
+ export function normalizeApplicationOptions(
605
+ rawOptions,
606
+ projectMetadata,
607
+ workspaceRoot,
608
+ projectName,
609
+ ) {
610
+ const resolvedWorkspaceRoot = path.resolve(workspaceRoot);
611
+ const relProjectRoot = projectMetadata?.root ?? '';
612
+ const projectRoot = path.resolve(resolvedWorkspaceRoot, relProjectRoot);
613
+ const relSourceRoot =
614
+ projectMetadata?.sourceRoot ?? path.posix.join(toPosixPath(relProjectRoot), 'src');
615
+ const projectSourceRoot = path.resolve(resolvedWorkspaceRoot, relSourceRoot);
616
+
617
+ // Support both modern `browser` and legacy `main`
618
+ const entryRel = rawOptions.browser ?? rawOptions.main;
619
+ if (entryRel === '') {
620
+ throw new Error('`browser` / `main` option cannot be an empty string.');
621
+ }
622
+ const browserEntry = entryRel
623
+ ? path.resolve(resolvedWorkspaceRoot, entryRel)
624
+ : path.join(projectSourceRoot, 'main.ts');
625
+
626
+ const serverEntry =
627
+ typeof rawOptions.server === 'string' && rawOptions.server.trim() !== ''
628
+ ? path.resolve(resolvedWorkspaceRoot, rawOptions.server)
629
+ : undefined;
630
+
631
+ if (!rawOptions.tsConfig) {
632
+ throw new Error(
633
+ `Missing required "tsConfig" option in build configuration for project "${projectName}".`,
634
+ );
635
+ }
636
+ const tsconfigPath = path.resolve(resolvedWorkspaceRoot, rawOptions.tsConfig);
637
+
638
+ // Polyfills: array (`["zone.js"]`) or legacy string (`"src/polyfills.ts"`)
639
+ let polyfills = [];
640
+ if (Array.isArray(rawOptions.polyfills)) {
641
+ polyfills = [...rawOptions.polyfills];
642
+ } else if (typeof rawOptions.polyfills === 'string' && rawOptions.polyfills.trim() !== '') {
643
+ polyfills = [rawOptions.polyfills.trim()];
644
+ }
645
+
646
+ // Output path: string (`"dist/my-app"`) or `{ base, browser, server, media }`
647
+ const rawOutputPath =
648
+ rawOptions.outputPath ?? path.join('dist', projectName);
649
+ const outputBase = path.resolve(
650
+ resolvedWorkspaceRoot,
651
+ typeof rawOutputPath === 'string' ? rawOutputPath : rawOutputPath.base,
652
+ );
653
+ const browserSubdir =
654
+ typeof rawOutputPath === 'object' && rawOutputPath !== null
655
+ ? (rawOutputPath.browser ?? 'browser')
656
+ : 'browser';
657
+ const serverSubdir =
658
+ typeof rawOutputPath === 'object' && rawOutputPath !== null
659
+ ? (rawOutputPath.server ?? 'server')
660
+ : 'server';
661
+ const mediaSubdir =
662
+ typeof rawOutputPath === 'object' && rawOutputPath !== null
663
+ ? (rawOutputPath.media ?? 'media')
664
+ : 'media';
665
+
666
+ const outputOptions = {
667
+ base: outputBase,
668
+ browser: browserSubdir,
669
+ server: serverSubdir,
670
+ media: mediaSubdir,
671
+ browserDir: browserSubdir ? path.join(outputBase, browserSubdir) : outputBase,
672
+ serverDir: serverSubdir ? path.join(outputBase, serverSubdir) : outputBase,
673
+ clean: rawOptions.deleteOutputPath ?? true,
674
+ };
675
+
676
+ // Index HTML options
677
+ let indexHtmlOptions = null;
678
+ if (rawOptions.index !== false) {
679
+ if (typeof rawOptions.index === 'string') {
680
+ indexHtmlOptions = {
681
+ input: path.resolve(resolvedWorkspaceRoot, rawOptions.index),
682
+ output: path.basename(rawOptions.index),
683
+ preloadInitial: !rawOptions.serviceWorker,
684
+ };
685
+ } else if (typeof rawOptions.index === 'object' && rawOptions.index !== null) {
686
+ indexHtmlOptions = {
687
+ input: path.resolve(resolvedWorkspaceRoot, rawOptions.index.input),
688
+ output: rawOptions.index.output || 'index.html',
689
+ preloadInitial: rawOptions.index.preloadInitial ?? !rawOptions.serviceWorker,
690
+ };
691
+ } else {
692
+ indexHtmlOptions = {
693
+ input: path.join(projectSourceRoot, 'index.html'),
694
+ output: 'index.html',
695
+ preloadInitial: !rawOptions.serviceWorker,
696
+ };
697
+ }
698
+ }
699
+
700
+ // File replacements (`{ replace, with }` and legacy `{ replace, replaceWith }`)
701
+ const fileReplacements = [];
702
+ for (const rep of rawOptions.fileReplacements || []) {
703
+ const targetWith = rep.with ?? rep.replaceWith;
704
+ if (!rep.replace || !targetWith) {
705
+ continue;
706
+ }
707
+ const absReplace = path.resolve(resolvedWorkspaceRoot, rep.replace);
708
+ const absWith = path.resolve(resolvedWorkspaceRoot, targetWith);
709
+ if (!fs.existsSync(absWith)) {
710
+ throw new Error(`The ${absWith} path in file replacements does not exist.`);
711
+ }
712
+ fileReplacements.push({
713
+ replace: absReplace,
714
+ with: absWith,
715
+ });
716
+ }
717
+
718
+ const optimization = normalizeOptimization(rawOptions.optimization ?? true);
719
+ const sourceMap = normalizeSourceMaps(rawOptions.sourceMap ?? false);
720
+ const globalStyles = normalizeGlobalEntries(rawOptions.styles, 'styles');
721
+ const globalScripts = normalizeGlobalEntries(rawOptions.scripts, 'scripts');
722
+ const assets = normalizeAssetPatterns(
723
+ rawOptions.assets || [],
724
+ resolvedWorkspaceRoot,
725
+ projectRoot,
726
+ projectSourceRoot,
727
+ );
728
+
729
+ const includePaths = (rawOptions.stylePreprocessorOptions?.includePaths || []).map((p) =>
730
+ path.resolve(resolvedWorkspaceRoot, p),
731
+ );
732
+
733
+ const outputHashing = rawOptions.outputHashing ?? 'none';
734
+
735
+ return {
736
+ projectName,
737
+ workspaceRoot: resolvedWorkspaceRoot,
738
+ projectRoot,
739
+ projectSourceRoot,
740
+ tsconfigPath,
741
+ browserEntry,
742
+ serverEntry,
743
+ polyfills,
744
+ outputOptions,
745
+ outputHashing,
746
+ indexHtmlOptions,
747
+ assets,
748
+ globalStyles,
749
+ globalScripts,
750
+ inlineStyleLanguage: rawOptions.inlineStyleLanguage ?? 'css',
751
+ stylePreprocessorOptions: {
752
+ includePaths,
753
+ sass: rawOptions.stylePreprocessorOptions?.sass,
754
+ },
755
+ fileReplacements,
756
+ optimization,
757
+ sourceMap,
758
+ aot: rawOptions.aot ?? true,
759
+ baseHref: rawOptions.baseHref,
760
+ deployUrl: rawOptions.deployUrl,
761
+ define: rawOptions.define ? { ...rawOptions.define } : undefined,
762
+ externalDependencies: normalizeExternals(rawOptions.externalDependencies),
763
+ conditions: rawOptions.conditions,
764
+ budgets: Array.isArray(rawOptions.budgets) ? rawOptions.budgets : [],
765
+ namedChunks: Boolean(rawOptions.namedChunks ?? false),
766
+ subresourceIntegrity: Boolean(rawOptions.subresourceIntegrity ?? false),
767
+ crossOrigin: rawOptions.crossOrigin ?? 'none',
768
+ preserveSymlinks:
769
+ rawOptions.preserveSymlinks ?? process.execArgv.includes('--preserve-symlinks'),
770
+ extractLicenses: Boolean(rawOptions.extractLicenses ?? true),
771
+ statsJson: Boolean(rawOptions.statsJson ?? false),
772
+ watch: Boolean(rawOptions.watch ?? false),
773
+ poll: rawOptions.poll,
774
+ verbose: Boolean(rawOptions.verbose ?? false),
775
+ progress: Boolean(rawOptions.progress ?? true),
776
+ colors: typeof rawOptions.colors === 'boolean' ? rawOptions.colors : undefined,
777
+ clearScreen: Boolean(rawOptions.clearScreen ?? false),
778
+ ssr: rawOptions.ssr ?? false,
779
+ };
780
+ }
781
+
782
+ /**
783
+ * Normalizes `serve` (`dev-server`) options and resolves its linked `buildTarget` /
784
+ * `browserTarget` (defaulting to `<project>:build:development`).
785
+ */
786
+ export function normalizeDevServerOptions(
787
+ rawServeOptions,
788
+ workspace,
789
+ projectName,
790
+ workspaceRoot,
791
+ ) {
792
+ const resolvedWorkspaceRoot = path.resolve(workspaceRoot);
793
+ const projectMetadata = workspace?.projects?.[projectName] || {};
794
+ const projectRoot = path.resolve(resolvedWorkspaceRoot, projectMetadata.root ?? '');
795
+
796
+ // Support both modern `buildTarget` and legacy `browserTarget`
797
+ const explicitTargetSpecifier =
798
+ rawServeOptions.buildTarget || rawServeOptions.browserTarget;
799
+ const parsedBuildTarget = explicitTargetSpecifier
800
+ ? parseTargetString(explicitTargetSpecifier, projectName, 'build')
801
+ : { project: projectName, target: 'build' };
802
+
803
+ // Prefer `development` configuration when no explicit configuration was specified and
804
+ // `development` exists on the build target, matching Angular CLI dev-server conventions.
805
+ const buildTargetOptions = resolveTargetOptions(workspace, parsedBuildTarget, 'development');
806
+
807
+ let port = rawServeOptions.port ?? 4200;
808
+ if (process.env.PORT !== undefined && process.env.PORT !== '') {
809
+ const envPort = Number(process.env.PORT);
810
+ if (!Number.isNaN(envPort)) {
811
+ port = envPort;
812
+ }
813
+ }
814
+
815
+ const liveReload = rawServeOptions.liveReload ?? true;
816
+ const hmr = rawServeOptions.hmr ?? Boolean(liveReload);
817
+
818
+ return {
819
+ projectName,
820
+ workspaceRoot: resolvedWorkspaceRoot,
821
+ projectRoot,
822
+ buildTarget: parsedBuildTarget,
823
+ buildTargetOptions,
824
+ port,
825
+ strictPort: port !== 0,
826
+ host: rawServeOptions.host ?? 'localhost',
827
+ open: Boolean(rawServeOptions.open ?? false),
828
+ ssl: Boolean(rawServeOptions.ssl ?? false),
829
+ sslKey: rawServeOptions.sslKey
830
+ ? path.resolve(resolvedWorkspaceRoot, rawServeOptions.sslKey)
831
+ : undefined,
832
+ sslCert: rawServeOptions.sslCert
833
+ ? path.resolve(resolvedWorkspaceRoot, rawServeOptions.sslCert)
834
+ : undefined,
835
+ proxyConfig: rawServeOptions.proxyConfig,
836
+ hmr: Boolean(hmr),
837
+ liveReload: Boolean(liveReload),
838
+ headers: rawServeOptions.headers ? { ...rawServeOptions.headers } : undefined,
839
+ allowedHosts: rawServeOptions.allowedHosts ?? [],
840
+ servePath: rawServeOptions.servePath,
841
+ define: rawServeOptions.define ? { ...rawServeOptions.define } : undefined,
842
+ prebundle: rawServeOptions.prebundle ?? true,
843
+ watch: rawServeOptions.watch ?? true,
844
+ poll: rawServeOptions.poll,
845
+ verbose: Boolean(rawServeOptions.verbose ?? false),
846
+ progress: Boolean(rawServeOptions.progress ?? true),
847
+ colors: typeof rawServeOptions.colors === 'boolean' ? rawServeOptions.colors : undefined,
848
+ clearScreen: Boolean(rawServeOptions.clearScreen ?? false),
849
+ };
850
+ }