-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathindex.ts
418 lines (372 loc) · 13.7 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect';
import * as assert from 'assert';
import type { Message, OutputFile } from 'esbuild';
import { promises as fs } from 'fs';
import * as path from 'path';
import { NormalizedOptimizationOptions, deleteOutputDir } from '../../utils';
import { copyAssets } from '../../utils/copy-assets';
import { assertIsError } from '../../utils/error';
import { transformSupportedBrowsersToTargets } from '../../utils/esbuild-targets';
import { FileInfo } from '../../utils/index-file/augment-index-html';
import { IndexHtmlGenerator } from '../../utils/index-file/index-html-generator';
import { generateEntryPoints } from '../../utils/package-chunk-sort';
import { augmentAppWithServiceWorker } from '../../utils/service-worker';
import { getSupportedBrowsers } from '../../utils/supported-browsers';
import { getIndexInputFile, getIndexOutputFile } from '../../utils/webpack-browser-config';
import { resolveGlobalStyles } from '../../webpack/configs';
import { createCompilerPlugin } from './compiler-plugin';
import { bundle, logMessages } from './esbuild';
import { logExperimentalWarnings } from './experimental-warnings';
import { normalizeOptions } from './options';
import { Schema as BrowserBuilderOptions, SourceMapClass } from './schema';
import { bundleStylesheetText } from './stylesheets';
/**
* Main execution function for the esbuild-based application builder.
* The options are compatible with the Webpack-based builder.
* @param options The browser builder options to use when setting up the application build
* @param context The Architect builder context object
* @returns A promise with the builder result output
*/
// eslint-disable-next-line max-lines-per-function
export async function buildEsbuildBrowser(
options: BrowserBuilderOptions,
context: BuilderContext,
): Promise<BuilderOutput> {
const startTime = Date.now();
// Only AOT is currently supported
if (options.aot !== true) {
context.logger.error(
'JIT mode is currently not supported by this experimental builder. AOT mode must be used.',
);
return { success: false };
}
// Inform user of experimental status of builder and options
logExperimentalWarnings(options, context);
// Determine project name from builder context target
const projectName = context.target?.project;
if (!projectName) {
context.logger.error(`The 'browser-esbuild' builder requires a target to be specified.`);
return { success: false };
}
const {
projectRoot,
workspaceRoot,
entryPoints,
entryPointNameLookup,
optimizationOptions,
outputPath,
sourcemapOptions,
tsconfig,
assets,
outputNames,
} = await normalizeOptions(context, projectName, options);
// Clean output path if enabled
if (options.deleteOutputPath) {
deleteOutputDir(workspaceRoot, options.outputPath);
}
// Create output directory if needed
try {
await fs.mkdir(outputPath, { recursive: true });
} catch (e) {
assertIsError(e);
context.logger.error('Unable to create output directory: ' + e.message);
return { success: false };
}
const target = transformSupportedBrowsersToTargets(
getSupportedBrowsers(projectRoot, context.logger),
);
const [codeResults, styleResults] = await Promise.all([
// Execute esbuild to bundle the application code
bundleCode(
workspaceRoot,
entryPoints,
outputNames,
options,
optimizationOptions,
sourcemapOptions,
tsconfig,
target,
),
// Execute esbuild to bundle the global stylesheets
bundleGlobalStylesheets(
workspaceRoot,
outputNames,
options,
optimizationOptions,
sourcemapOptions,
target,
),
]);
// Log all warnings and errors generated during bundling
await logMessages(context, {
errors: [...codeResults.errors, ...styleResults.errors],
warnings: [...codeResults.warnings, ...styleResults.warnings],
});
// Return if the bundling failed to generate output files or there are errors
if (!codeResults.outputFiles || codeResults.errors.length) {
return { success: false };
}
// Structure the code bundling output files
const initialFiles: FileInfo[] = [];
const outputFiles: OutputFile[] = [];
for (const outputFile of codeResults.outputFiles) {
// Entries in the metafile are relative to the `absWorkingDir` option which is set to the workspaceRoot
const relativeFilePath = path.relative(workspaceRoot, outputFile.path);
const entryPoint = codeResults.metafile?.outputs[relativeFilePath]?.entryPoint;
outputFile.path = relativeFilePath;
if (entryPoint) {
// An entryPoint value indicates an initial file
initialFiles.push({
file: outputFile.path,
name: entryPointNameLookup.get(entryPoint) ?? '',
extension: path.extname(outputFile.path),
});
}
outputFiles.push(outputFile);
}
// Add global stylesheets output files
outputFiles.push(...styleResults.outputFiles);
initialFiles.push(...styleResults.initialFiles);
// Return if the global stylesheet bundling has errors
if (styleResults.errors.length) {
return { success: false };
}
// Generate index HTML file
if (options.index) {
const entrypoints = generateEntryPoints({
scripts: options.scripts ?? [],
styles: options.styles ?? [],
});
// Create an index HTML generator that reads from the in-memory output files
const indexHtmlGenerator = new IndexHtmlGenerator({
indexPath: path.join(context.workspaceRoot, getIndexInputFile(options.index)),
entrypoints,
sri: options.subresourceIntegrity,
optimization: optimizationOptions,
crossOrigin: options.crossOrigin,
});
/** Virtual output path to support reading in-memory files. */
const virtualOutputPath = '/';
indexHtmlGenerator.readAsset = async function (filePath: string): Promise<string> {
// Remove leading directory separator
const relativefilePath = path.relative(virtualOutputPath, filePath);
const file = outputFiles.find((file) => file.path === relativefilePath);
if (file) {
return file.text;
}
throw new Error(`Output file does not exist: ${path}`);
};
const { content, warnings, errors } = await indexHtmlGenerator.process({
baseHref: options.baseHref,
lang: undefined,
outputPath: virtualOutputPath,
files: initialFiles,
});
for (const error of errors) {
context.logger.error(error);
}
for (const warning of warnings) {
context.logger.warn(warning);
}
outputFiles.push(createOutputFileFromText(getIndexOutputFile(options.index), content));
}
// Copy assets
if (assets) {
await copyAssets(assets, [outputPath], workspaceRoot);
}
// Write output files
await Promise.all(
outputFiles.map((file) => fs.writeFile(path.join(outputPath, file.path), file.contents)),
);
// Augment the application with service worker support
// TODO: This should eventually operate on the in-memory files prior to writing the output files
if (options.serviceWorker) {
try {
await augmentAppWithServiceWorker(
projectRoot,
workspaceRoot,
outputPath,
options.baseHref || '/',
options.ngswConfigPath,
);
} catch (error) {
context.logger.error(error instanceof Error ? error.message : `${error}`);
return { success: false };
}
}
context.logger.info(`Complete. [${(Date.now() - startTime) / 1000} seconds]`);
return { success: true };
}
function createOutputFileFromText(path: string, text: string): OutputFile {
return {
path,
text,
get contents() {
return Buffer.from(this.text, 'utf-8');
},
};
}
async function bundleCode(
workspaceRoot: string,
entryPoints: Record<string, string>,
outputNames: { bundles: string; media: string },
options: BrowserBuilderOptions,
optimizationOptions: NormalizedOptimizationOptions,
sourcemapOptions: SourceMapClass,
tsconfig: string,
target: string[],
) {
let fileReplacements: Record<string, string> | undefined;
if (options.fileReplacements) {
for (const replacement of options.fileReplacements) {
fileReplacements ??= {};
fileReplacements[path.join(workspaceRoot, replacement.replace)] = path.join(
workspaceRoot,
replacement.with,
);
}
}
return bundle({
absWorkingDir: workspaceRoot,
bundle: true,
format: 'esm',
entryPoints,
entryNames: outputNames.bundles,
assetNames: outputNames.media,
target,
supported: {
// Native async/await is not supported with Zone.js. Disabling support here will cause
// esbuild to downlevel async/await and for await...of to a Zone.js supported form. However, esbuild
// does not currently support downleveling async generators. Instead babel is used within the JS/TS
// loader to perform the downlevel transformation.
// NOTE: If esbuild adds support in the future, the babel support for async generators can be disabled.
'async-await': false,
},
mainFields: ['es2020', 'browser', 'module', 'main'],
conditions: ['es2020', 'es2015', 'module'],
resolveExtensions: ['.ts', '.tsx', '.mjs', '.js'],
logLevel: options.verbose ? 'debug' : 'silent',
metafile: true,
minify: optimizationOptions.scripts,
pure: ['forwardRef'],
outdir: workspaceRoot,
sourcemap: sourcemapOptions.scripts && (sourcemapOptions.hidden ? 'external' : true),
splitting: true,
tsconfig,
external: options.externalDependencies,
write: false,
platform: 'browser',
preserveSymlinks: options.preserveSymlinks,
plugins: [
createCompilerPlugin(
// JS/TS options
{
sourcemap: !!sourcemapOptions.scripts,
thirdPartySourcemaps: sourcemapOptions.vendor,
tsconfig,
advancedOptimizations: options.buildOptimizer,
fileReplacements,
},
// Component stylesheet options
{
workspaceRoot,
optimization: !!optimizationOptions.styles.minify,
sourcemap:
// Hidden component stylesheet sourcemaps are inaccessible which is effectively
// the same as being disabled. Disabling has the advantage of avoiding the overhead
// of sourcemap processing.
!!sourcemapOptions.styles && (sourcemapOptions.hidden ? false : 'inline'),
outputNames,
includePaths: options.stylePreprocessorOptions?.includePaths,
externalDependencies: options.externalDependencies,
target,
},
),
],
define: {
...(optimizationOptions.scripts ? { 'ngDevMode': 'false' } : undefined),
'ngJitMode': 'false',
},
});
}
async function bundleGlobalStylesheets(
workspaceRoot: string,
outputNames: { bundles: string; media: string },
options: BrowserBuilderOptions,
optimizationOptions: NormalizedOptimizationOptions,
sourcemapOptions: SourceMapClass,
target: string[],
) {
const outputFiles: OutputFile[] = [];
const initialFiles: FileInfo[] = [];
const errors: Message[] = [];
const warnings: Message[] = [];
// resolveGlobalStyles is temporarily reused from the Webpack builder code
const { entryPoints: stylesheetEntrypoints, noInjectNames } = resolveGlobalStyles(
options.styles || [],
workspaceRoot,
// preserveSymlinks is always true here to allow the bundler to handle the option
true,
// skipResolution to leverage the bundler's more comprehensive resolution
true,
);
for (const [name, files] of Object.entries(stylesheetEntrypoints)) {
const virtualEntryData = files
.map((file) => `@import '${file.replace(/\\/g, '/')}';`)
.join('\n');
const sheetResult = await bundleStylesheetText(
virtualEntryData,
{ virtualName: `angular:style/global;${name}`, resolvePath: workspaceRoot },
{
workspaceRoot,
optimization: !!optimizationOptions.styles.minify,
sourcemap: !!sourcemapOptions.styles && (sourcemapOptions.hidden ? 'external' : true),
outputNames: noInjectNames.includes(name) ? { media: outputNames.media } : outputNames,
includePaths: options.stylePreprocessorOptions?.includePaths,
preserveSymlinks: options.preserveSymlinks,
externalDependencies: options.externalDependencies,
target,
},
);
errors.push(...sheetResult.errors);
warnings.push(...sheetResult.warnings);
if (!sheetResult.path) {
// Failed to process the stylesheet
assert.ok(
sheetResult.errors.length,
`Global stylesheet processing for '${name}' failed with no errors.`,
);
continue;
}
// The virtual stylesheets will be named `stdin` by esbuild. This must be replaced
// with the actual name of the global style and the leading directory separator must
// also be removed to make the path relative.
const sheetPath = sheetResult.path.replace('stdin', name);
let sheetContents = sheetResult.contents;
if (sheetResult.map) {
outputFiles.push(createOutputFileFromText(sheetPath + '.map', sheetResult.map));
sheetContents = sheetContents.replace(
'sourceMappingURL=stdin.css.map',
`sourceMappingURL=${name}.css.map`,
);
}
outputFiles.push(createOutputFileFromText(sheetPath, sheetContents));
if (!noInjectNames.includes(name)) {
initialFiles.push({
file: sheetPath,
name,
extension: '.css',
});
}
outputFiles.push(...sheetResult.resourceFiles);
}
return { outputFiles, initialFiles, errors, warnings };
}
export default createBuilder(buildEsbuildBrowser);