-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathcompiler-plugin.ts
415 lines (364 loc) · 14.6 KB
/
compiler-plugin.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
/**
* @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 type { CompilerHost } from '@angular/compiler-cli';
import { transformAsync } from '@babel/core';
import * as assert from 'assert';
import type { OnStartResult, PartialMessage, PartialNote, Plugin, PluginBuild } from 'esbuild';
import { promises as fs } from 'fs';
import * as path from 'path';
import ts from 'typescript';
import angularApplicationPreset from '../../babel/presets/application';
import { requiresLinking } from '../../babel/webpack-loader';
import { loadEsmModule } from '../../utils/load-esm';
import { BundleStylesheetOptions, bundleStylesheetText } from './stylesheets';
interface EmitFileResult {
content?: string;
map?: string;
dependencies: readonly string[];
hash?: Uint8Array;
}
type FileEmitter = (file: string) => Promise<EmitFileResult | undefined>;
/**
* Converts TypeScript Diagnostic related information into an esbuild compatible note object.
* Related information is a subset of a full TypeScript Diagnostic and also used for diagnostic
* notes associated with the main Diagnostic.
* @param diagnostic The TypeScript diagnostic relative information to convert.
* @param host A TypeScript FormatDiagnosticsHost instance to use during conversion.
* @returns An esbuild diagnostic message as a PartialMessage object
*/
function convertTypeScriptDiagnosticInfo(
info: ts.DiagnosticRelatedInformation,
host: ts.FormatDiagnosticsHost,
textPrefix?: string,
): PartialNote {
let text = ts.flattenDiagnosticMessageText(info.messageText, host.getNewLine());
if (textPrefix) {
text = textPrefix + text;
}
const note: PartialNote = { text };
if (info.file) {
note.location = {
file: info.file.fileName,
length: info.length,
};
// Calculate the line/column location and extract the full line text that has the diagnostic
if (info.start) {
const { line, character } = ts.getLineAndCharacterOfPosition(info.file, info.start);
note.location.line = line + 1;
note.location.column = character;
// The start position for the slice is the first character of the error line
const lineStartPosition = ts.getPositionOfLineAndCharacter(info.file, line, 0);
// The end position for the slice is the first character of the next line or the length of
// the entire file if the line is the last line of the file (getPositionOfLineAndCharacter
// will error if a nonexistent line is passed).
const { line: lastLineOfFile } = ts.getLineAndCharacterOfPosition(
info.file,
info.file.text.length - 1,
);
const lineEndPosition =
line < lastLineOfFile
? ts.getPositionOfLineAndCharacter(info.file, line + 1, 0)
: info.file.text.length;
note.location.lineText = info.file.text.slice(lineStartPosition, lineEndPosition).trimEnd();
}
}
return note;
}
/**
* Converts a TypeScript Diagnostic message into an esbuild compatible message object.
* @param diagnostic The TypeScript diagnostic to convert.
* @param host A TypeScript FormatDiagnosticsHost instance to use during conversion.
* @returns An esbuild diagnostic message as a PartialMessage object
*/
function convertTypeScriptDiagnostic(
diagnostic: ts.Diagnostic,
host: ts.FormatDiagnosticsHost,
): PartialMessage {
let codePrefix = 'TS';
let code = `${diagnostic.code}`;
if (diagnostic.source === 'ngtsc') {
codePrefix = 'NG';
// Remove `-99` Angular prefix from diagnostic code
code = code.slice(3);
}
const message: PartialMessage = {
...convertTypeScriptDiagnosticInfo(diagnostic, host, `${codePrefix}${code}: `),
// Store original diagnostic for reference if needed downstream
detail: diagnostic,
};
if (diagnostic.relatedInformation?.length) {
message.notes = diagnostic.relatedInformation.map((info) =>
convertTypeScriptDiagnosticInfo(info, host),
);
}
return message;
}
// This is a non-watch version of the compiler code from `@ngtools/webpack` augmented for esbuild
// eslint-disable-next-line max-lines-per-function
export function createCompilerPlugin(
pluginOptions: { sourcemap: boolean; tsconfig: string; advancedOptimizations?: boolean },
styleOptions: BundleStylesheetOptions,
): Plugin {
return {
name: 'angular-compiler',
// eslint-disable-next-line max-lines-per-function
async setup(build: PluginBuild): Promise<void> {
// This uses a wrapped dynamic import to load `@angular/compiler-cli` which is ESM.
// Once TypeScript provides support for retaining dynamic imports this workaround can be dropped.
const compilerCli = await loadEsmModule<typeof import('@angular/compiler-cli')>(
'@angular/compiler-cli',
);
// Temporary deep import for transformer support
const {
mergeTransformers,
replaceBootstrap,
} = require('@ngtools/webpack/src/ivy/transformation');
// Setup defines based on the values provided by the Angular compiler-cli
build.initialOptions.define ??= {};
for (const [key, value] of Object.entries(compilerCli.GLOBAL_DEFS_FOR_TERSER_WITH_AOT)) {
if (key in build.initialOptions.define) {
// Skip keys that have been manually provided
continue;
}
// esbuild requires values to be a string (actual strings need to be quoted).
// In this case, all provided values are booleans.
build.initialOptions.define[key] = value.toString();
}
// The tsconfig is loaded in setup instead of in start to allow the esbuild target build option to be modified.
// esbuild build options can only be modified in setup prior to starting the build.
const {
options: compilerOptions,
rootNames,
errors: configurationDiagnostics,
} = compilerCli.readConfiguration(pluginOptions.tsconfig, {
enableIvy: true,
noEmitOnError: false,
suppressOutputPathCheck: true,
outDir: undefined,
inlineSources: pluginOptions.sourcemap,
inlineSourceMap: pluginOptions.sourcemap,
sourceMap: false,
mapRoot: undefined,
sourceRoot: undefined,
declaration: false,
declarationMap: false,
allowEmptyCodegenFiles: false,
annotationsAs: 'decorators',
enableResourceInlining: false,
});
// Adjust the esbuild output target based on the tsconfig target
if (
compilerOptions.target === undefined ||
compilerOptions.target <= ts.ScriptTarget.ES2015
) {
build.initialOptions.target = 'es2015';
} else if (compilerOptions.target >= ts.ScriptTarget.ESNext) {
build.initialOptions.target = 'esnext';
} else {
build.initialOptions.target = ts.ScriptTarget[compilerOptions.target].toLowerCase();
}
// The file emitter created during `onStart` that will be used during the build in `onLoad` callbacks for TS files
let fileEmitter: FileEmitter | undefined;
build.onStart(async () => {
const result: OnStartResult = {};
// Create TypeScript compiler host
const host = ts.createIncrementalCompilerHost(compilerOptions);
// Temporarily add a readResource hook to allow for a transformResource hook.
// Once the AOT compiler allows only a transformResource hook this can be removed.
(host as CompilerHost).readResource = function (fileName) {
// Provide same no file found behavior as @ngtools/webpack
return this.readFile(fileName) ?? '';
};
// Add an AOT compiler resource transform hook
(host as CompilerHost).transformResource = async function (data, context) {
// Only style resources are transformed currently
if (context.type !== 'style') {
return null;
}
// The file with the resource content will either be an actual file (resourceFile)
// or the file containing the inline component style text (containingFile).
const file = context.resourceFile ?? context.containingFile;
const { contents, errors, warnings } = await bundleStylesheetText(
data,
{
resolvePath: path.dirname(file),
virtualName: file,
},
styleOptions,
);
(result.errors ??= []).push(...errors);
(result.warnings ??= []).push(...warnings);
return { content: contents };
};
// Create the Angular specific program that contains the Angular compiler
const angularProgram = new compilerCli.NgtscProgram(rootNames, compilerOptions, host);
const angularCompiler = angularProgram.compiler;
const { ignoreForDiagnostics, ignoreForEmit } = angularCompiler;
const typeScriptProgram = angularProgram.getTsProgram();
const builder = ts.createAbstractBuilder(typeScriptProgram, host);
await angularCompiler.analyzeAsync();
function* collectDiagnostics() {
// Collect program level diagnostics
yield* configurationDiagnostics;
yield* angularCompiler.getOptionDiagnostics();
yield* builder.getOptionsDiagnostics();
yield* builder.getGlobalDiagnostics();
// Collect source file specific diagnostics
const OptimizeFor = compilerCli.OptimizeFor;
for (const sourceFile of builder.getSourceFiles()) {
if (ignoreForDiagnostics.has(sourceFile)) {
continue;
}
yield* builder.getSyntacticDiagnostics(sourceFile);
yield* builder.getSemanticDiagnostics(sourceFile);
const angularDiagnostics = angularCompiler.getDiagnosticsForFile(
sourceFile,
OptimizeFor.WholeProgram,
);
yield* angularDiagnostics;
}
}
for (const diagnostic of collectDiagnostics()) {
const message = convertTypeScriptDiagnostic(diagnostic, host);
if (diagnostic.category === ts.DiagnosticCategory.Error) {
(result.errors ??= []).push(message);
} else {
(result.warnings ??= []).push(message);
}
}
fileEmitter = createFileEmitter(
builder,
mergeTransformers(angularCompiler.prepareEmit().transformers, {
before: [replaceBootstrap(() => builder.getProgram().getTypeChecker())],
}),
() => [],
);
return result;
});
build.onLoad(
{ filter: compilerOptions.allowJs ? /\.[cm]?[jt]sx?$/ : /\.[cm]?tsx?$/ },
async (args) => {
assert.ok(fileEmitter, 'Invalid plugin execution order');
const typescriptResult = await fileEmitter(args.path);
if (!typescriptResult) {
// No TS result indicates the file is not part of the TypeScript program.
// If allowJs is enabled and the file is JS then defer to the next load hook.
if (compilerOptions.allowJs && /\.[cm]?js$/.test(args.path)) {
return undefined;
}
// Otherwise return an error
return {
errors: [
{
text: 'File is missing from the TypeScript compilation.',
location: { file: args.path },
notes: [
{
text: `Ensure the file is part of the TypeScript program via the 'files' or 'include' property.`,
},
],
},
],
};
}
const data = typescriptResult.content ?? '';
const babelResult = await transformAsync(data, {
filename: args.path,
inputSourceMap: (pluginOptions.sourcemap ? undefined : false) as undefined,
sourceMaps: pluginOptions.sourcemap ? 'inline' : false,
compact: false,
configFile: false,
babelrc: false,
browserslistConfigFile: false,
plugins: [],
presets: [
[
angularApplicationPreset,
{
forceAsyncTransformation: data.includes('async'),
optimize: pluginOptions.advancedOptimizations && {},
},
],
],
});
return {
contents: babelResult?.code ?? '',
loader: 'js',
};
},
);
build.onLoad({ filter: /\.[cm]?js$/ }, async (args) => {
const angularPackage = /[\\/]node_modules[\\/]@angular[\\/]/.test(args.path);
const linkerPluginCreator = (
await loadEsmModule<typeof import('@angular/compiler-cli/linker/babel')>(
'@angular/compiler-cli/linker/babel',
)
).createEs2015LinkerPlugin;
const data = await fs.readFile(args.path, 'utf-8');
const result = await transformAsync(data, {
filename: args.path,
inputSourceMap: (pluginOptions.sourcemap ? undefined : false) as undefined,
sourceMaps: pluginOptions.sourcemap ? 'inline' : false,
compact: false,
configFile: false,
babelrc: false,
browserslistConfigFile: false,
plugins: [],
presets: [
[
angularApplicationPreset,
{
angularLinker: {
shouldLink: await requiresLinking(args.path, data),
jitMode: false,
linkerPluginCreator,
},
forceAsyncTransformation:
!/[\\/][_f]?esm2015[\\/]/.test(args.path) && data.includes('async'),
optimize: pluginOptions.advancedOptimizations && {
looseEnums: angularPackage,
pureTopLevel: angularPackage,
},
},
],
],
});
return {
contents: result?.code ?? data,
loader: 'js',
};
});
},
};
}
function createFileEmitter(
program: ts.BuilderProgram,
transformers: ts.CustomTransformers = {},
onAfterEmit?: (sourceFile: ts.SourceFile) => void,
): FileEmitter {
return async (file: string) => {
const sourceFile = program.getSourceFile(file);
if (!sourceFile) {
return undefined;
}
let content: string | undefined;
program.emit(
sourceFile,
(filename, data) => {
if (/\.[cm]?js$/.test(filename)) {
content = data;
}
},
undefined /* cancellationToken */,
undefined /* emitOnlyDtsFiles */,
transformers,
);
onAfterEmit?.(sourceFile);
return { content, dependencies: [] };
};
}