Repository navigation
Expand file tree
/
Copy pathangular-compilation_spec.ts
More file actions
509 lines (443 loc) · 18.9 KB
/
Copy pathangular-compilation_spec.ts
File metadata and controls
509 lines (443 loc) · 18.9 KB
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/**
* @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.dev/license
*/
import path from 'node:path';
import ts from 'typescript';
import type { AngularHostOptions } from '../angular-host';
import { CompilerOptionOverrides, transformCompilerOptions } from './compiler-options';
import { TypeScriptCompilation } from './typescript-compilation';
import {
AngularCompilation,
AngularCompilationResult,
DiagnosticModes,
createAngularCompilation,
} from './index';
describe('AngularCompilation', () => {
class CustomTransformCompilation extends AngularCompilation {
override async initialize(): Promise<AngularCompilationResult> {
return {
compilerOptions: { allowJs: false },
referencedFiles: ['/src/main.ts'],
};
}
override async transformFile(filename: string, content: string) {
if (filename.endsWith('.ts')) {
return {
contents: content + '\n// transformed',
watchFiles: ['/src/dep.ts'],
};
}
return null;
}
}
it('allows implementing on-demand transformFile without collectDiagnostics', async () => {
const compilation = new CustomTransformCompilation();
const initResult = await compilation.initialize();
expect(initResult.referencedFiles).toEqual(['/src/main.ts']);
expect(initResult.compilerOptions.allowJs).toBe(false);
const transformResult = await compilation.transformFile?.(
'/src/main.ts',
'console.log("hello");',
);
expect(transformResult).toEqual({
contents: 'console.log("hello");\n// transformed',
watchFiles: ['/src/dep.ts'],
});
const diagnostics = await compilation.diagnoseFiles();
expect(diagnostics).toEqual({});
});
describe('TypeScriptCompilation', () => {
class MockTypeScriptCompilation extends TypeScriptCompilation {
async initialize(): Promise<AngularCompilationResult> {
return { compilerOptions: {}, referencedFiles: [] };
}
protected override *collectDiagnostics(modes: DiagnosticModes): Iterable<ts.Diagnostic> {
if (modes & DiagnosticModes.Option) {
yield {
category: ts.DiagnosticCategory.Error,
code: 1234,
messageText: 'Mock option error',
file: undefined,
start: undefined,
length: undefined,
};
}
if (modes & DiagnosticModes.Semantic) {
yield {
category: ts.DiagnosticCategory.Warning,
code: 5678,
messageText: 'Mock semantic warning',
file: undefined,
start: undefined,
length: undefined,
};
}
}
public getCachedSourceFiles(): Map<string, ts.SourceFile> {
return this.sourceFiles;
}
public async testLoadConfiguration(
tsconfig: string,
overrides?: CompilerOptionOverrides,
buildType?: 'application' | 'library',
) {
return this.loadConfiguration(tsconfig, overrides, buildType);
}
}
it('collects and converts diagnostics categorized by error and warning', async () => {
const compilation = new MockTypeScriptCompilation();
const diagnostics = await compilation.diagnoseFiles(DiagnosticModes.All);
expect(diagnostics.errors?.length).toBe(1);
expect(diagnostics.errors?.[0].text).toContain('Mock option error');
expect(diagnostics.warnings?.length).toBe(1);
expect(diagnostics.warnings?.[0].text).toContain('Mock semantic warning');
});
it('filters diagnostics according to requested DiagnosticModes', async () => {
const compilation = new MockTypeScriptCompilation();
const diagnostics = await compilation.diagnoseFiles(DiagnosticModes.Option);
expect(diagnostics.errors?.length).toBe(1);
expect(diagnostics.errors?.[0].text).toContain('Mock option error');
expect(diagnostics.warnings).toBeUndefined();
});
it('returns empty diagnostics immediately when mode is DiagnosticModes.None', async () => {
const compilation = new MockTypeScriptCompilation();
const diagnostics = await compilation.diagnoseFiles(DiagnosticModes.None);
expect(diagnostics).toEqual({});
});
it('evicts files from AST cache on update and invalidateFiles', async () => {
const compilation = new MockTypeScriptCompilation();
const mockSourceFile = ts.createSourceFile('test.ts', '', ts.ScriptTarget.Latest);
compilation.getCachedSourceFiles().set('/src/test.ts', mockSourceFile);
expect(compilation.getCachedSourceFiles().has('/src/test.ts')).toBeTrue();
await compilation.update?.(new Set(['/src/test.ts']));
expect(compilation.getCachedSourceFiles().has('/src/test.ts')).toBeFalse();
});
it('dynamically loads the @angular/compiler-cli module', async () => {
const compilerCli = await TypeScriptCompilation.loadCompilerCli();
expect(compilerCli).toBeDefined();
expect(typeof compilerCli.readConfiguration).toBe('function');
});
it('loads configuration and applies compiler option transformations', async () => {
const compilation = new MockTypeScriptCompilation();
const mockReadConfig = jasmine.createSpy('readConfiguration').and.returnValue({
options: { target: ts.ScriptTarget.ES2020 },
rootNames: ['/src/main.ts'],
errors: [],
});
spyOn(TypeScriptCompilation, 'loadCompilerCli').and.resolveTo({
readConfiguration: mockReadConfig,
} as unknown as typeof import('@angular/compiler-cli'));
const result = await compilation.testLoadConfiguration('tsconfig.json', { sourcemap: true });
expect(mockReadConfig).toHaveBeenCalledWith(
'tsconfig.json',
jasmine.objectContaining({
suppressOutputPathCheck: true,
outDir: undefined,
}),
undefined,
jasmine.any(Map),
);
expect(result.rootNames).toEqual(['/src/main.ts']);
expect(result.fallbackRootNames).toBeUndefined();
expect(result.compilerOptions.target).toBe(ts.ScriptTarget.ES2022);
expect(result.compilerOptions.inlineSources).toBe(true);
expect(result.warnings.length).toBeGreaterThan(0);
expect(result.tsConfigFiles).toEqual(['tsconfig.json']);
});
it('filters rootNames to rootFiles while retaining ambient declaration files and setting fallbackRootNames', async () => {
const compilation = new MockTypeScriptCompilation();
const mockReadConfig = jasmine.createSpy('readConfiguration').and.returnValue({
options: { target: ts.ScriptTarget.ES2022 },
rootNames: [
'/src/app/included.spec.ts',
'/src/app/excluded.spec.ts',
'/src/app/app-module.ts',
'/src/env.d.ts',
'/src/types.d.mts',
'/src/legacy.d.cts',
],
errors: [],
});
spyOn(TypeScriptCompilation, 'loadCompilerCli').and.resolveTo({
readConfiguration: mockReadConfig,
} as unknown as typeof import('@angular/compiler-cli'));
const result = await compilation.testLoadConfiguration('tsconfig.spec.json', {
rootFiles: ['/src/app/included.spec.ts'],
});
expect(result.rootNames).toEqual([
'/src/app/included.spec.ts',
'/src/env.d.ts',
'/src/types.d.mts',
'/src/legacy.d.cts',
]);
expect(result.fallbackRootNames).toEqual([
'/src/app/included.spec.ts',
'/src/app/excluded.spec.ts',
'/src/app/app-module.ts',
'/src/env.d.ts',
'/src/types.d.mts',
'/src/legacy.d.cts',
]);
});
it('omits fallbackRootNames when buildType is "library" or when rootFiles covers all tsconfig files', async () => {
const compilation = new MockTypeScriptCompilation();
const mockReadConfig = jasmine.createSpy('readConfiguration').and.returnValue({
options: { target: ts.ScriptTarget.ES2022 },
rootNames: ['/src/public-api.ts', '/src/internal.ts', '/src/env.d.ts'],
errors: [],
});
spyOn(TypeScriptCompilation, 'loadCompilerCli').and.resolveTo({
readConfiguration: mockReadConfig,
} as unknown as typeof import('@angular/compiler-cli'));
const libraryResult = await compilation.testLoadConfiguration(
'tsconfig.lib.json',
{ rootFiles: ['/src/public-api.ts'] },
'library',
);
expect(libraryResult.rootNames).toEqual(['/src/public-api.ts', '/src/env.d.ts']);
expect(libraryResult.fallbackRootNames).toBeUndefined();
const fullSetResult = await compilation.testLoadConfiguration(
'tsconfig.app.json',
{ rootFiles: ['/src/public-api.ts', '/src/internal.ts'] },
'application',
);
expect(fullSetResult.rootNames).toEqual([
'/src/public-api.ts',
'/src/internal.ts',
'/src/env.d.ts',
]);
expect(fullSetResult.fallbackRootNames).toBeUndefined();
});
it('passes extendedConfigCache to readConfiguration and invalidates entries on config change', async () => {
const compilation = new MockTypeScriptCompilation();
let passedCache: Map<string, ts.ExtendedConfigCacheEntry> | undefined;
const mockReadConfig = jasmine
.createSpy('readConfiguration')
.and.callFake((_project, _options, _host, extendedConfigCache) => {
passedCache = extendedConfigCache;
extendedConfigCache?.set(
'/path/to/tsconfig.base.json',
{} as ts.ExtendedConfigCacheEntry,
);
return {
options: { target: ts.ScriptTarget.ES2020 },
rootNames: ['/src/main.ts'],
errors: [],
};
});
spyOn(TypeScriptCompilation, 'loadCompilerCli').and.resolveTo({
readConfiguration: mockReadConfig,
} as unknown as typeof import('@angular/compiler-cli'));
const result1 = await compilation.testLoadConfiguration('tsconfig.json');
expect(mockReadConfig).toHaveBeenCalledTimes(1);
expect(passedCache).toBeDefined();
expect(passedCache?.has('/path/to/tsconfig.base.json')).toBeTrue();
expect(result1.tsConfigFiles).toEqual(['tsconfig.json', '/path/to/tsconfig.base.json']);
// Invalidation of non-config file should keep extended config cache intact
await compilation.update?.(new Set(['/src/main.ts']));
expect(passedCache?.has('/path/to/tsconfig.base.json')).toBeTrue();
// Invalidation of extended tsconfig file should remove it from cache
await compilation.update?.(new Set(['/path/to/tsconfig.base.json']));
expect(passedCache?.has('/path/to/tsconfig.base.json')).toBeFalse();
// Invalidation with different casing should also remove it from cache
passedCache?.set('/path/to/tsconfig.base.json', {} as ts.ExtendedConfigCacheEntry);
await compilation.update?.(new Set(['/PATH/TO/TSCONFIG.BASE.JSON']));
expect(passedCache?.has('/path/to/tsconfig.base.json')).toBeFalse();
// Subsequent configuration load re-uses the same cache instance
await compilation.testLoadConfiguration('tsconfig.json');
expect(mockReadConfig).toHaveBeenCalledTimes(2);
expect(mockReadConfig.calls.argsFor(1)[3]).toBe(passedCache);
});
});
describe('createAngularCompilation', () => {
it('creates JitCompilation when mode is "jit"', async () => {
const compilation = await createAngularCompilation('jit', true, false);
expect(compilation.constructor.name).toBe('JitCompilation');
});
it('creates AotCompilation when mode is "aot"', async () => {
const compilation = await createAngularCompilation('aot', true, false);
expect(compilation.constructor.name).toBe('AotCompilation');
});
it('creates JitCompilation when mode is boolean true (legacy)', async () => {
const compilation = await createAngularCompilation(true, true, false);
expect(compilation.constructor.name).toBe('JitCompilation');
});
it('creates AotCompilation when mode is boolean false (legacy)', async () => {
const compilation = await createAngularCompilation(false, true, false);
expect(compilation.constructor.name).toBe('AotCompilation');
});
it('throws when mode is "transform"', async () => {
await expectAsync(createAngularCompilation('transform', true, false)).toBeRejectedWithError(
'Transform compilation mode is not supported.',
);
});
});
describe('transformCompilerOptions', () => {
it('does not mutate the input compiler options object', () => {
const originalOptions: ts.CompilerOptions = {
target: ts.ScriptTarget.ES2020,
module: ts.ModuleKind.CommonJS,
};
const originalCopy = { ...originalOptions };
transformCompilerOptions(ts, originalOptions);
expect(originalOptions).toEqual(originalCopy);
});
it('sets target to ES2022 and useDefineForClassFields to false when target is undefined', () => {
const { compilerOptions, warnings } = transformCompilerOptions(
ts,
{ module: ts.ModuleKind.ES2022 },
undefined,
'tsconfig.json',
);
expect(compilerOptions.target).toBe(ts.ScriptTarget.ES2022);
expect(compilerOptions.useDefineForClassFields).toBe(false);
expect(warnings.length).toBe(1);
expect(warnings[0].text).toContain(
"TypeScript compiler options 'target' and 'useDefineForClassFields'",
);
expect(warnings[0].location?.file).toBe('tsconfig.json');
});
it('preserves existing useDefineForClassFields if target < ES2022', () => {
const { compilerOptions, warnings } = transformCompilerOptions(
ts,
{
target: ts.ScriptTarget.ES2020,
useDefineForClassFields: true,
module: ts.ModuleKind.ES2022,
},
undefined,
'tsconfig.json',
);
expect(compilerOptions.target).toBe(ts.ScriptTarget.ES2022);
expect(compilerOptions.useDefineForClassFields).toBe(true);
expect(warnings.length).toBe(1);
});
it('sets compilationMode to full and warns when compilationMode is partial', () => {
const { compilerOptions, warnings } = transformCompilerOptions(ts, {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ES2022,
compilationMode: 'partial',
});
expect(compilerOptions.compilationMode).toBe('full');
expect(warnings.length).toBe(1);
expect(warnings[0].text).toContain('Angular partial compilation mode is not supported');
});
it('configures incremental and tsBuildInfoFile when cachePath is provided', () => {
const { compilerOptions } = transformCompilerOptions(
ts,
{ target: ts.ScriptTarget.ES2022 },
{ cachePath: '/tmp/cache' },
);
expect(compilerOptions.incremental).toBe(true);
expect(compilerOptions.tsBuildInfoFile).toContain('.tsbuildinfo');
});
it('sets incremental to false when cachePath is not provided or incremental is false', () => {
const { compilerOptions: opt1 } = transformCompilerOptions(
ts,
{ target: ts.ScriptTarget.ES2022 },
undefined,
);
expect(opt1.incremental).toBe(false);
const { compilerOptions: opt2 } = transformCompilerOptions(
ts,
{ target: ts.ScriptTarget.ES2022, incremental: false },
{ cachePath: '/tmp/cache' },
);
expect(opt2.incremental).toBe(false);
});
it('sets module to ES2022 and warns when module < ES2015', () => {
const { compilerOptions, warnings } = transformCompilerOptions(ts, {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.CommonJS,
});
expect(compilerOptions.module).toBe(ts.ModuleKind.ES2022);
expect(warnings.length).toBe(1);
expect(warnings[0].text).toContain(
"TypeScript compiler options 'module' values 'CommonJS', 'UMD'",
);
});
it('warns when isolatedModules is enabled with emitDecoratorMetadata', () => {
const { warnings } = transformCompilerOptions(ts, {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ES2022,
isolatedModules: true,
emitDecoratorMetadata: true,
});
expect(warnings.length).toBe(1);
expect(warnings[0].text).toContain(
"TypeScript compiler option 'isolatedModules' may prevent",
);
});
it('synchronizes customConditions when moduleResolution is Bundler or module is Preserve', () => {
const { compilerOptions: bundlerOptions } = transformCompilerOptions(
ts,
{ target: ts.ScriptTarget.ES2022, moduleResolution: ts.ModuleResolutionKind.Bundler },
{ customConditions: ['development'] },
);
expect(bundlerOptions.customConditions).toEqual(['development']);
const { compilerOptions: preserveOptions } = transformCompilerOptions(
ts,
{ target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.Preserve },
{ customConditions: ['development'] },
);
expect(preserveOptions.customConditions).toEqual(['development']);
});
it('applies override options correctly', () => {
const { compilerOptions } = transformCompilerOptions(
ts,
{
target: ts.ScriptTarget.ES2022,
isolatedModules: true,
basePath: '/workspace/projects/app',
},
{
sourcemap: true,
preserveSymlinks: true,
externalRuntimeStyles: true,
enableHmr: true,
instrumentForCoverage: true,
includeTestMetadata: true,
basePath: '/workspace',
},
);
expect(compilerOptions.basePath).toBe('/workspace');
expect(compilerOptions.inlineSources).toBe(true);
expect(compilerOptions.inlineSourceMap).toBe(true);
expect(compilerOptions.preserveSymlinks).toBe(true);
expect(compilerOptions.externalRuntimeStyles).toBe(true);
expect(compilerOptions['_enableHmr']).toBe(true);
expect(compilerOptions['_useTypeScriptTranspilation']).toBe(true);
expect(compilerOptions.supportTestBed).toBe(true);
expect(compilerOptions.supportJitMode).toBe(true);
expect(compilerOptions.noEmitOnError).toBe(false);
expect(compilerOptions.composite).toBe(false);
});
it('enforces library compiler options and skips app-only target warning', () => {
const { compilerOptions, warnings } = transformCompilerOptions(
ts,
{
target: ts.ScriptTarget.ES2020,
noEmit: true,
emitDeclarationOnly: true,
isolatedModules: true,
},
{
cachePath: '/tmp/cache',
},
'tsconfig.lib.json',
'library',
);
expect(compilerOptions.target).toBe(ts.ScriptTarget.ES2022);
expect(compilerOptions.useDefineForClassFields).toBeUndefined();
expect(compilerOptions.noEmit).toBe(false);
expect(compilerOptions.emitDeclarationOnly).toBe(false);
expect(compilerOptions.incremental).toBe(true);
expect(compilerOptions.tsBuildInfoFile).toBe(path.join('/tmp/cache', '.tsbuildinfo'));
expect(warnings).toEqual([]);
});
});
});