@ngrs/build 0.0.0-stage → 0.2.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,994 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import { createRequire } from 'node:module';
5
+ import path from 'node:path';
6
+ import { angular, formatDiagnostics } from '@ngrs/vite';
7
+ import * as vite from 'vite';
8
+ import { createBuilder, createConsoleLogger } from '../../architect-compat.mjs';
9
+ import { checkBudgets } from '../../budgets.mjs';
10
+ import { transformIndexHtmlContent } from '../../index-html.mjs';
11
+ import {
12
+ calculateEstimatedTransferSizes,
13
+ formatBuildMessage,
14
+ generateEsbuildBuildStatsTable,
15
+ getEntryPointName,
16
+ resolveColorsOption,
17
+ withProgress,
18
+ } from '../../stats-table.mjs';
19
+ import {
20
+ isSubDirectory,
21
+ loadWorkspace,
22
+ normalizeApplicationOptions,
23
+ resolveAssets,
24
+ resolveProjectName,
25
+ resolveTargetOptions,
26
+ toPosixPath,
27
+ } from '../../workspace.mjs';
28
+
29
+ const localRequire = createRequire(import.meta.url);
30
+ const { compileSass: nativeCompileSass, compileSassString: nativeCompileSassString } =
31
+ localRequire('@ngrs/compiler');
32
+
33
+ const { build: viteBuild } = vite;
34
+ const isRolldownVite = 'rolldownVersion' in vite && Boolean(vite.rolldownVersion);
35
+
36
+ const VIRTUAL_POLYFILLS_ID = '/@ngrs/polyfills.js';
37
+ const VIRTUAL_ENTRY_ID = '/@ngrs/entry.js';
38
+ const RESOLVED_POLYFILLS_ID = '\0ngrs:polyfills.js';
39
+ const RESOLVED_ENTRY_ID = '\0ngrs:entry.js';
40
+
41
+ let cachedDartSassPromise;
42
+ function loadDartSassFallback() {
43
+ if (!cachedDartSassPromise) {
44
+ cachedDartSassPromise = import('sass');
45
+ }
46
+ return cachedDartSassPromise;
47
+ }
48
+
49
+ let cachedLightningCss;
50
+ function loadLightningCss() {
51
+ if (cachedLightningCss !== undefined) {
52
+ return cachedLightningCss;
53
+ }
54
+ try {
55
+ const vitePkgPath = localRequire.resolve('vite/package.json');
56
+ const viteReq = createRequire(vitePkgPath);
57
+ cachedLightningCss = viteReq('lightningcss');
58
+ } catch {
59
+ cachedLightningCss = null;
60
+ }
61
+ return cachedLightningCss;
62
+ }
63
+
64
+ function shortContentHash(content) {
65
+ return createHash('sha256').update(content).digest('hex').slice(0, 8).toUpperCase();
66
+ }
67
+
68
+ export function resolvePolyfillImportSpecifier(specifier, workspaceRoot, projectRoot) {
69
+ const candidateWorkspace = path.resolve(workspaceRoot, specifier);
70
+ if (fs.existsSync(candidateWorkspace) && fs.statSync(candidateWorkspace).isFile()) {
71
+ return toPosixPath(candidateWorkspace);
72
+ }
73
+ const candidateProject = path.resolve(projectRoot, specifier);
74
+ if (fs.existsSync(candidateProject) && fs.statSync(candidateProject).isFile()) {
75
+ return toPosixPath(candidateProject);
76
+ }
77
+ const bases = [projectRoot, workspaceRoot, process.cwd()];
78
+ for (const base of bases) {
79
+ try {
80
+ const req = createRequire(path.join(base, 'package.json'));
81
+ return toPosixPath(req.resolve(specifier));
82
+ } catch {
83
+ // Try next base
84
+ }
85
+ }
86
+ return specifier;
87
+ }
88
+
89
+ function createVirtualEntryPlugin(appOptions) {
90
+ const polyfillImports = appOptions.polyfills.map((spec) =>
91
+ resolvePolyfillImportSpecifier(spec, appOptions.workspaceRoot, appOptions.projectRoot),
92
+ );
93
+ const jitImport = appOptions.aot === false ? `import '@angular/compiler';\n` : '';
94
+ const polyfillCode =
95
+ jitImport +
96
+ polyfillImports.map((imp) => `import ${JSON.stringify(imp)};`).join('\n') +
97
+ '\n';
98
+ const entryCode =
99
+ (polyfillImports.length > 0 ? `import ${JSON.stringify(VIRTUAL_POLYFILLS_ID)};\n` : jitImport) +
100
+ `import ${JSON.stringify(toPosixPath(appOptions.browserEntry))};\n`;
101
+
102
+ return {
103
+ name: 'ngrs:application-virtual-entry',
104
+ enforce: 'pre',
105
+ resolveId(source) {
106
+ if (source === VIRTUAL_POLYFILLS_ID) {
107
+ return RESOLVED_POLYFILLS_ID;
108
+ }
109
+ if (source === VIRTUAL_ENTRY_ID) {
110
+ return RESOLVED_ENTRY_ID;
111
+ }
112
+ return null;
113
+ },
114
+ load(id) {
115
+ if (id === RESOLVED_POLYFILLS_ID) {
116
+ return polyfillCode;
117
+ }
118
+ if (id === RESOLVED_ENTRY_ID) {
119
+ return entryCode;
120
+ }
121
+ return null;
122
+ },
123
+ };
124
+ }
125
+
126
+ export async function compileGlobalStyleBundle(bundle, appOptions) {
127
+ const parts = [];
128
+ for (const rawFile of bundle.files) {
129
+ const absFile = resolvePolyfillImportSpecifier(
130
+ rawFile,
131
+ appOptions.workspaceRoot,
132
+ appOptions.projectRoot,
133
+ );
134
+ if (!fs.existsSync(absFile)) {
135
+ throw new Error(`Global stylesheet "${rawFile}" could not be found at "${absFile}".`);
136
+ }
137
+ const lower = absFile.toLowerCase();
138
+ if (lower.endsWith('.scss') || lower.endsWith('.sass')) {
139
+ const sassCustomOpts = appOptions.stylePreprocessorOptions.sass;
140
+ const hasJsSassCallbacks =
141
+ sassCustomOpts &&
142
+ (sassCustomOpts.functions !== undefined || sassCustomOpts.importers !== undefined);
143
+ let compiledCss = null;
144
+ if (!hasJsSassCallbacks && typeof nativeCompileSass === 'function') {
145
+ try {
146
+ compiledCss = nativeCompileSass(
147
+ absFile,
148
+ appOptions.stylePreprocessorOptions.includePaths,
149
+ Boolean(appOptions.optimization.styles.minify),
150
+ );
151
+ } catch {
152
+ compiledCss = null;
153
+ }
154
+ }
155
+ if (compiledCss === null) {
156
+ const sass = await loadDartSassFallback();
157
+ const compiled = sass.compile(absFile, {
158
+ loadPaths: appOptions.stylePreprocessorOptions.includePaths,
159
+ syntax: lower.endsWith('.sass') ? 'indented' : 'scss',
160
+ style: appOptions.optimization.styles.minify ? 'compressed' : 'expanded',
161
+ ...(sassCustomOpts || {}),
162
+ });
163
+ compiledCss = compiled.css;
164
+ }
165
+ parts.push(compiledCss);
166
+ } else {
167
+ parts.push(await readFile(absFile, 'utf8'));
168
+ }
169
+ }
170
+
171
+ let css = parts.join('\n');
172
+ if (appOptions.optimization.styles.minify && css.trim().length > 0) {
173
+ try {
174
+ if (isRolldownVite) {
175
+ const lcss = loadLightningCss();
176
+ if (lcss && typeof lcss.transform === 'function') {
177
+ const out = lcss.transform({
178
+ filename: `${bundle.name}.css`,
179
+ code: Buffer.from(css, 'utf8'),
180
+ minify: true,
181
+ });
182
+ css = Buffer.from(out.code).toString('utf8');
183
+ } else if (typeof nativeCompileSassString === 'function') {
184
+ css = nativeCompileSassString(css, null, true, false);
185
+ } else {
186
+ const sass = await loadDartSassFallback();
187
+ css = sass.compileString(css, { style: 'compressed' }).css;
188
+ }
189
+ } else if (typeof vite.transformWithEsbuild === 'function') {
190
+ const minified = await vite.transformWithEsbuild(css, `${bundle.name}.css`, {
191
+ loader: 'css',
192
+ minify: true,
193
+ legalComments: appOptions.optimization.styles.removeSpecialComments ? 'none' : 'inline',
194
+ });
195
+ css = minified.code;
196
+ }
197
+ } catch {
198
+ // Keep compiled CSS if minifier encounters non-standard syntax
199
+ }
200
+ }
201
+ return css;
202
+ }
203
+
204
+ async function compileGlobalScriptBundle(bundle, appOptions) {
205
+ const parts = [];
206
+ for (const rawFile of bundle.files) {
207
+ const absFile = resolvePolyfillImportSpecifier(
208
+ rawFile,
209
+ appOptions.workspaceRoot,
210
+ appOptions.projectRoot,
211
+ );
212
+ if (!fs.existsSync(absFile)) {
213
+ throw new Error(`Global script "${rawFile}" could not be found at "${absFile}".`);
214
+ }
215
+ parts.push(await readFile(absFile, 'utf8'));
216
+ }
217
+
218
+ let js = parts.join('\n;\n');
219
+ if (appOptions.optimization.scripts && js.trim().length > 0) {
220
+ if ('minify' in vite && typeof vite.minify === 'function') {
221
+ const minified = await vite.minify(`${bundle.name}.js`, js, {
222
+ sourcemap: false,
223
+ });
224
+ js = minified.code;
225
+ } else if (typeof vite.transformWithEsbuild === 'function') {
226
+ const minified = await vite.transformWithEsbuild(js, `${bundle.name}.js`, {
227
+ loader: 'js',
228
+ minify: true,
229
+ });
230
+ js = minified.code;
231
+ }
232
+ }
233
+ return js;
234
+ }
235
+
236
+ function classifyBundlerOutputs(emittedOutputs) {
237
+ const chunkByFileName = new Map();
238
+ const initialChunkNames = new Map();
239
+
240
+ for (const item of emittedOutputs) {
241
+ if (item.type === 'chunk') {
242
+ chunkByFileName.set(item.fileName, item);
243
+ if (item.isEntry) {
244
+ const entryName =
245
+ item.name ||
246
+ (item.facadeModuleId && !item.facadeModuleId.startsWith('\0')
247
+ ? getEntryPointName(item.facadeModuleId)
248
+ : '-');
249
+ initialChunkNames.set(item.fileName, entryName);
250
+ }
251
+ }
252
+ }
253
+
254
+ // BFS transitive static imports from entry chunks (1:1 with `findTransitiveInitialFiles` in @angular/build)
255
+ const queue = [...initialChunkNames.keys()];
256
+ for (let i = 0; i < queue.length; i++) {
257
+ const fileName = queue[i];
258
+ const chunk = chunkByFileName.get(fileName);
259
+ if (!chunk) continue;
260
+ for (const staticImp of chunk.imports || []) {
261
+ if (!initialChunkNames.has(staticImp) && chunkByFileName.has(staticImp)) {
262
+ initialChunkNames.set(staticImp, '-');
263
+ queue.push(staticImp);
264
+ }
265
+ }
266
+ }
267
+
268
+ const classified = [];
269
+ for (const item of emittedOutputs) {
270
+ if (item.type === 'chunk') {
271
+ const isInitial = initialChunkNames.has(item.fileName);
272
+ let displayName = '-';
273
+ if (isInitial) {
274
+ displayName = initialChunkNames.get(item.fileName) ?? '-';
275
+ } else if (item.isDynamicEntry) {
276
+ if (item.facadeModuleId && !item.facadeModuleId.startsWith('\0')) {
277
+ displayName = getEntryPointName(item.facadeModuleId);
278
+ } else if (item.name && item.name !== 'chunk') {
279
+ displayName = item.name.replace(/[\\/.]/g, '-');
280
+ }
281
+ }
282
+ classified.push({
283
+ kind: 'chunk',
284
+ item,
285
+ fileName: item.fileName,
286
+ name: displayName,
287
+ initial: isInitial,
288
+ contents: item.code,
289
+ size: Buffer.byteLength(item.code, 'utf8'),
290
+ });
291
+ } else if (item.type === 'asset') {
292
+ const size =
293
+ typeof item.source === 'string'
294
+ ? Buffer.byteLength(item.source, 'utf8')
295
+ : item.source.byteLength;
296
+ const isCss = item.fileName.endsWith('.css');
297
+ const stem = isCss
298
+ ? path.basename(item.fileName, '.css').replace(/-[A-Za-z0-9_-]{8,}$/, '') || '-'
299
+ : '-';
300
+ classified.push({
301
+ kind: 'asset',
302
+ item,
303
+ fileName: item.fileName,
304
+ name: stem,
305
+ initial: isCss,
306
+ contents: item.source,
307
+ size,
308
+ });
309
+ }
310
+ }
311
+
312
+ return classified;
313
+ }
314
+
315
+ /**
316
+ * Executes a single production/development browser (and optional server) build for a normalized
317
+ * `@ngrs/build` application configuration using Vite 8's native Rust Rolldown bundler
318
+ * (`build.rolldownOptions`, with `build.rollupOptions` fallback on Vite 6/7).
319
+ *
320
+ * @param {import('../../workspace.mjs').NormalizedApplicationOptions} appOptions
321
+ * @param {object} [logger]
322
+ * @param {object} [extensions]
323
+ */
324
+ export async function executeApplicationBuild(
325
+ appOptions,
326
+ logger = createConsoleLogger(appOptions.verbose),
327
+ extensions = {},
328
+ ) {
329
+ const colors = resolveColorsOption(appOptions.colors);
330
+ const progressTitle = extensions?.rebuild ? 'Changes detected. Rebuilding...' : 'Building...';
331
+ const startTime = performance.now();
332
+ const { outputOptions } = appOptions;
333
+ const browserOutDir = outputOptions.browserDir;
334
+
335
+ const compilerWarnings = [];
336
+ const compilerErrors = [];
337
+
338
+ const recordDiagnostics = (diags) => {
339
+ const formatted = formatDiagnostics(diags, appOptions.workspaceRoot);
340
+ for (const w of formatted.warnings) {
341
+ if (!compilerWarnings.includes(w)) compilerWarnings.push(w);
342
+ }
343
+ for (const e of formatted.errors) {
344
+ if (!compilerErrors.includes(e)) compilerErrors.push(e);
345
+ }
346
+ };
347
+
348
+ let executionOutcome;
349
+ try {
350
+ executionOutcome = await withProgress(
351
+ progressTitle,
352
+ appOptions.progress ?? true,
353
+ colors,
354
+ logger,
355
+ async () => {
356
+ if (
357
+ outputOptions.clean &&
358
+ outputOptions.base !== appOptions.workspaceRoot &&
359
+ isSubDirectory(appOptions.workspaceRoot, outputOptions.base)
360
+ ) {
361
+ await rm(outputOptions.base, { recursive: true, force: true });
362
+ }
363
+ await mkdir(browserOutDir, { recursive: true });
364
+
365
+ const hashBundles =
366
+ appOptions.outputHashing === 'all' || appOptions.outputHashing === 'bundles';
367
+ const hashMedia =
368
+ appOptions.outputHashing === 'all' || appOptions.outputHashing === 'media';
369
+
370
+ /** @type {Array<{ file: string, css: string, size: number }>} */
371
+ let collectedComponentStyles = [];
372
+
373
+ const entryInputs = {
374
+ ...(appOptions.polyfills.length > 0 ? { polyfills: VIRTUAL_POLYFILLS_ID } : {}),
375
+ main: VIRTUAL_ENTRY_ID,
376
+ };
377
+
378
+ const defineMap = {
379
+ ...(appOptions.optimization.scripts
380
+ ? {
381
+ ngDevMode: 'false',
382
+ ngI18nClosureMode: 'false',
383
+ ...(appOptions.aot !== false ? { ngJitMode: 'false' } : {}),
384
+ }
385
+ : {}),
386
+ ngServerMode: 'false',
387
+ ...(appOptions.define || {}),
388
+ };
389
+
390
+ const externalPatterns = appOptions.externalDependencies.map(
391
+ (dep) => new RegExp(`^${dep.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:$|\\/)`),
392
+ );
393
+
394
+ const bundlerOptionsKey = isRolldownVite ? 'rolldownOptions' : 'rollupOptions';
395
+ const browserBundlerOptions = {
396
+ input: entryInputs,
397
+ external: externalPatterns.length > 0 ? externalPatterns : undefined,
398
+ output: {
399
+ format: 'es',
400
+ entryFileNames: hashBundles ? '[name]-[hash].js' : '[name].js',
401
+ chunkFileNames: appOptions.namedChunks
402
+ ? hashBundles
403
+ ? '[name]-[hash].js'
404
+ : '[name].js'
405
+ : hashBundles
406
+ ? 'chunk-[hash].js'
407
+ : 'chunk-[name].js',
408
+ assetFileNames: hashMedia
409
+ ? `${outputOptions.media}/[name]-[hash][extname]`
410
+ : `${outputOptions.media}/[name][extname]`,
411
+ },
412
+ };
413
+
414
+ const prebuildGlobalStylesPromise = Promise.all(
415
+ appOptions.globalStyles.map((styleBundle) =>
416
+ compileGlobalStyleBundle(styleBundle, appOptions),
417
+ ),
418
+ );
419
+ const prebuildGlobalScriptsPromise = Promise.all(
420
+ appOptions.globalScripts.map((scriptBundle) =>
421
+ compileGlobalScriptBundle(scriptBundle, appOptions),
422
+ ),
423
+ );
424
+ const prebuildAssetsPromise = resolveAssets(appOptions.assets, appOptions.workspaceRoot);
425
+ prebuildGlobalStylesPromise.catch(() => {});
426
+ prebuildGlobalScriptsPromise.catch(() => {});
427
+ prebuildAssetsPromise.catch(() => {});
428
+
429
+ const buildOutput = await viteBuild({
430
+ configFile: false,
431
+ envDir: false,
432
+ root: appOptions.workspaceRoot,
433
+ base: appOptions.deployUrl || appOptions.baseHref || './',
434
+ mode: appOptions.optimization.scripts ? 'production' : 'development',
435
+ logLevel: 'silent',
436
+ publicDir: false,
437
+ define: defineMap,
438
+ resolve: {
439
+ preserveSymlinks: appOptions.preserveSymlinks,
440
+ alias: appOptions.fileReplacements.map((r) => ({
441
+ find: r.replace,
442
+ replacement: r.with,
443
+ })),
444
+ ...(appOptions.conditions ? { conditions: appOptions.conditions } : {}),
445
+ },
446
+ css: {
447
+ preprocessorOptions: {
448
+ scss: { loadPaths: appOptions.stylePreprocessorOptions.includePaths },
449
+ sass: { loadPaths: appOptions.stylePreprocessorOptions.includePaths },
450
+ },
451
+ },
452
+ plugins: [
453
+ createVirtualEntryPlugin(appOptions),
454
+ ...angular({
455
+ tsconfig: appOptions.tsconfigPath,
456
+ workspaceRoot: appOptions.workspaceRoot,
457
+ fileReplacements: appOptions.fileReplacements,
458
+ hmr: false,
459
+ sourceMap: appOptions.sourceMap.scripts,
460
+ inlineStyleLanguage: appOptions.inlineStyleLanguage,
461
+ stylePreprocessorOptions: appOptions.stylePreprocessorOptions,
462
+ jit: !appOptions.aot,
463
+ suppressViteDiagnosticsLog: true,
464
+ onDiagnostics: recordDiagnostics,
465
+ onComponentStylesCollected(styles) {
466
+ collectedComponentStyles = styles;
467
+ },
468
+ }),
469
+ ...(extensions?.plugins || []),
470
+ ],
471
+ build: {
472
+ outDir: browserOutDir,
473
+ emptyOutDir: false,
474
+ target: 'es2022',
475
+ minify: appOptions.optimization.scripts ? (isRolldownVite ? 'oxc' : 'esbuild') : false,
476
+ cssMinify: appOptions.optimization.styles.minify
477
+ ? isRolldownVite
478
+ ? 'lightningcss'
479
+ : true
480
+ : false,
481
+ sourcemap: appOptions.sourceMap.scripts
482
+ ? appOptions.sourceMap.hidden
483
+ ? 'hidden'
484
+ : true
485
+ : false,
486
+ [bundlerOptionsKey]: browserBundlerOptions,
487
+ },
488
+ });
489
+
490
+ const bundlerResults = Array.isArray(buildOutput) ? buildOutput : [buildOutput];
491
+ const emittedOutputs = bundlerResults.flatMap((r) => r.output || []);
492
+ const classifiedBrowser = classifyBundlerOutputs(emittedOutputs);
493
+
494
+ /** @type {Array<{ files: string[], names: string[], initial: boolean }>} */
495
+ const budgetChunks = [];
496
+ /** @type {Array<{ name: string, size: number, componentStyle?: boolean }>} */
497
+ const budgetAssets = [];
498
+ /** @type {Array<{ path: string, contents: Buffer | Uint8Array | string, size: number, initial: boolean, name: string }>} */
499
+ const statsFiles = [];
500
+
501
+ let polyfillsBundleFile = null;
502
+ let polyfillsContent = '';
503
+ let mainBundleFile = null;
504
+ let mainContent = '';
505
+
506
+ for (const entry of classifiedBrowser) {
507
+ if (entry.kind === 'chunk') {
508
+ budgetChunks.push({
509
+ files: [entry.fileName],
510
+ names: entry.name !== '-' ? [entry.name] : [],
511
+ initial: entry.initial,
512
+ });
513
+ budgetAssets.push({
514
+ name: entry.fileName,
515
+ size: entry.size,
516
+ });
517
+ statsFiles.push({
518
+ path: entry.fileName,
519
+ contents: entry.contents,
520
+ size: entry.size,
521
+ initial: entry.initial,
522
+ name: entry.name,
523
+ });
524
+ if (entry.item.name === 'polyfills' && entry.item.isEntry) {
525
+ polyfillsBundleFile = entry.fileName;
526
+ polyfillsContent = entry.contents;
527
+ } else if (entry.item.name === 'main' && entry.item.isEntry) {
528
+ mainBundleFile = entry.fileName;
529
+ mainContent = entry.contents;
530
+ }
531
+ } else {
532
+ budgetAssets.push({
533
+ name: entry.fileName,
534
+ size: entry.size,
535
+ });
536
+ if (/\.(?:css|m?js)$/.test(entry.fileName)) {
537
+ statsFiles.push({
538
+ path: entry.fileName,
539
+ contents: entry.contents,
540
+ size: entry.size,
541
+ initial: entry.initial,
542
+ name: entry.name,
543
+ });
544
+ }
545
+ }
546
+ }
547
+
548
+ const [compiledGlobalStyles, compiledGlobalScripts, resolvedAssetFiles] =
549
+ await Promise.all([
550
+ prebuildGlobalStylesPromise,
551
+ prebuildGlobalScriptsPromise,
552
+ prebuildAssetsPromise,
553
+ ]);
554
+
555
+ // Emit global styles
556
+ const injectedStylesForHtml = [];
557
+ for (let i = 0; i < appOptions.globalStyles.length; i++) {
558
+ const styleBundle = appOptions.globalStyles[i];
559
+ const css = compiledGlobalStyles[i];
560
+ const fileName = hashBundles
561
+ ? `${styleBundle.name}-${shortContentHash(css)}.css`
562
+ : `${styleBundle.name}.css`;
563
+ await writeFile(path.join(browserOutDir, fileName), css, 'utf8');
564
+ const size = Buffer.byteLength(css, 'utf8');
565
+ budgetChunks.push({
566
+ files: [fileName],
567
+ names: [styleBundle.name],
568
+ initial: styleBundle.initial,
569
+ });
570
+ budgetAssets.push({ name: fileName, size });
571
+ statsFiles.push({
572
+ path: fileName,
573
+ contents: css,
574
+ size,
575
+ initial: styleBundle.initial,
576
+ name: styleBundle.name,
577
+ });
578
+ if (styleBundle.initial) {
579
+ injectedStylesForHtml.push({ href: fileName, content: css });
580
+ }
581
+ }
582
+
583
+ // Emit global scripts
584
+ const injectedScriptsForHtml = [];
585
+ for (let i = 0; i < appOptions.globalScripts.length; i++) {
586
+ const scriptBundle = appOptions.globalScripts[i];
587
+ const js = compiledGlobalScripts[i];
588
+ const fileName = hashBundles
589
+ ? `${scriptBundle.name}-${shortContentHash(js)}.js`
590
+ : `${scriptBundle.name}.js`;
591
+ await writeFile(path.join(browserOutDir, fileName), js, 'utf8');
592
+ const size = Buffer.byteLength(js, 'utf8');
593
+ budgetChunks.push({
594
+ files: [fileName],
595
+ names: [scriptBundle.name],
596
+ initial: scriptBundle.initial,
597
+ });
598
+ budgetAssets.push({ name: fileName, size });
599
+ statsFiles.push({
600
+ path: fileName,
601
+ contents: js,
602
+ size,
603
+ initial: scriptBundle.initial,
604
+ name: scriptBundle.name,
605
+ });
606
+ if (scriptBundle.initial) {
607
+ injectedScriptsForHtml.push({
608
+ src: fileName,
609
+ isModule: false,
610
+ defer: true,
611
+ content: js,
612
+ });
613
+ }
614
+ }
615
+
616
+ // Copy static assets
617
+ await Promise.all(
618
+ resolvedAssetFiles.map(async (asset) => {
619
+ const destAbs = path.join(browserOutDir, asset.destination);
620
+ await mkdir(path.dirname(destAbs), { recursive: true });
621
+ await copyFile(asset.source, destAbs);
622
+ }),
623
+ );
624
+
625
+ // Transform and write index.html
626
+ if (appOptions.indexHtmlOptions && fs.existsSync(appOptions.indexHtmlOptions.input)) {
627
+ const rawHtml = await readFile(appOptions.indexHtmlOptions.input, 'utf8');
628
+ const htmlScripts = [...injectedScriptsForHtml];
629
+ if (polyfillsBundleFile) {
630
+ htmlScripts.push({
631
+ src: polyfillsBundleFile,
632
+ isModule: true,
633
+ content: polyfillsContent,
634
+ });
635
+ }
636
+ if (mainBundleFile) {
637
+ htmlScripts.push({
638
+ src: mainBundleFile,
639
+ isModule: true,
640
+ content: mainContent,
641
+ });
642
+ }
643
+
644
+ let finalHtml = transformIndexHtmlContent({
645
+ html: rawHtml,
646
+ baseHref: appOptions.baseHref,
647
+ deployUrl: appOptions.deployUrl,
648
+ crossOrigin: appOptions.crossOrigin,
649
+ sri: appOptions.subresourceIntegrity,
650
+ styles: injectedStylesForHtml,
651
+ scripts: htmlScripts,
652
+ });
653
+
654
+ if (typeof extensions?.indexHtmlTransformer === 'function') {
655
+ finalHtml = await extensions.indexHtmlTransformer(finalHtml);
656
+ }
657
+
658
+ const outHtmlPath = path.join(browserOutDir, appOptions.indexHtmlOptions.output);
659
+ await mkdir(path.dirname(outHtmlPath), { recursive: true });
660
+ await writeFile(outHtmlPath, finalHtml, 'utf8');
661
+ }
662
+
663
+ // Optional SSR server bundle when configured
664
+ const serverStats = [];
665
+ if (appOptions.ssr && appOptions.serverEntry && fs.existsSync(appOptions.serverEntry)) {
666
+ await mkdir(outputOptions.serverDir, { recursive: true });
667
+ const serverBuildOut = await viteBuild({
668
+ configFile: false,
669
+ envDir: false,
670
+ root: appOptions.workspaceRoot,
671
+ mode: appOptions.optimization.scripts ? 'production' : 'development',
672
+ logLevel: 'silent',
673
+ publicDir: false,
674
+ define: {
675
+ ...defineMap,
676
+ ngServerMode: 'true',
677
+ },
678
+ resolve: {
679
+ preserveSymlinks: appOptions.preserveSymlinks,
680
+ alias: appOptions.fileReplacements.map((r) => ({
681
+ find: r.replace,
682
+ replacement: r.with,
683
+ })),
684
+ },
685
+ plugins: [
686
+ ...angular({
687
+ tsconfig: appOptions.tsconfigPath,
688
+ workspaceRoot: appOptions.workspaceRoot,
689
+ fileReplacements: appOptions.fileReplacements,
690
+ hmr: false,
691
+ sourceMap: appOptions.sourceMap.scripts,
692
+ inlineStyleLanguage: appOptions.inlineStyleLanguage,
693
+ stylePreprocessorOptions: appOptions.stylePreprocessorOptions,
694
+ jit: !appOptions.aot,
695
+ suppressViteDiagnosticsLog: true,
696
+ onDiagnostics: recordDiagnostics,
697
+ }),
698
+ ],
699
+ build: {
700
+ ssr: appOptions.serverEntry,
701
+ outDir: outputOptions.serverDir,
702
+ emptyOutDir: false,
703
+ target: 'es2022',
704
+ minify: false,
705
+ sourcemap: appOptions.sourceMap.scripts,
706
+ [bundlerOptionsKey]: {
707
+ output: {
708
+ format: 'es',
709
+ entryFileNames: '[name].mjs',
710
+ },
711
+ },
712
+ },
713
+ });
714
+
715
+ const srvResults = Array.isArray(serverBuildOut) ? serverBuildOut : [serverBuildOut];
716
+ const srvClassified = classifyBundlerOutputs(
717
+ srvResults.flatMap((r) => r.output || []),
718
+ );
719
+ for (const entry of srvClassified) {
720
+ if (/\.(?:css|m?js)$/.test(entry.fileName)) {
721
+ serverStats.push({
722
+ initial: entry.initial,
723
+ stats: [entry.fileName, entry.name, entry.size, '-'],
724
+ });
725
+ }
726
+ }
727
+ }
728
+
729
+ // Add component stylesheets for `anyComponentStyle` budget checks
730
+ for (const compStyle of collectedComponentStyles) {
731
+ budgetAssets.push({
732
+ name: path.relative(appOptions.workspaceRoot, compStyle.file),
733
+ size: compStyle.size,
734
+ componentStyle: true,
735
+ });
736
+ }
737
+
738
+ const budgetResults = checkBudgets(appOptions.budgets, {
739
+ chunks: budgetChunks,
740
+ assets: budgetAssets,
741
+ });
742
+
743
+ const showTransferSizes = Boolean(
744
+ appOptions.optimization.scripts || appOptions.optimization.styles.minify,
745
+ );
746
+ const estimatedTransferSizes = showTransferSizes
747
+ ? await calculateEstimatedTransferSizes(statsFiles)
748
+ : undefined;
749
+
750
+ const browserStats = statsFiles.map((f) => ({
751
+ initial: f.initial,
752
+ stats: [
753
+ f.path,
754
+ f.name ?? '-',
755
+ f.size,
756
+ estimatedTransferSizes?.get(f.path) ?? '-',
757
+ ],
758
+ }));
759
+
760
+ if (appOptions.statsJson) {
761
+ await writeFile(
762
+ path.join(outputOptions.base, 'stats.json'),
763
+ JSON.stringify({ chunks: budgetChunks, assets: budgetAssets }, null, 2),
764
+ 'utf8',
765
+ );
766
+ }
767
+
768
+ return {
769
+ budgetChunks,
770
+ budgetAssets,
771
+ budgetResults,
772
+ browserStats,
773
+ serverStats,
774
+ showTransferSizes,
775
+ };
776
+ },
777
+ );
778
+ } catch (err) {
779
+ const durationSec = ((performance.now() - startTime) / 1000).toFixed(3);
780
+ const rawMsg = err instanceof Error ? err.message : String(err);
781
+ logger.info(
782
+ `Application bundle generation failed. [${durationSec} seconds] - ${new Date().toISOString()}\n`,
783
+ );
784
+ const allErrors = compilerErrors.length > 0 ? compilerErrors : [rawMsg];
785
+ if (compilerWarnings.length > 0) {
786
+ logger.warn(compilerWarnings.map((w) => formatBuildMessage(w, 'warning', colors)).join('\n'));
787
+ }
788
+ logger.error(allErrors.map((e) => formatBuildMessage(e, 'error', colors)).join('\n'));
789
+ return {
790
+ success: false,
791
+ outputPath: outputOptions.base,
792
+ browserOutputPath: browserOutDir,
793
+ errors: allErrors,
794
+ };
795
+ }
796
+
797
+ const {
798
+ budgetChunks,
799
+ budgetAssets,
800
+ budgetResults,
801
+ browserStats,
802
+ serverStats,
803
+ showTransferSizes,
804
+ } = executionOutcome;
805
+
806
+ const warnings = [...compilerWarnings];
807
+ const errors = [...compilerErrors];
808
+ let hasBudgetError = false;
809
+ for (const br of budgetResults) {
810
+ if (br.severity === 'error') {
811
+ hasBudgetError = true;
812
+ errors.push(br.message);
813
+ } else {
814
+ warnings.push(br.message);
815
+ }
816
+ }
817
+
818
+ const durationSec = ((performance.now() - startTime) / 1000).toFixed(3);
819
+ const initialTotal = budgetChunks
820
+ .filter((c) => c.initial)
821
+ .flatMap((c) => c.files)
822
+ .reduce((sum, f) => {
823
+ const asset = budgetAssets.find((a) => a.name === f && !a.componentStyle);
824
+ return sum + (asset?.size ?? 0);
825
+ }, 0);
826
+
827
+ const tableText = generateEsbuildBuildStatsTable(
828
+ [browserStats, serverStats],
829
+ colors,
830
+ true,
831
+ showTransferSizes,
832
+ budgetResults,
833
+ appOptions.verbose,
834
+ );
835
+
836
+ const hasError = hasBudgetError || errors.length > 0;
837
+ const logs = [];
838
+ if (tableText) {
839
+ logs.push(tableText + '\n');
840
+ }
841
+ logs.push(
842
+ `Application bundle generation ${hasError ? 'failed' : 'complete'}. [${durationSec} seconds] - ${new Date().toISOString()}\n`,
843
+ );
844
+ logger.info(logs.join('\n'));
845
+
846
+ if (warnings.length > 0) {
847
+ logger.warn(warnings.map((w) => formatBuildMessage(w, 'warning', colors)).join('\n'));
848
+ }
849
+ if (errors.length > 0) {
850
+ logger.error(errors.map((e) => formatBuildMessage(e, 'error', colors)).join('\n'));
851
+ }
852
+
853
+ if (appOptions.watch && !extensions?.rebuild && (appOptions.progress ?? true)) {
854
+ logger.info('Watch mode enabled. Watching for file changes...');
855
+ }
856
+
857
+ if (!hasError && !extensions?.skipOutputLocationLog) {
858
+ logger.info(`Output location: ${outputOptions.base}\n`);
859
+ }
860
+
861
+ return {
862
+ success: !hasError,
863
+ outputPath: outputOptions.base,
864
+ browserOutputPath: browserOutDir,
865
+ stats: {
866
+ chunks: budgetChunks,
867
+ assets: budgetAssets,
868
+ initialTotalBytes: initialTotal,
869
+ },
870
+ budgetResults,
871
+ };
872
+ }
873
+
874
+ /**
875
+ * Architect-compatible `buildApplication` async generator (`@ngrs/build:application`,
876
+ * `@ngrs/build:browser-esbuild`, `@ngrs/build:browser`).
877
+ */
878
+ export async function* buildApplication(options = {}, context = {}, extensions) {
879
+ const workspaceRoot = context?.workspaceRoot || options?.workspaceRoot || process.cwd();
880
+ const logger = context?.logger || createConsoleLogger(Boolean(options?.verbose));
881
+
882
+ let projectName = context?.target?.project || options?.project;
883
+ let projectMetadata = {};
884
+ let loadedWorkspace = null;
885
+
886
+ if (context?.getProjectMetadata && projectName) {
887
+ projectMetadata = await context.getProjectMetadata(projectName);
888
+ } else {
889
+ try {
890
+ const loaded = await loadWorkspace(workspaceRoot);
891
+ loadedWorkspace = loaded.workspace;
892
+ projectName = resolveProjectName(loaded.workspace, projectName);
893
+ projectMetadata = loaded.workspace.projects[projectName] || {};
894
+ } catch {
895
+ projectName = projectName || 'app';
896
+ }
897
+ }
898
+
899
+ let effectiveOptions = { ...(options || {}) };
900
+ delete effectiveOptions.workspaceRoot;
901
+ delete effectiveOptions.project;
902
+ const requestedConfig = context?.target?.configuration || effectiveOptions.configuration;
903
+ delete effectiveOptions.configuration;
904
+
905
+ if (!effectiveOptions.tsConfig && loadedWorkspace) {
906
+ const targets =
907
+ loadedWorkspace.projects?.[projectName]?.architect ||
908
+ loadedWorkspace.projects?.[projectName]?.targets ||
909
+ {};
910
+ const targetName = context?.target?.target || 'build';
911
+ if (targets[targetName]) {
912
+ const workspaceTargetOpts = resolveTargetOptions(
913
+ loadedWorkspace,
914
+ {
915
+ project: projectName,
916
+ target: targetName,
917
+ ...(requestedConfig ? { configuration: requestedConfig } : {}),
918
+ },
919
+ 'production',
920
+ );
921
+ effectiveOptions = {
922
+ ...workspaceTargetOpts,
923
+ ...effectiveOptions,
924
+ };
925
+ }
926
+ }
927
+
928
+ const normalized = normalizeApplicationOptions(
929
+ effectiveOptions,
930
+ projectMetadata,
931
+ workspaceRoot,
932
+ projectName,
933
+ );
934
+
935
+ const firstResult = await executeApplicationBuild(normalized, logger, extensions);
936
+ yield firstResult;
937
+
938
+ if (!normalized.watch) {
939
+ return;
940
+ }
941
+
942
+ // Watch mode: watch sourceRoot for changes and trigger rebuilds until stopped
943
+ let closed = false;
944
+ let watcher;
945
+ let resolveNext;
946
+
947
+ const stopWatching = () => {
948
+ closed = true;
949
+ watcher?.close();
950
+ resolveNext?.();
951
+ };
952
+ context?.addTeardown?.(stopWatching);
953
+
954
+ const watchDir = fs.existsSync(normalized.projectSourceRoot)
955
+ ? normalized.projectSourceRoot
956
+ : normalized.projectRoot;
957
+
958
+ let debounceTimer = null;
959
+ watcher = fs.watch(watchDir, { recursive: true }, (_event, filename) => {
960
+ if (!filename) return;
961
+ const norm = toPosixPath(filename);
962
+ if (norm.includes('node_modules/') || norm.startsWith('dist/')) return;
963
+ clearTimeout(debounceTimer);
964
+ debounceTimer = setTimeout(() => {
965
+ resolveNext?.();
966
+ }, 100);
967
+ });
968
+
969
+ try {
970
+ while (!closed) {
971
+ await new Promise((resolve) => {
972
+ resolveNext = resolve;
973
+ });
974
+ if (closed) break;
975
+ if (normalized.clearScreen) {
976
+ console.clear();
977
+ }
978
+ const nextResult = await executeApplicationBuild(
979
+ {
980
+ ...normalized,
981
+ outputOptions: { ...normalized.outputOptions, clean: false },
982
+ },
983
+ logger,
984
+ { ...(extensions || {}), rebuild: true },
985
+ );
986
+ yield nextResult;
987
+ }
988
+ } finally {
989
+ stopWatching();
990
+ }
991
+ }
992
+
993
+ export const applicationBuilder = createBuilder(buildApplication);
994
+ export default applicationBuilder;