forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
esbuild.ts
153 lines (139 loc) · 4.96 KB
/
esbuild.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
/**
* @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 } from '@angular-devkit/architect';
import {
BuildContext,
BuildFailure,
BuildOptions,
Message,
Metafile,
OutputFile,
PartialMessage,
build,
context,
formatMessages,
} from 'esbuild';
import { basename, extname, relative } from 'node:path';
import { FileInfo } from '../../utils/index-file/augment-index-html';
/**
* Determines if an unknown value is an esbuild BuildFailure error object thrown by esbuild.
* @param value A potential esbuild BuildFailure error object.
* @returns `true` if the object is determined to be a BuildFailure object; otherwise, `false`.
*/
export function isEsBuildFailure(value: unknown): value is BuildFailure {
return !!value && typeof value === 'object' && 'errors' in value && 'warnings' in value;
}
export class BundlerContext {
#esbuildContext?: BuildContext<{ metafile: true; write: false }>;
#esbuildOptions: BuildOptions & { metafile: true; write: false };
constructor(private workspaceRoot: string, private incremental: boolean, options: BuildOptions) {
this.#esbuildOptions = {
...options,
metafile: true,
write: false,
};
}
/**
* Executes the esbuild build function and normalizes the build result in the event of a
* build failure that results in no output being generated.
* All builds use the `write` option with a value of `false` to allow for the output files
* build result array to be populated.
*
* @returns If output files are generated, the full esbuild BuildResult; if not, the
* warnings and errors for the attempted build.
*/
async bundle(): Promise<
| { errors: Message[]; warnings: Message[] }
| {
errors: undefined;
warnings: Message[];
metafile: Metafile;
outputFiles: OutputFile[];
initialFiles: FileInfo[];
}
> {
let result;
try {
if (this.#esbuildContext) {
// Rebuild using the existing incremental build context
result = await this.#esbuildContext.rebuild();
} else if (this.incremental) {
// Create an incremental build context and perform the first build.
// Context creation does not perform a build.
this.#esbuildContext = await context(this.#esbuildOptions);
result = await this.#esbuildContext.rebuild();
} else {
// For non-incremental builds, perform a single build
result = await build(this.#esbuildOptions);
}
} catch (failure) {
// Build failures will throw an exception which contains errors/warnings
if (isEsBuildFailure(failure)) {
return failure;
} else {
throw failure;
}
}
// Return if the build encountered any errors
if (result.errors.length) {
return {
errors: result.errors,
warnings: result.warnings,
};
}
// Find all initial files
const initialFiles: FileInfo[] = [];
for (const outputFile of result.outputFiles) {
// Entries in the metafile are relative to the `absWorkingDir` option which is set to the workspaceRoot
const relativeFilePath = relative(this.workspaceRoot, outputFile.path);
const entryPoint = result.metafile?.outputs[relativeFilePath]?.entryPoint;
outputFile.path = relativeFilePath;
if (entryPoint) {
// The first part of the filename is the name of file (e.g., "polyfills" for "polyfills.7S5G3MDY.js")
const name = basename(outputFile.path).split('.', 1)[0];
// Only entrypoints with an entry in the options are initial files.
// Dynamic imports also have an entryPoint value in the meta file.
if ((this.#esbuildOptions.entryPoints as Record<string, string>)?.[name]) {
// An entryPoint value indicates an initial file
initialFiles.push({
file: outputFile.path,
name,
extension: extname(outputFile.path),
});
}
}
}
// Return the successful build results
return { ...result, initialFiles, errors: undefined };
}
/**
* Disposes incremental build resources present in the context.
*
* @returns A promise that resolves when disposal is complete.
*/
async dispose(): Promise<void> {
try {
return this.#esbuildContext?.dispose();
} finally {
this.#esbuildContext = undefined;
}
}
}
export async function logMessages(
context: BuilderContext,
{ errors, warnings }: { errors?: PartialMessage[]; warnings?: PartialMessage[] },
): Promise<void> {
if (warnings?.length) {
const warningMessages = await formatMessages(warnings, { kind: 'warning', color: true });
context.logger.warn(warningMessages.join('\n'));
}
if (errors?.length) {
const errorMessages = await formatMessages(errors, { kind: 'error', color: true });
context.logger.error(errorMessages.join('\n'));
}
}