diff --git a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/dep.ts b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/dep.ts index 4cc1c02b7d..2e3c21564b 100644 --- a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/dep.ts +++ b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/dep.ts @@ -20,7 +20,9 @@ export class NormalService { }) export class AppComponent { found: boolean; - constructor(service: ShakeableService) { this.found = !!service.normal; } + constructor(service: ShakeableService) { + this.found = !!service.normal; + } } @NgModule({ diff --git a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/hierarchy.ts b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/hierarchy.ts index 86daf88798..2465c74ad0 100644 --- a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/hierarchy.ts +++ b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/hierarchy.ts @@ -29,7 +29,9 @@ export class AppComponent { export class ChildComponent { found: boolean; - constructor(@Optional() @Self() service: Service|null) { this.found = !!service; } + constructor(@Optional() @Self() service: Service|null) { + this.found = !!service; + } } @NgModule({ diff --git a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/self.ts b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/self.ts index fb37c76e40..324b059315 100644 --- a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/self.ts +++ b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/self.ts @@ -21,7 +21,9 @@ export class NormalService { }) export class AppComponent { found: boolean; - constructor(service: NormalService) { this.found = !!service.shakeable; } + constructor(service: NormalService) { + this.found = !!service.shakeable; + } } @NgModule({ diff --git a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/string.ts b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/string.ts index fca98267bd..3187a87e9b 100644 --- a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/string.ts +++ b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/string.ts @@ -17,7 +17,9 @@ import {ServerModule} from '@angular/platform-server'; }) export class AppComponent { data: string; - constructor(service: Service) { this.data = service.data; } + constructor(service: Service) { + this.data = service.data; + } } @NgModule({ diff --git a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/token.ts b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/token.ts index 3b93c3e5d8..e3ca53e5d4 100644 --- a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/token.ts +++ b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/token.ts @@ -6,11 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import {Component, Inject, Injectable, InjectionToken, NgModule, forwardRef, inject} from '@angular/core'; +import {Component, forwardRef, Inject, inject, Injectable, InjectionToken, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {ServerModule} from '@angular/platform-server'; -export interface IService { readonly dep: {readonly data: string;}; } +export interface IService { + readonly dep: {readonly data: string;}; +} @NgModule({}) export class TokenModule { @@ -28,7 +30,9 @@ export const TOKEN = new InjectionToken('test', { }) export class AppComponent { data: string; - constructor(@Inject(TOKEN) service: IService) { this.data = service.dep.data; } + constructor(@Inject(TOKEN) service: IService) { + this.data = service.dep.data; + } } @NgModule({ diff --git a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/test/app_spec.ts b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/test/app_spec.ts index 793a27c4d6..5311662b10 100644 --- a/packages/compiler-cli/integrationtest/bazel/injectable_def/app/test/app_spec.ts +++ b/packages/compiler-cli/integrationtest/bazel/injectable_def/app/test/app_spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Component, INJECTOR, Injectable, NgModule} from '@angular/core'; +import {Component, Injectable, INJECTOR, NgModule} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {renderModuleFactory} from '@angular/platform-server'; import {BasicAppModuleNgFactory} from 'app_built/src/basic.ngfactory'; @@ -104,7 +104,6 @@ describe('ngInjectableDef Bazel Integration', () => { }); it('allows provider override in JIT for module-scoped @Injectables', () => { - @NgModule() class Module { } @@ -172,7 +171,9 @@ describe('ngInjectableDef Bazel Integration', () => { // ChildServices exteds ParentService but does not have @Injectable class ChildService extends ParentService { - constructor(value: string) { super(value); } + constructor(value: string) { + super(value); + } static ngInjectableDef = { providedIn: 'root', factory: () => new ChildService('child'), diff --git a/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/test/module_spec.ts b/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/test/module_spec.ts index 2ff1d1364d..ea3f99aaca 100644 --- a/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/test/module_spec.ts +++ b/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/test/module_spec.ts @@ -6,17 +6,23 @@ * found in the LICENSE file at https://angular.io/license */ -import {Injectable, InjectionToken, Injector, NgModule, forwardRef, ɵcreateInjector as createInjector} from '@angular/core'; +import {forwardRef, Injectable, InjectionToken, Injector, NgModule, ɵcreateInjector as createInjector} from '@angular/core'; import {AOT_TOKEN, AotModule, AotService} from 'app_built/src/module'; describe('Ivy NgModule', () => { describe('AOT', () => { let injector: Injector; - beforeEach(() => { injector = createInjector(AotModule); }); - it('works', () => { expect(injector.get(AotService) instanceof AotService).toBeTruthy(); }); + beforeEach(() => { + injector = createInjector(AotModule); + }); + it('works', () => { + expect(injector.get(AotService) instanceof AotService).toBeTruthy(); + }); - it('merges imports and exports', () => { expect(injector.get(AOT_TOKEN)).toEqual('exports'); }); + it('merges imports and exports', () => { + expect(injector.get(AOT_TOKEN)).toEqual('exports'); + }); }); @@ -38,7 +44,9 @@ describe('Ivy NgModule', () => { class JitAppModule { } - it('works', () => { createInjector(JitAppModule); }); + it('works', () => { + createInjector(JitAppModule); + }); it('throws an error on circular module dependencies', () => { @NgModule({ diff --git a/packages/compiler-cli/integrationtest/ngtools_src/feature/lazy-feature.module.ts b/packages/compiler-cli/integrationtest/ngtools_src/feature/lazy-feature.module.ts index 64e9bc4488..b57ecc46e5 100644 --- a/packages/compiler-cli/integrationtest/ngtools_src/feature/lazy-feature.module.ts +++ b/packages/compiler-cli/integrationtest/ngtools_src/feature/lazy-feature.module.ts @@ -16,10 +16,8 @@ export class LazyFeatureComponent { @NgModule({ imports: [RouterModule.forChild([ {path: '', component: LazyFeatureComponent, pathMatch: 'full'}, - {path: 'feature', loadChildren: './feature.module#FeatureModule'}, { - path: 'nested-feature', - loadChildren: './lazy-feature-nested.module#LazyFeatureNestedModule' - } + {path: 'feature', loadChildren: './feature.module#FeatureModule'}, + {path: 'nested-feature', loadChildren: './lazy-feature-nested.module#LazyFeatureNestedModule'} ])], declarations: [LazyFeatureComponent] }) diff --git a/packages/compiler-cli/integrationtest/src/animate.ts b/packages/compiler-cli/integrationtest/src/animate.ts index 0c746888bd..3b187e9130 100644 --- a/packages/compiler-cli/integrationtest/src/animate.ts +++ b/packages/compiler-cli/integrationtest/src/animate.ts @@ -5,7 +5,7 @@ * 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 {AUTO_STYLE, animate, state, style, transition, trigger} from '@angular/animations'; +import {animate, AUTO_STYLE, state, style, transition, trigger} from '@angular/animations'; import {Component} from '@angular/core'; @Component({ @@ -30,8 +30,16 @@ import {Component} from '@angular/core'; }) export class AnimateCmp { stateExpression: string; - constructor() { this.setAsClosed(); } - setAsSomethingElse() { this.stateExpression = 'something'; } - setAsOpen() { this.stateExpression = 'open'; } - setAsClosed() { this.stateExpression = 'closed'; } + constructor() { + this.setAsClosed(); + } + setAsSomethingElse() { + this.stateExpression = 'something'; + } + setAsOpen() { + this.stateExpression = 'open'; + } + setAsClosed() { + this.stateExpression = 'closed'; + } } diff --git a/packages/compiler-cli/integrationtest/src/custom_token.ts b/packages/compiler-cli/integrationtest/src/custom_token.ts index 698b4dd5fe..4db05e4232 100644 --- a/packages/compiler-cli/integrationtest/src/custom_token.ts +++ b/packages/compiler-cli/integrationtest/src/custom_token.ts @@ -8,6 +8,8 @@ import {InjectionToken} from '@angular/core'; -export interface Named { name: string; } +export interface Named { + name: string; +} export const CUSTOM = new InjectionToken('CUSTOM'); diff --git a/packages/compiler-cli/integrationtest/src/errors.ts b/packages/compiler-cli/integrationtest/src/errors.ts index fc25afe56e..0165521d8c 100644 --- a/packages/compiler-cli/integrationtest/src/errors.ts +++ b/packages/compiler-cli/integrationtest/src/errors.ts @@ -10,5 +10,7 @@ import {Component} from '@angular/core'; @Component({selector: 'comp-with-error', templateUrl: 'errors.html'}) export class BindingErrorComp { - createError() { throw new Error('Test'); } + createError() { + throw new Error('Test'); + } } diff --git a/packages/compiler-cli/integrationtest/src/features.ts b/packages/compiler-cli/integrationtest/src/features.ts index 756cbd0b79..47cde6908b 100644 --- a/packages/compiler-cli/integrationtest/src/features.ts +++ b/packages/compiler-cli/integrationtest/src/features.ts @@ -7,7 +7,7 @@ */ import * as common from '@angular/common'; -import {CUSTOM_ELEMENTS_SCHEMA, Component, Directive, EventEmitter, Inject, InjectionToken, NgModule, Output, forwardRef} from '@angular/core'; +import {Component, CUSTOM_ELEMENTS_SCHEMA, Directive, EventEmitter, forwardRef, Inject, InjectionToken, NgModule, Output} from '@angular/core'; import {Observable} from 'rxjs'; import {wrapInArray} from './funcs'; @@ -62,7 +62,9 @@ export class CompUsingCustomElements { }) export class CompConsumingEvents { handleDomEventVoid(e: any): void {} - handleDomEventPreventDefault(e: any): boolean { return false; } + handleDomEventPreventDefault(e: any): boolean { + return false; + } handleDirEvent(e: any): void {} } @@ -70,8 +72,7 @@ export class CompConsumingEvents { selector: '[dirEvent]', }) export class DirPublishingEvents { - @Output('dirEvent') - dirEvent: Observable = new EventEmitter(); + @Output('dirEvent') dirEvent: Observable = new EventEmitter(); } @NgModule({schemas: [CUSTOM_ELEMENTS_SCHEMA], declarations: wrapInArray(CompUsingCustomElements)}) diff --git a/packages/compiler-cli/integrationtest/src/jit_summaries.ts b/packages/compiler-cli/integrationtest/src/jit_summaries.ts index 8d2bccf698..9221608aa1 100644 --- a/packages/compiler-cli/integrationtest/src/jit_summaries.ts +++ b/packages/compiler-cli/integrationtest/src/jit_summaries.ts @@ -11,7 +11,7 @@ import {Component, Directive, Injectable, NgModule, Pipe} from '@angular/core'; const instances = new Map(); export function expectInstanceCreated(type: any) { - const instance = instances.get(type) !; + const instance = instances.get(type)!; expect(instance).toBeDefined(); expect(instance.dep instanceof SomeDep).toBe(true); } @@ -19,7 +19,9 @@ export function expectInstanceCreated(type: any) { export class SomeDep {} export class Base { - constructor(public dep: SomeDep) { instances.set(Object.getPrototypeOf(this).constructor, this); } + constructor(public dep: SomeDep) { + instances.set(Object.getPrototypeOf(this).constructor, this); + } } @Component({templateUrl: './jit_summaries.html'}) @@ -36,7 +38,9 @@ export class SomeDirective extends Base { @Pipe({name: 'somePipe'}) export class SomePipe extends Base { - transform(value: any) { return value; } + transform(value: any) { + return value; + } } @Injectable() diff --git a/packages/compiler-cli/integrationtest/src/module.ts b/packages/compiler-cli/integrationtest/src/module.ts index a3d8711a93..ead5e36920 100644 --- a/packages/compiler-cli/integrationtest/src/module.ts +++ b/packages/compiler-cli/integrationtest/src/module.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {ApplicationRef, NgModule, forwardRef} from '@angular/core'; +import {ApplicationRef, forwardRef, NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {ServerModule} from '@angular/platform-server'; import {FlatModule} from 'flat_module'; diff --git a/packages/compiler-cli/integrationtest/src/module_fixtures.ts b/packages/compiler-cli/integrationtest/src/module_fixtures.ts index 18fe662ac1..0fd71d8c69 100644 --- a/packages/compiler-cli/integrationtest/src/module_fixtures.ts +++ b/packages/compiler-cli/integrationtest/src/module_fixtures.ts @@ -19,24 +19,26 @@ export class ServiceUsingLibModule { @Directive({selector: '[someDir]', host: {'[title]': 'someDir'}}) export class SomeDirectiveInRootModule { - @Input() - someDir: string; + @Input() someDir: string; } @Directive({selector: '[someDir]', host: {'[title]': 'someDir'}}) export class SomeDirectiveInLibModule { - @Input() - someDir: string; + @Input() someDir: string; } @Pipe({name: 'somePipe'}) export class SomePipeInRootModule { - transform(value: string): any { return `transformed ${value}`; } + transform(value: string): any { + return `transformed ${value}`; + } } @Pipe({name: 'somePipe'}) export class SomePipeInLibModule { - transform(value: string): any { return `transformed ${value}`; } + transform(value: string): any { + return `transformed ${value}`; + } } @Component({selector: 'comp', template: `
`}) @@ -66,8 +68,8 @@ export class SomeLibModule { return { ngModule: SomeLibModule, providers: [ - ServiceUsingLibModule, provideValueWithEntryComponents( - [{a: 'b', component: CompUsingLibModuleDirectiveAndPipe}]) + ServiceUsingLibModule, + provideValueWithEntryComponents([{a: 'b', component: CompUsingLibModuleDirectiveAndPipe}]) ] }; } diff --git a/packages/compiler-cli/integrationtest/test/jit_summaries_spec.ts b/packages/compiler-cli/integrationtest/test/jit_summaries_spec.ts index e68db802e2..66ee77a3ca 100644 --- a/packages/compiler-cli/integrationtest/test/jit_summaries_spec.ts +++ b/packages/compiler-cli/integrationtest/test/jit_summaries_spec.ts @@ -8,9 +8,9 @@ import {Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; -import {ServerTestingModule, platformServerTesting} from '@angular/platform-server/testing'; +import {platformServerTesting, ServerTestingModule} from '@angular/platform-server/testing'; -import {SomeDep, SomeDirective, SomeModule, SomePipe, SomePrivateComponent, SomeService, expectInstanceCreated} from '../src/jit_summaries'; +import {expectInstanceCreated, SomeDep, SomeDirective, SomeModule, SomePipe, SomePrivateComponent, SomeService} from '../src/jit_summaries'; import {SomeModuleNgSummary} from '../src/jit_summaries.ngsummary'; describe('Jit Summaries', () => { @@ -18,7 +18,9 @@ describe('Jit Summaries', () => { TestBed.initTestEnvironment(ServerTestingModule, platformServerTesting(), SomeModuleNgSummary); }); - afterEach(() => { TestBed.resetTestEnvironment(); }); + afterEach(() => { + TestBed.resetTestEnvironment(); + }); it('should use directive metadata from summaries', () => { @Component({template: '
'}) diff --git a/packages/compiler-cli/integrationtest/test/ng_module_spec.ts b/packages/compiler-cli/integrationtest/test/ng_module_spec.ts index 4e58a8f4ea..151c64211c 100644 --- a/packages/compiler-cli/integrationtest/test/ng_module_spec.ts +++ b/packages/compiler-cli/integrationtest/test/ng_module_spec.ts @@ -10,7 +10,7 @@ import './init'; import {ComponentUsingThirdParty} from '../src/comp_using_3rdp'; import {ComponentUsingFlatModule} from '../src/comp_using_flat_module'; import {MainModule} from '../src/module'; -import {CompUsingLibModuleDirectiveAndPipe, CompUsingRootModuleDirectiveAndPipe, SOME_TOKEN, ServiceUsingLibModule, SomeLibModule, SomeService} from '../src/module_fixtures'; +import {CompUsingLibModuleDirectiveAndPipe, CompUsingRootModuleDirectiveAndPipe, ServiceUsingLibModule, SOME_TOKEN, SomeLibModule, SomeService} from '../src/module_fixtures'; import {createComponent, createModule} from './util'; diff --git a/packages/compiler-cli/integrationtest/test/query_spec.ts b/packages/compiler-cli/integrationtest/test/query_spec.ts index 1d66f58c89..a97c91f142 100644 --- a/packages/compiler-cli/integrationtest/test/query_spec.ts +++ b/packages/compiler-cli/integrationtest/test/query_spec.ts @@ -19,7 +19,6 @@ describe('child queries', () => { debugElement.query(By.directive(CompWithChildQuery)); expect(childQueryCompFixture.componentInstance.child).toBeDefined(); expect(childQueryCompFixture.componentInstance.child instanceof CompForChildQuery).toBe(true); - }); it('should support compiling children queries', () => { diff --git a/packages/compiler-cli/integrationtest/test/source_map_spec.ts b/packages/compiler-cli/integrationtest/test/source_map_spec.ts index 25b4dd7b1b..2b4ad43979 100644 --- a/packages/compiler-cli/integrationtest/test/source_map_spec.ts +++ b/packages/compiler-cli/integrationtest/test/source_map_spec.ts @@ -31,7 +31,7 @@ function getSourcePositionForStack(stack: string): {source: string, line: number const htmlLocations = stack .split('\n') // e.g. at View_MyComp_0 (...html:153:40) - .map(line => /\((.*\.html):(\d+):(\d+)/.exec(line) !) + .map(line => /\((.*\.html):(\d+):(\d+)/.exec(line)!) .filter(match => !!match) .map(match => ({ source: match[1], diff --git a/packages/compiler-cli/integrationtest/test/test_ngtools_api.ts b/packages/compiler-cli/integrationtest/test/test_ngtools_api.ts index f98bb42051..bff1e6cbc7 100644 --- a/packages/compiler-cli/integrationtest/test/test_ngtools_api.ts +++ b/packages/compiler-cli/integrationtest/test/test_ngtools_api.ts @@ -22,10 +22,15 @@ import {createProgram, readConfiguration} from '@angular/compiler-cli'; * properly read and wrote. */ function main() { - Promise.resolve().then(() => lazyRoutesTest()).then(() => { process.exit(0); }).catch((err) => { - console.error(err.stack); - process.exit(1); - }); + Promise.resolve() + .then(() => lazyRoutesTest()) + .then(() => { + process.exit(0); + }) + .catch((err) => { + console.error(err.stack); + process.exit(1); + }); } function lazyRoutesTest() { @@ -36,7 +41,8 @@ function lazyRoutesTest() { const host = ts.createCompilerHost(config.options, true); const program = createProgram({ rootNames: config.rootNames, - options: config.options, host, + options: config.options, + host, }); config.options.basePath = basePath; diff --git a/packages/compiler-cli/integrationtest/test/util.ts b/packages/compiler-cli/integrationtest/test/util.ts index 0fe1ae64d1..05f6943f86 100644 --- a/packages/compiler-cli/integrationtest/test/util.ts +++ b/packages/compiler-cli/integrationtest/test/util.ts @@ -13,7 +13,7 @@ import {platformServerTesting} from '@angular/platform-server/testing'; import {MainModule} from '../src/module'; import {MainModuleNgFactory} from '../src/module.ngfactory'; -let mainModuleRef: NgModuleRef = null !; +let mainModuleRef: NgModuleRef = null!; beforeEach((done) => { platformServerTesting().bootstrapModuleFactory(MainModuleNgFactory).then((moduleRef: any) => { mainModuleRef = moduleRef; diff --git a/packages/compiler-cli/src/diagnostics/translate_diagnostics.ts b/packages/compiler-cli/src/diagnostics/translate_diagnostics.ts index 46d98c2177..d44d1f8852 100644 --- a/packages/compiler-cli/src/diagnostics/translate_diagnostics.ts +++ b/packages/compiler-cli/src/diagnostics/translate_diagnostics.ts @@ -35,7 +35,8 @@ export function translateDiagnostics( const fileName = span.start.file.url; ng.push({ messageText: diagnosticMessageToString(diagnostic.messageText), - category: diagnostic.category, span, + category: diagnostic.category, + span, source: SOURCE, code: DEFAULT_ERROR_CODE }); @@ -53,6 +54,6 @@ function sourceSpanOf(host: TypeCheckHost, source: ts.SourceFile, start: number) return host.parseSourceSpanOf(source.fileName, line, character); } -function diagnosticMessageToString(message: ts.DiagnosticMessageChain | string): string { +function diagnosticMessageToString(message: ts.DiagnosticMessageChain|string): string { return ts.flattenDiagnosticMessageText(message, '\n'); } diff --git a/packages/compiler-cli/src/language_services.ts b/packages/compiler-cli/src/language_services.ts index a59c053dc0..3a75c881da 100644 --- a/packages/compiler-cli/src/language_services.ts +++ b/packages/compiler-cli/src/language_services.ts @@ -16,4 +16,4 @@ to the language service. */ export {MetadataCollector, ModuleMetadata} from './metadata'; export {CompilerOptions} from './transformers/api'; -export {MetadataReaderCache, MetadataReaderHost, createMetadataReaderCache, readMetadata} from './transformers/metadata_reader'; +export {createMetadataReaderCache, MetadataReaderCache, MetadataReaderHost, readMetadata} from './transformers/metadata_reader'; diff --git a/packages/compiler-cli/src/main.ts b/packages/compiler-cli/src/main.ts index 88b2fc37b5..c57f62fbd0 100644 --- a/packages/compiler-cli/src/main.ts +++ b/packages/compiler-cli/src/main.ts @@ -24,9 +24,9 @@ import {NodeJSFileSystem, setFileSystem} from './ngtsc/file_system'; export function main( args: string[], consoleError: (s: string) => void = console.error, config?: NgcParsedConfiguration, customTransformers?: api.CustomTransformers, programReuse?: { - program: api.Program | undefined, + program: api.Program|undefined, }, - modifiedResourceFiles?: Set| null): number { + modifiedResourceFiles?: Set|null): number { let {project, rootNames, options, errors: configErrors, watch, emitFlags} = config || readNgcCommandLineAndConfiguration(args); if (configErrors.length) { @@ -47,7 +47,9 @@ export function main( options, emitFlags, oldProgram, - emitCallback: createEmitCallback(options), customTransformers, modifiedResourceFiles + emitCallback: createEmitCallback(options), + customTransformers, + modifiedResourceFiles }); if (programReuse !== undefined) { programReuse.program = program; @@ -57,8 +59,8 @@ export function main( export function mainDiagnosticsForTest( args: string[], config?: NgcParsedConfiguration, - programReuse?: {program: api.Program | undefined}, - modifiedResourceFiles?: Set| null): ReadonlyArray { + programReuse?: {program: api.Program|undefined}, + modifiedResourceFiles?: Set|null): ReadonlyArray { let {project, rootNames, options, errors: configErrors, watch, emitFlags} = config || readNgcCommandLineAndConfiguration(args); if (configErrors.length) { @@ -100,9 +102,10 @@ function createEmitCallback(options: api.CompilerOptions): api.TsEmitCallback|un options.emitDecoratorMetadata = true; } const tsickleHost: Pick< - tsickle.TsickleHost, 'shouldSkipTsickleProcessing'|'pathToModuleName'| - 'shouldIgnoreWarningsForPath'|'fileNameToModuleId'|'googmodule'|'untyped'| - 'convertIndexImportShorthand'|'transformDecorators'|'transformTypesToClosure'> = { + tsickle.TsickleHost, + 'shouldSkipTsickleProcessing'|'pathToModuleName'|'shouldIgnoreWarningsForPath'| + 'fileNameToModuleId'|'googmodule'|'untyped'|'convertIndexImportShorthand'| + 'transformDecorators'|'transformTypesToClosure'> = { shouldSkipTsickleProcessing: (fileName) => /\.d\.ts$/.test(fileName) || // View Engine's generated files were never intended to be processed with tsickle. (!options.enableIvy && GENERATED_FILES.test(fileName)), @@ -111,7 +114,9 @@ function createEmitCallback(options: api.CompilerOptions): api.TsEmitCallback|un fileNameToModuleId: (fileName) => fileName, googmodule: false, untyped: true, - convertIndexImportShorthand: false, transformDecorators, transformTypesToClosure, + convertIndexImportShorthand: false, + transformDecorators, + transformTypesToClosure, }; if (options.annotateForClosureCompiler || options.annotationsAs === 'static fields') { @@ -147,7 +152,9 @@ function createEmitCallback(options: api.CompilerOptions): api.TsEmitCallback|un } } -export interface NgcParsedConfiguration extends ParsedConfiguration { watch?: boolean; } +export interface NgcParsedConfiguration extends ParsedConfiguration { + watch?: boolean; +} export function readNgcCommandLineAndConfiguration(args: string[]): NgcParsedConfiguration { const options: api.CompilerOptions = {}; @@ -194,7 +201,8 @@ export function readCommandLineAndConfiguration( } return { project, - rootNames: config.rootNames, options, + rootNames: config.rootNames, + options, errors: config.errors, emitFlags: config.emitFlags }; @@ -237,7 +245,7 @@ export function watchMode( function printDiagnostics( diagnostics: ReadonlyArray, - options: api.CompilerOptions | undefined, consoleError: (s: string) => void): void { + options: api.CompilerOptions|undefined, consoleError: (s: string) => void): void { if (diagnostics.length === 0) { return; } diff --git a/packages/compiler-cli/src/metadata/bundle_index_host.ts b/packages/compiler-cli/src/metadata/bundle_index_host.ts index 489c32c4db..74db9c8979 100644 --- a/packages/compiler-cli/src/metadata/bundle_index_host.ts +++ b/packages/compiler-cli/src/metadata/bundle_index_host.ts @@ -47,8 +47,7 @@ function createSyntheticIndexHost( newHost.writeFile = (fileName: string, data: string, writeByteOrderMark: boolean, - onError: ((message: string) => void) | undefined, - sourceFiles: Readonly[]) => { + onError: ((message: string) => void)|undefined, sourceFiles: Readonly[]) => { delegate.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); if (fileName.match(DTS) && sourceFiles && sourceFiles.length == 1 && path.normalize(sourceFiles[0].fileName) === normalSyntheticIndexName) { @@ -103,7 +102,7 @@ export function createBundleIndexHost( // contents of the flat module index. The bundle produced during emit does use the metadata cache // with associated transforms, so the metadata will have lowered expressions, resource inlining, // etc. - const getMetadataBundle = (cache: MetadataCache | null) => { + const getMetadataBundle = (cache: MetadataCache|null) => { const bundler = new MetadataBundler( indexModule, ngOptions.flatModuleId, new CompilerHostAdapter(host, cache, ngOptions), ngOptions.flatModulePrivateSymbolPrefix); @@ -113,7 +112,7 @@ export function createBundleIndexHost( // First, produce the bundle with no MetadataCache. const metadataBundle = getMetadataBundle(/* MetadataCache */ null); const name = - path.join(path.dirname(indexModule), ngOptions.flatModuleOutFile !.replace(JS_EXT, '.ts')); + path.join(path.dirname(indexModule), ngOptions.flatModuleOutFile!.replace(JS_EXT, '.ts')); const libraryIndex = `./${path.basename(indexModule)}`; const content = privateEntriesToIndex(libraryIndex, metadataBundle.privates); diff --git a/packages/compiler-cli/src/metadata/bundler.ts b/packages/compiler-cli/src/metadata/bundler.ts index 5c07de49c0..e1d3ad407e 100644 --- a/packages/compiler-cli/src/metadata/bundler.ts +++ b/packages/compiler-cli/src/metadata/bundler.ts @@ -11,7 +11,7 @@ import * as ts from 'typescript'; import {MetadataCache} from '../transformers/metadata_cache'; import {MetadataCollector} from './collector'; -import {ClassMetadata, ConstructorMetadata, FunctionMetadata, METADATA_VERSION, MemberMetadata, MetadataEntry, MetadataError, MetadataMap, MetadataObject, MetadataSymbolicExpression, MetadataSymbolicReferenceExpression, MetadataValue, MethodMetadata, ModuleExportMetadata, ModuleMetadata, isClassMetadata, isConstructorMetadata, isFunctionMetadata, isInterfaceMetadata, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportedSymbolReferenceExpression, isMetadataModuleReferenceExpression, isMetadataSymbolicCallExpression, isMetadataSymbolicExpression, isMethodMetadata} from './schema'; +import {ClassMetadata, ConstructorMetadata, FunctionMetadata, isClassMetadata, isConstructorMetadata, isFunctionMetadata, isInterfaceMetadata, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportedSymbolReferenceExpression, isMetadataModuleReferenceExpression, isMetadataSymbolicCallExpression, isMetadataSymbolicExpression, isMethodMetadata, MemberMetadata, METADATA_VERSION, MetadataEntry, MetadataError, MetadataMap, MetadataObject, MetadataSymbolicExpression, MetadataSymbolicReferenceExpression, MetadataValue, MethodMetadata, ModuleExportMetadata, ModuleMetadata} from './schema'; @@ -59,7 +59,9 @@ interface Symbol { privateName?: string; } -export interface BundleEntries { [name: string]: MetadataEntry; } +export interface BundleEntries { + [name: string]: MetadataEntry; +} export interface BundlePrivateEntry { privateName: string; @@ -77,7 +79,7 @@ export interface MetadataBundlerHost { } type StaticsMetadata = { - [name: string]: MetadataValue | FunctionMetadata; + [name: string]: MetadataValue|FunctionMetadata; }; export class MetadataBundler { @@ -87,7 +89,7 @@ export class MetadataBundler { private rootModule: string; private privateSymbolPrefix: string; // TODO(issue/24571): remove '!'. - private exported !: Set; + private exported!: Set; constructor( private root: string, private importAs: string|undefined, private host: MetadataBundlerHost, @@ -106,14 +108,14 @@ export class MetadataBundler { const privates = Array.from(this.symbolMap.values()) .filter(s => s.referenced && s.isPrivate) .map(s => ({ - privateName: s.privateName !, - name: s.declaration !.name, - module: s.declaration !.module + privateName: s.privateName!, + name: s.declaration!.name, + module: s.declaration!.module })); const origins = Array.from(this.symbolMap.values()) .filter(s => s.referenced && !s.reexport) .reduce<{[name: string]: string}>((p, s) => { - p[s.isPrivate ? s.privateName ! : s.name] = s.declaration !.module; + p[s.isPrivate ? s.privateName! : s.name] = s.declaration!.module; return p; }, {}); const exports = this.getReExports(exportedSymbols); @@ -121,8 +123,10 @@ export class MetadataBundler { metadata: { __symbolic: 'module', version: METADATA_VERSION, - exports: exports.length ? exports : undefined, metadata, origins, - importAs: this.importAs ! + exports: exports.length ? exports : undefined, + metadata, + origins, + importAs: this.importAs! }, privates }; @@ -156,7 +160,7 @@ export class MetadataBundler { const exportSymbol = (exportedSymbol: Symbol, exportAs: string) => { const symbol = this.symbolOf(moduleName, exportAs); - result !.push(symbol); + result!.push(symbol); exportedSymbol.reexportedAs = symbol; symbol.exports = exportedSymbol; }; @@ -276,18 +280,18 @@ export class MetadataBundler { Array.from(this.symbolMap.values()).forEach(symbol => { if (symbol.referenced && !symbol.reexport) { let name = symbol.name; - const identifier = `${symbol.declaration!.module}:${symbol.declaration !.name}`; + const identifier = `${symbol.declaration!.module}:${symbol.declaration!.name}`; if (symbol.isPrivate && !symbol.privateName) { name = newPrivateName(this.privateSymbolPrefix); symbol.privateName = name; } if (symbolsMap.has(identifier)) { const names = symbolsMap.get(identifier); - names !.push(name); + names!.push(name); } else { symbolsMap.set(identifier, [name]); } - result[name] = symbol.value !; + result[name] = symbol.value!; } }); @@ -320,9 +324,9 @@ export class MetadataBundler { for (const symbol of exportedSymbols) { if (symbol.reexport) { // symbol.declaration is guaranteed to be defined during the phase this method is called. - const declaration = symbol.declaration !; + const declaration = symbol.declaration!; const module = declaration.module; - if (declaration !.name == '*') { + if (declaration!.name == '*') { // Reexport all the symbols. exportAlls.add(declaration.module); } else { @@ -346,12 +350,12 @@ export class MetadataBundler { private convertSymbol(symbol: Symbol) { // canonicalSymbol is ensured to be defined before this is called. - const canonicalSymbol = symbol.canonicalSymbol !; + const canonicalSymbol = symbol.canonicalSymbol!; if (!canonicalSymbol.referenced) { canonicalSymbol.referenced = true; // declaration is ensured to be definded before this method is called. - const declaration = canonicalSymbol.declaration !; + const declaration = canonicalSymbol.declaration!; const module = this.getMetadata(declaration.module); if (module) { const value = module.metadata[declaration.name]; @@ -399,11 +403,11 @@ export class MetadataBundler { private convertMember(moduleName: string, member: MemberMetadata) { const result: MemberMetadata = {__symbolic: member.__symbolic}; result.decorators = - member.decorators && member.decorators.map(d => this.convertExpression(moduleName, d) !); + member.decorators && member.decorators.map(d => this.convertExpression(moduleName, d)!); if (isMethodMetadata(member)) { (result as MethodMetadata).parameterDecorators = member.parameterDecorators && member.parameterDecorators.map( - d => d && d.map(p => this.convertExpression(moduleName, p) !)); + d => d && d.map(p => this.convertExpression(moduleName, p)!)); if (isConstructorMetadata(member)) { if (member.parameters) { (result as ConstructorMetadata).parameters = @@ -450,7 +454,7 @@ export class MetadataBundler { return this.convertError(moduleName, value); } if (isMetadataSymbolicExpression(value)) { - return this.convertExpression(moduleName, value) !; + return this.convertExpression(moduleName, value)!; } if (Array.isArray(value)) { return value.map(v => this.convertValue(moduleName, v)); @@ -466,8 +470,8 @@ export class MetadataBundler { } private convertExpression( - moduleName: string, value: MetadataSymbolicExpression|MetadataError|null| - undefined): MetadataSymbolicExpression|MetadataError|undefined|null { + moduleName: string, value: MetadataSymbolicExpression|MetadataError|null|undefined): + MetadataSymbolicExpression|MetadataError|undefined|null { if (value) { switch (value.__symbolic) { case 'error': @@ -487,14 +491,15 @@ export class MetadataBundler { message: value.message, line: value.line, character: value.character, - context: value.context, module + context: value.context, + module }; } private convertReference(moduleName: string, value: MetadataSymbolicReferenceExpression): MetadataSymbolicReferenceExpression|MetadataError|undefined { const createReference = (symbol: Symbol): MetadataSymbolicReferenceExpression => { - const declaration = symbol.declaration !; + const declaration = symbol.declaration!; if (declaration.module.startsWith('.')) { // Reference to a symbol defined in the module. Ensure it is converted then return a // references to the final symbol. @@ -503,11 +508,11 @@ export class MetadataBundler { __symbolic: 'reference', get name() { // Resolved lazily because private names are assigned late. - const canonicalSymbol = symbol.canonicalSymbol !; + const canonicalSymbol = symbol.canonicalSymbol!; if (canonicalSymbol.isPrivate == null) { throw Error('Invalid state: isPrivate was not initialized'); } - return canonicalSymbol.isPrivate ? canonicalSymbol.privateName ! : canonicalSymbol.name; + return canonicalSymbol.isPrivate ? canonicalSymbol.privateName! : canonicalSymbol.name; } }; } else { @@ -584,7 +589,7 @@ export class MetadataBundler { private convertExpressionNode(moduleName: string, value: MetadataSymbolicExpression): MetadataSymbolicExpression { - const result: MetadataSymbolicExpression = { __symbolic: value.__symbolic } as any; + const result: MetadataSymbolicExpression = {__symbolic: value.__symbolic} as any; for (const key in value) { (result as any)[key] = this.convertValue(moduleName, (value as any)[key]); } diff --git a/packages/compiler-cli/src/metadata/collector.ts b/packages/compiler-cli/src/metadata/collector.ts index f54ba3def7..577347181e 100644 --- a/packages/compiler-cli/src/metadata/collector.ts +++ b/packages/compiler-cli/src/metadata/collector.ts @@ -8,8 +8,8 @@ import * as ts from 'typescript'; -import {Evaluator, errorSymbol, recordMapEntry} from './evaluator'; -import {ClassMetadata, ConstructorMetadata, FunctionMetadata, InterfaceMetadata, METADATA_VERSION, MemberMetadata, MetadataEntry, MetadataError, MetadataMap, MetadataSymbolicBinaryExpression, MetadataSymbolicCallExpression, MetadataSymbolicExpression, MetadataSymbolicIfExpression, MetadataSymbolicIndexExpression, MetadataSymbolicPrefixExpression, MetadataSymbolicReferenceExpression, MetadataSymbolicSelectExpression, MetadataSymbolicSpreadExpression, MetadataValue, MethodMetadata, ModuleExportMetadata, ModuleMetadata, isClassMetadata, isConstructorMetadata, isFunctionMetadata, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportDefaultReference, isMetadataImportedSymbolReferenceExpression, isMetadataSymbolicExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSelectExpression, isMethodMetadata} from './schema'; +import {errorSymbol, Evaluator, recordMapEntry} from './evaluator'; +import {ClassMetadata, ConstructorMetadata, FunctionMetadata, InterfaceMetadata, isClassMetadata, isConstructorMetadata, isFunctionMetadata, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportDefaultReference, isMetadataImportedSymbolReferenceExpression, isMetadataSymbolicExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSelectExpression, isMethodMetadata, MemberMetadata, METADATA_VERSION, MetadataEntry, MetadataError, MetadataMap, MetadataSymbolicBinaryExpression, MetadataSymbolicCallExpression, MetadataSymbolicExpression, MetadataSymbolicIfExpression, MetadataSymbolicIndexExpression, MetadataSymbolicPrefixExpression, MetadataSymbolicReferenceExpression, MetadataSymbolicSelectExpression, MetadataSymbolicSpreadExpression, MetadataValue, MethodMetadata, ModuleExportMetadata, ModuleMetadata} from './schema'; import {Symbols} from './symbols'; const isStatic = (node: ts.Declaration) => @@ -60,12 +60,12 @@ export class MetadataCollector { new Map(); const composedSubstituter = substituteExpression && this.options.substituteExpression ? (value: MetadataValue, node: ts.Node) => - this.options.substituteExpression !(substituteExpression(value, node), node) : + this.options.substituteExpression!(substituteExpression(value, node), node) : substituteExpression; const evaluatorOptions = substituteExpression ? {...this.options, substituteExpression: composedSubstituter} : this.options; - let metadata: {[name: string]: MetadataValue | ClassMetadata | FunctionMetadata}|undefined; + let metadata: {[name: string]: MetadataValue|ClassMetadata|FunctionMetadata}|undefined; const evaluator = new Evaluator(locals, nodeMap, evaluatorOptions, (name, value) => { if (!metadata) metadata = {}; metadata[name] = value; @@ -88,9 +88,9 @@ export class MetadataCollector { return errorSymbol(message, node, context, sourceFile); } - function maybeGetSimpleFunction( - functionDeclaration: ts.FunctionDeclaration | - ts.MethodDeclaration): {func: FunctionMetadata, name: string}|undefined { + function maybeGetSimpleFunction(functionDeclaration: ts.FunctionDeclaration| + ts.MethodDeclaration): {func: FunctionMetadata, name: string}| + undefined { if (functionDeclaration.name && functionDeclaration.name.kind == ts.SyntaxKind.Identifier) { const nameNode = functionDeclaration.name; const functionName = nameNode.text; @@ -119,8 +119,8 @@ export class MetadataCollector { function classMetadataOf(classDeclaration: ts.ClassDeclaration): ClassMetadata { const result: ClassMetadata = {__symbolic: 'class'}; - function getDecorators(decorators: ReadonlyArray| undefined): - MetadataSymbolicExpression[]|undefined { + function getDecorators(decorators: ReadonlyArray| + undefined): MetadataSymbolicExpression[]|undefined { if (decorators && decorators.length) return decorators.map(decorator => objFromDecorator(decorator)); return undefined; @@ -167,8 +167,8 @@ export class MetadataCollector { } // static member - let statics: {[name: string]: MetadataValue | FunctionMetadata}|null = null; - function recordStaticMember(name: string, value: MetadataValue | FunctionMetadata) { + let statics: {[name: string]: MetadataValue|FunctionMetadata}|null = null; + function recordStaticMember(name: string, value: MetadataValue|FunctionMetadata) { if (!statics) statics = {}; statics[name] = value; } @@ -189,11 +189,10 @@ export class MetadataCollector { } const methodDecorators = getDecorators(method.decorators); const parameters = method.parameters; - const parameterDecoratorData: - ((MetadataSymbolicExpression | MetadataError)[] | undefined)[] = []; - const parametersData: - (MetadataSymbolicReferenceExpression | MetadataError | - MetadataSymbolicSelectExpression | null)[] = []; + const parameterDecoratorData: ((MetadataSymbolicExpression | MetadataError)[]| + undefined)[] = []; + const parametersData: (MetadataSymbolicReferenceExpression|MetadataError| + MetadataSymbolicSelectExpression|null)[] = []; let hasDecoratorData: boolean = false; let hasParameterData: boolean = false; for (const parameter of parameters) { @@ -282,15 +281,14 @@ export class MetadataCollector { ts.getCombinedModifierFlags(node as ts.Declaration) & ts.ModifierFlags.Export; const isExportedIdentifier = (identifier?: ts.Identifier) => identifier && exportMap.has(identifier.text); - const isExported = - (node: ts.FunctionDeclaration | ts.ClassDeclaration | ts.TypeAliasDeclaration | - ts.InterfaceDeclaration | ts.EnumDeclaration) => - isExport(node) || isExportedIdentifier(node.name); + const isExported = (node: ts.FunctionDeclaration|ts.ClassDeclaration|ts.TypeAliasDeclaration| + ts.InterfaceDeclaration|ts.EnumDeclaration) => + isExport(node) || isExportedIdentifier(node.name); const exportedIdentifierName = (identifier?: ts.Identifier) => identifier && (exportMap.get(identifier.text) || identifier.text); - const exportedName = - (node: ts.FunctionDeclaration | ts.ClassDeclaration | ts.InterfaceDeclaration | - ts.TypeAliasDeclaration | ts.EnumDeclaration) => exportedIdentifierName(node.name); + const exportedName = (node: ts.FunctionDeclaration|ts.ClassDeclaration| + ts.InterfaceDeclaration|ts.TypeAliasDeclaration|ts.EnumDeclaration) => + exportedIdentifierName(node.name); // Pre-declare classes and functions @@ -419,8 +417,8 @@ export class MetadataCollector { if (name) { if (!metadata) metadata = {}; // TODO(alxhub): The literal here is not valid FunctionMetadata. - metadata[name] = maybeFunc ? recordEntry(maybeFunc.func, node) : - ({ __symbolic: 'function' } as any); + metadata[name] = + maybeFunc ? recordEntry(maybeFunc.func, node) : ({__symbolic: 'function'} as any); } } break; @@ -456,7 +454,8 @@ export class MetadataCollector { operator: '+', left: { __symbolic: 'select', - expression: recordEntry({__symbolic: 'reference', name: enumName}, node), name + expression: recordEntry({__symbolic: 'reference', name: enumName}, node), + name }, } as any; } else { @@ -555,7 +554,8 @@ export class MetadataCollector { } const result: ModuleMetadata = { __symbolic: 'module', - version: this.options.version || METADATA_VERSION, metadata + version: this.options.version || METADATA_VERSION, + metadata }; if (sourceFile.moduleName) result.importAs = sourceFile.moduleName; if (exports) result.exports = exports; @@ -570,8 +570,7 @@ function validateMetadata( metadata: {[name: string]: MetadataEntry}) { let locals: Set = new Set(['Array', 'Object', 'Set', 'Map', 'string', 'number', 'any']); - function validateExpression( - expression: MetadataValue | MetadataSymbolicExpression | MetadataError) { + function validateExpression(expression: MetadataValue|MetadataSymbolicExpression|MetadataError) { if (!expression) { return; } else if (Array.isArray(expression)) { @@ -648,11 +647,11 @@ function validateMetadata( } if (classData.members) { Object.getOwnPropertyNames(classData.members) - .forEach(name => classData.members ![name].forEach((m) => validateMember(classData, m))); + .forEach(name => classData.members![name].forEach((m) => validateMember(classData, m))); } if (classData.statics) { Object.getOwnPropertyNames(classData.statics).forEach(name => { - const staticMember = classData.statics ![name]; + const staticMember = classData.statics![name]; if (isFunctionMetadata(staticMember)) { validateExpression(staticMember.value); } else { @@ -675,7 +674,7 @@ function validateMetadata( } } - function shouldReportNode(node: ts.Node | undefined) { + function shouldReportNode(node: ts.Node|undefined) { if (node) { const nodeStart = node.getStart(); return !( @@ -688,12 +687,13 @@ function validateMetadata( function reportError(error: MetadataError) { const node = nodeMap.get(error); if (shouldReportNode(node)) { - const lineInfo = error.line != undefined ? - error.character != undefined ? `:${error.line + 1}:${error.character + 1}` : - `:${error.line + 1}` : - ''; - throw new Error( - `${sourceFile.fileName}${lineInfo}: Metadata collected contains an error that will be reported at runtime: ${expandedMessage(error)}.\n ${JSON.stringify(error)}`); + const lineInfo = error.line != undefined ? error.character != undefined ? + `:${error.line + 1}:${error.character + 1}` : + `:${error.line + 1}` : + ''; + throw new Error(`${sourceFile.fileName}${ + lineInfo}: Metadata collected contains an error that will be reported at runtime: ${ + expandedMessage(error)}.\n ${JSON.stringify(error)}`); } } @@ -708,8 +708,9 @@ function validateMetadata( if (shouldReportNode(node)) { if (node) { const {line, character} = sourceFile.getLineAndCharacterOfPosition(node.getStart()); - throw new Error( - `${sourceFile.fileName}:${line + 1}:${character + 1}: Error encountered in metadata generated for exported symbol '${name}': \n ${e.message}`); + throw new Error(`${sourceFile.fileName}:${line + 1}:${ + character + 1}: Error encountered in metadata generated for exported symbol '${ + name}': \n ${e.message}`); } throw new Error( `Error encountered in metadata generated for exported symbol ${name}: \n ${e.message}`); @@ -722,7 +723,7 @@ function validateMetadata( function namesOf(parameters: ts.NodeArray): string[] { const result: string[] = []; - function addNamesOf(name: ts.Identifier | ts.BindingPattern) { + function addNamesOf(name: ts.Identifier|ts.BindingPattern) { if (name.kind == ts.SyntaxKind.Identifier) { const identifier = name; result.push(identifier.text); @@ -752,7 +753,8 @@ function expandedMessage(error: any): string { switch (error.message) { case 'Reference to non-exported class': if (error.context && error.context.className) { - return `Reference to a non-exported class ${error.context.className}. Consider exporting the class`; + return `Reference to a non-exported class ${ + error.context.className}. Consider exporting the class`; } break; case 'Variable not initialized': @@ -771,7 +773,8 @@ function expandedMessage(error: any): string { 'unction calls are not supported. Consider replacing the function or lambda with a reference to an exported function'; case 'Reference to a local symbol': if (error.context && error.context.name) { - return `Reference to a local (non-exported) symbol '${error.context.name}'. Consider exporting the symbol`; + return `Reference to a local (non-exported) symbol '${ + error.context.name}'. Consider exporting the symbol`; } } return error.message; diff --git a/packages/compiler-cli/src/metadata/evaluator.ts b/packages/compiler-cli/src/metadata/evaluator.ts index 9cf440cc71..4752d98211 100644 --- a/packages/compiler-cli/src/metadata/evaluator.ts +++ b/packages/compiler-cli/src/metadata/evaluator.ts @@ -9,7 +9,7 @@ import * as ts from 'typescript'; import {CollectorOptions} from './collector'; -import {ClassMetadata, FunctionMetadata, InterfaceMetadata, MetadataEntry, MetadataError, MetadataImportedSymbolReferenceExpression, MetadataSourceLocationInfo, MetadataSymbolicCallExpression, MetadataValue, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportDefaultReference, isMetadataImportedSymbolReferenceExpression, isMetadataModuleReferenceExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSpreadExpression} from './schema'; +import {ClassMetadata, FunctionMetadata, InterfaceMetadata, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportDefaultReference, isMetadataImportedSymbolReferenceExpression, isMetadataModuleReferenceExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSpreadExpression, MetadataEntry, MetadataError, MetadataImportedSymbolReferenceExpression, MetadataSourceLocationInfo, MetadataSymbolicCallExpression, MetadataValue} from './schema'; import {Symbols} from './symbols'; @@ -46,8 +46,9 @@ export function recordMapEntry( sourceFile?: ts.SourceFile) { if (!nodeMap.has(entry)) { nodeMap.set(entry, node); - if (node && (isMetadataImportedSymbolReferenceExpression(entry) || - isMetadataImportDefaultReference(entry)) && + if (node && + (isMetadataImportedSymbolReferenceExpression(entry) || + isMetadataImportDefaultReference(entry)) && entry.line == null) { const info = sourceInfo(node, sourceFile); if (info.line != null) entry.line = info.line; @@ -88,7 +89,7 @@ export interface ImportMetadata { } -function getSourceFileOfNode(node: ts.Node | undefined): ts.SourceFile { +function getSourceFileOfNode(node: ts.Node|undefined): ts.SourceFile { while (node && node.kind != ts.SyntaxKind.SourceFile) { node = node.parent; } @@ -97,7 +98,7 @@ function getSourceFileOfNode(node: ts.Node | undefined): ts.SourceFile { /* @internal */ export function sourceInfo( - node: ts.Node | undefined, sourceFile: ts.SourceFile | undefined): MetadataSourceLocationInfo { + node: ts.Node|undefined, sourceFile: ts.SourceFile|undefined): MetadataSourceLocationInfo { if (node) { sourceFile = sourceFile || getSourceFileOfNode(node); if (sourceFile) { @@ -435,7 +436,7 @@ export class Evaluator { case ts.SyntaxKind.TypeReference: const typeReferenceNode = node; const typeNameNode = typeReferenceNode.typeName; - const getReference: (typeNameNode: ts.Identifier | ts.QualifiedName) => MetadataValue = + const getReference: (typeNameNode: ts.Identifier|ts.QualifiedName) => MetadataValue = node => { if (typeNameNode.kind === ts.SyntaxKind.QualifiedName) { const qualifiedName = node; @@ -691,6 +692,6 @@ function isPropertyAssignment(node: ts.Node): node is ts.PropertyAssignment { const empty = ts.createNodeArray(); -function arrayOrEmpty(v: ts.NodeArray| undefined): ts.NodeArray { +function arrayOrEmpty(v: ts.NodeArray|undefined): ts.NodeArray { return v || empty; } \ No newline at end of file diff --git a/packages/compiler-cli/src/metadata/schema.ts b/packages/compiler-cli/src/metadata/schema.ts index ec2ed8ad1c..519a8c1fd6 100644 --- a/packages/compiler-cli/src/metadata/schema.ts +++ b/packages/compiler-cli/src/metadata/schema.ts @@ -18,7 +18,7 @@ export const METADATA_VERSION = 4; -export type MetadataEntry = ClassMetadata | InterfaceMetadata | FunctionMetadata | MetadataValue; +export type MetadataEntry = ClassMetadata|InterfaceMetadata|FunctionMetadata|MetadataValue; export interface ModuleMetadata { __symbolic: 'module'; @@ -43,18 +43,22 @@ export interface ClassMetadata { arity?: number; decorators?: (MetadataSymbolicExpression|MetadataError)[]; members?: MetadataMap; - statics?: {[name: string]: MetadataValue | FunctionMetadata}; + statics?: {[name: string]: MetadataValue|FunctionMetadata}; } export function isClassMetadata(value: any): value is ClassMetadata { return value && value.__symbolic === 'class'; } -export interface InterfaceMetadata { __symbolic: 'interface'; } +export interface InterfaceMetadata { + __symbolic: 'interface'; +} export function isInterfaceMetadata(value: any): value is InterfaceMetadata { return value && value.__symbolic === 'interface'; } -export interface MetadataMap { [name: string]: MemberMetadata[]; } +export interface MetadataMap { + [name: string]: MemberMetadata[]; +} export interface MemberMetadata { __symbolic: 'constructor'|'method'|'property'; @@ -99,24 +103,26 @@ export function isFunctionMetadata(value: any): value is FunctionMetadata { return value && value.__symbolic === 'function'; } -export type MetadataValue = string | number | boolean | undefined | null | MetadataObject | - MetadataArray | MetadataSymbolicExpression | MetadataSymbolicReferenceExpression | - MetadataSymbolicBinaryExpression | MetadataSymbolicIndexExpression | - MetadataSymbolicCallExpression | MetadataSymbolicPrefixExpression | - MetadataSymbolicIfExpression | MetadataSymbolicSpreadExpression | - MetadataSymbolicSelectExpression | MetadataError; +export type MetadataValue = string|number|boolean|undefined|null|MetadataObject|MetadataArray| + MetadataSymbolicExpression|MetadataSymbolicReferenceExpression|MetadataSymbolicBinaryExpression| + MetadataSymbolicIndexExpression|MetadataSymbolicCallExpression|MetadataSymbolicPrefixExpression| + MetadataSymbolicIfExpression|MetadataSymbolicSpreadExpression|MetadataSymbolicSelectExpression| + MetadataError; -export interface MetadataObject { [name: string]: MetadataValue; } +export interface MetadataObject { + [name: string]: MetadataValue; +} -export interface MetadataArray { [name: number]: MetadataValue; } +export interface MetadataArray { + [name: number]: MetadataValue; +} -export type MetadataSymbolicExpression = MetadataSymbolicBinaryExpression | - MetadataSymbolicIndexExpression | MetadataSymbolicIndexExpression | - MetadataSymbolicCallExpression | MetadataSymbolicCallExpression | - MetadataSymbolicPrefixExpression | MetadataSymbolicIfExpression | - MetadataGlobalReferenceExpression | MetadataModuleReferenceExpression | - MetadataImportedSymbolReferenceExpression | MetadataImportedDefaultReferenceExpression | - MetadataSymbolicSelectExpression | MetadataSymbolicSpreadExpression; +export type MetadataSymbolicExpression = MetadataSymbolicBinaryExpression| + MetadataSymbolicIndexExpression|MetadataSymbolicIndexExpression|MetadataSymbolicCallExpression| + MetadataSymbolicCallExpression|MetadataSymbolicPrefixExpression|MetadataSymbolicIfExpression| + MetadataGlobalReferenceExpression|MetadataModuleReferenceExpression| + MetadataImportedSymbolReferenceExpression|MetadataImportedDefaultReferenceExpression| + MetadataSymbolicSelectExpression|MetadataSymbolicSpreadExpression; export function isMetadataSymbolicExpression(value: any): value is MetadataSymbolicExpression { if (value) { @@ -234,18 +240,17 @@ export function isMetadataImportedSymbolReferenceExpression(value: any): export interface MetadataImportedDefaultReferenceExpression extends MetadataSourceLocationInfo { __symbolic: 'reference'; module: string; - default: - boolean; - arguments?: MetadataValue[]; + default: boolean; + arguments?: MetadataValue[]; } export function isMetadataImportDefaultReference(value: any): value is MetadataImportedDefaultReferenceExpression { return value && value.module && value.default && isMetadataSymbolicReferenceExpression(value); } -export type MetadataSymbolicReferenceExpression = MetadataGlobalReferenceExpression | - MetadataModuleReferenceExpression | MetadataImportedSymbolReferenceExpression | - MetadataImportedDefaultReferenceExpression; +export type MetadataSymbolicReferenceExpression = + MetadataGlobalReferenceExpression|MetadataModuleReferenceExpression| + MetadataImportedSymbolReferenceExpression|MetadataImportedDefaultReferenceExpression; export function isMetadataSymbolicReferenceExpression(value: any): value is MetadataSymbolicReferenceExpression { return value && value.__symbolic === 'reference'; diff --git a/packages/compiler-cli/src/metadata/symbols.ts b/packages/compiler-cli/src/metadata/symbols.ts index afd7aff827..e1f6563c76 100644 --- a/packages/compiler-cli/src/metadata/symbols.ts +++ b/packages/compiler-cli/src/metadata/symbols.ts @@ -12,7 +12,7 @@ import {MetadataSymbolicReferenceExpression, MetadataValue} from './schema'; export class Symbols { // TODO(issue/24571): remove '!'. - private _symbols !: Map; + private _symbols!: Map; private references = new Map(); constructor(private sourceFile: ts.SourceFile) {} @@ -21,12 +21,16 @@ export class Symbols { return (preferReference && this.references.get(name)) || this.symbols.get(name); } - define(name: string, value: MetadataValue) { this.symbols.set(name, value); } + define(name: string, value: MetadataValue) { + this.symbols.set(name, value); + } defineReference(name: string, value: MetadataSymbolicReferenceExpression) { this.references.set(name, value); } - has(name: string): boolean { return this.symbols.has(name); } + has(name: string): boolean { + return this.symbols.has(name); + } private get symbols(): Map { let result = this._symbols; diff --git a/packages/compiler-cli/src/ngtsc/annotations/src/component.ts b/packages/compiler-cli/src/ngtsc/annotations/src/component.ts index 3568e4f20a..1aa775a1eb 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/src/component.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/src/component.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {ConstantPool, CssSelector, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, Expression, ExternalExpr, Identifiers, InterpolationConfig, LexerRange, ParseError, ParseSourceFile, ParseTemplateOptions, R3ComponentMetadata, R3FactoryTarget, R3TargetBinder, SchemaMetadata, SelectorMatcher, Statement, TmplAstNode, WrappedNodeExpr, compileComponentFromMetadata, makeBindingParser, parseTemplate} from '@angular/compiler'; +import {compileComponentFromMetadata, ConstantPool, CssSelector, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, Expression, ExternalExpr, Identifiers, InterpolationConfig, LexerRange, makeBindingParser, ParseError, ParseSourceFile, parseTemplate, ParseTemplateOptions, R3ComponentMetadata, R3FactoryTarget, R3TargetBinder, SchemaMetadata, SelectorMatcher, Statement, TmplAstNode, WrappedNodeExpr} from '@angular/compiler'; import * as ts from 'typescript'; import {CycleAnalyzer} from '../../cycles'; @@ -15,7 +15,7 @@ import {absoluteFrom, relative} from '../../file_system'; import {DefaultImportRecorder, ModuleResolver, Reference, ReferenceEmitter} from '../../imports'; import {DependencyTracker} from '../../incremental/api'; import {IndexingContext} from '../../indexer'; -import {DirectiveMeta, InjectableClassRegistry, MetadataReader, MetadataRegistry, extractDirectiveGuards} from '../../metadata'; +import {DirectiveMeta, extractDirectiveGuards, InjectableClassRegistry, MetadataReader, MetadataRegistry} from '../../metadata'; import {flattenInheritedDirectiveMetadata} from '../../metadata/src/inheritance'; import {EnumValue, PartialEvaluator} from '../../partial_evaluator'; import {ClassDeclaration, Decorator, ReflectionHost, reflectObjectLiteral} from '../../reflection'; @@ -200,7 +200,7 @@ export class ComponentDecoratorHandler implements } else { return previous; } - }, undefined) !; + }, undefined)!; // Note that we could technically combine the `viewProvidersRequiringFactory` and @@ -211,7 +211,7 @@ export class ComponentDecoratorHandler implements let wrappedViewProviders: Expression|null = null; if (component.has('viewProviders')) { - const viewProviders = component.get('viewProviders') !; + const viewProviders = component.get('viewProviders')!; viewProvidersRequiringFactory = resolveProvidersRequiringFactory(viewProviders, this.reflector, this.evaluator); wrappedViewProviders = new WrappedNodeExpr( @@ -221,7 +221,7 @@ export class ComponentDecoratorHandler implements if (component.has('providers')) { providersRequiringFactory = resolveProvidersRequiringFactory( - component.get('providers') !, this.reflector, this.evaluator); + component.get('providers')!, this.reflector, this.evaluator); } // Parse the template. @@ -232,14 +232,14 @@ export class ComponentDecoratorHandler implements let template: ParsedTemplateWithSource; if (this.preanalyzeTemplateCache.has(node)) { // The template was parsed in preanalyze. Use it and delete it to save memory. - const preanalyzed = this.preanalyzeTemplateCache.get(node) !; + const preanalyzed = this.preanalyzeTemplateCache.get(node)!; this.preanalyzeTemplateCache.delete(node); template = preanalyzed; } else { // The template was not already parsed. Either there's a templateUrl, or an inline template. if (component.has('templateUrl')) { - const templateUrlExpr = component.get('templateUrl') !; + const templateUrlExpr = component.get('templateUrl')!; const templateUrl = this.evaluator.evaluate(templateUrlExpr); if (typeof templateUrl !== 'string') { throw new FatalDiagnosticError( @@ -303,7 +303,7 @@ export class ComponentDecoratorHandler implements let animations: Expression|null = null; if (component.has('animations')) { - animations = new WrappedNodeExpr(component.get('animations') !); + animations = new WrappedNodeExpr(component.get('animations')!); } const output: AnalysisOutput = { @@ -323,7 +323,8 @@ export class ComponentDecoratorHandler implements // analyzed and the full compilation scope for the component can be realized. animations, viewProviders: wrappedViewProviders, - i18nUseExternalIds: this.i18nUseExternalIds, relativeContextFilePath, + i18nUseExternalIds: this.i18nUseExternalIds, + relativeContextFilePath, }, guards: extractDirectiveGuards(node, this.reflector), metadataStmt: generateSetClassMetadataCall( @@ -335,7 +336,7 @@ export class ComponentDecoratorHandler implements }, }; if (changeDetection !== null) { - output.analysis !.meta.changeDetection = changeDetection; + output.analysis!.meta.changeDetection = changeDetection; } return output; } @@ -353,7 +354,8 @@ export class ComponentDecoratorHandler implements outputs: analysis.meta.outputs, queries: analysis.meta.queries.map(query => query.propertyName), isComponent: true, - baseClass: analysis.baseClass, ...analysis.guards, + baseClass: analysis.baseClass, + ...analysis.guards, }); this.injectableRegistry.registerInjectable(node); @@ -415,8 +417,8 @@ export class ComponentDecoratorHandler implements } for (const {name, ref} of scope.compilation.pipes) { if (!ts.isClassDeclaration(ref.node)) { - throw new Error( - `Unexpected non-class declaration ${ts.SyntaxKind[ref.node.kind]} for pipe ${ref.debugName}`); + throw new Error(`Unexpected non-class declaration ${ + ts.SyntaxKind[ref.node.kind]} for pipe ${ref.debugName}`); } pipes.set(name, ref as Reference>); } @@ -491,7 +493,7 @@ export class ComponentDecoratorHandler implements // The BoundTarget knows which directives and pipes matched the template. const usedDirectives = bound.getUsedDirectives(); - const usedPipes = bound.getUsedPipes().map(name => pipes.get(name) !); + const usedPipes = bound.getUsedPipes().map(name => pipes.get(name)!); // Scan through the directives/pipes actually used in the template and check whether any // import which needs to be generated would create a cycle. @@ -539,7 +541,7 @@ export class ComponentDecoratorHandler implements if (analysis.providersRequiringFactory !== null && analysis.meta.providers instanceof WrappedNodeExpr) { const providerDiagnostics = getProviderDiagnostics( - analysis.providersRequiringFactory, analysis.meta.providers !.node, + analysis.providersRequiringFactory, analysis.meta.providers!.node, this.injectableRegistry); diagnostics.push(...providerDiagnostics); } @@ -547,7 +549,7 @@ export class ComponentDecoratorHandler implements if (analysis.viewProvidersRequiringFactory !== null && analysis.meta.viewProviders instanceof WrappedNodeExpr) { const viewProviderDiagnostics = getProviderDiagnostics( - analysis.viewProvidersRequiringFactory, analysis.meta.viewProviders !.node, + analysis.viewProvidersRequiringFactory, analysis.meta.viewProviders!.node, this.injectableRegistry); diagnostics.push(...viewProviderDiagnostics); } @@ -587,7 +589,7 @@ export class ComponentDecoratorHandler implements private _resolveLiteral(decorator: Decorator): ts.ObjectLiteralExpression { if (this.literalCache.has(decorator)) { - return this.literalCache.get(decorator) !; + return this.literalCache.get(decorator)!; } if (decorator.args === null || decorator.args.length !== 1) { throw new FatalDiagnosticError( @@ -609,7 +611,7 @@ export class ComponentDecoratorHandler implements component: Map, field: string, enumSymbolName: string): number|null { let resolved: number|null = null; if (component.has(field)) { - const expr = component.get(field) !; + const expr = component.get(field)!; const value = this.evaluator.evaluate(expr) as any; if (value instanceof EnumValue && isAngularCoreReference(value.enumRef, enumSymbolName)) { resolved = value.resolved as number; @@ -628,7 +630,7 @@ export class ComponentDecoratorHandler implements return extraUrls.length > 0 ? extraUrls : null; } - const styleUrlsExpr = component.get('styleUrls') !; + const styleUrlsExpr = component.get('styleUrls')!; const styleUrls = this.evaluator.evaluate(styleUrlsExpr); if (!Array.isArray(styleUrls) || !styleUrls.every(url => typeof url === 'string')) { throw new FatalDiagnosticError( @@ -643,7 +645,7 @@ export class ComponentDecoratorHandler implements containingFile: string): Promise { if (component.has('templateUrl')) { // Extract the templateUrl and preload it. - const templateUrlExpr = component.get('templateUrl') !; + const templateUrlExpr = component.get('templateUrl')!; const templateUrl = this.evaluator.evaluate(templateUrlExpr); if (typeof templateUrl !== 'string') { throw new FatalDiagnosticError( @@ -703,7 +705,7 @@ export class ComponentDecoratorHandler implements ErrorCode.COMPONENT_MISSING_TEMPLATE, Decorator.nodeForError(decorator), 'component is missing a template'); } - const templateExpr = component.get('template') !; + const templateExpr = component.get('template')!; let templateStr: string; let templateUrl: string = ''; @@ -721,7 +723,7 @@ export class ComponentDecoratorHandler implements escapedString = true; sourceMapping = { type: 'direct', - node: templateExpr as(ts.StringLiteral | ts.NoSubstitutionTemplateLiteral), + node: templateExpr as (ts.StringLiteral | ts.NoSubstitutionTemplateLiteral), }; } else { const resolvedTemplate = this.evaluator.evaluate(templateExpr); @@ -749,7 +751,7 @@ export class ComponentDecoratorHandler implements templateRange: LexerRange|undefined, escapedString: boolean): ParsedTemplate { let preserveWhitespaces: boolean = this.defaultPreserveWhitespaces; if (component.has('preserveWhitespaces')) { - const expr = component.get('preserveWhitespaces') !; + const expr = component.get('preserveWhitespaces')!; const value = this.evaluator.evaluate(expr); if (typeof value !== 'boolean') { throw new FatalDiagnosticError( @@ -760,7 +762,7 @@ export class ComponentDecoratorHandler implements let interpolation: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG; if (component.has('interpolation')) { - const expr = component.get('interpolation') !; + const expr = component.get('interpolation')!; const value = this.evaluator.evaluate(expr); if (!Array.isArray(value) || value.length !== 2 || !value.every(element => typeof element === 'string')) { @@ -768,14 +770,15 @@ export class ComponentDecoratorHandler implements ErrorCode.VALUE_HAS_WRONG_TYPE, expr, 'interpolation must be an array with 2 elements of string type'); } - interpolation = InterpolationConfig.fromArray(value as[string, string]); + interpolation = InterpolationConfig.fromArray(value as [string, string]); } const {errors, nodes: emitNodes, styleUrls, styles, ngContentSelectors} = parseTemplate(templateStr, templateUrl, { preserveWhitespaces, interpolationConfig: interpolation, - range: templateRange, escapedString, + range: templateRange, + escapedString, enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat, }); @@ -795,7 +798,8 @@ export class ComponentDecoratorHandler implements const {nodes: diagNodes} = parseTemplate(templateStr, templateUrl, { preserveWhitespaces: true, interpolationConfig: interpolation, - range: templateRange, escapedString, + range: templateRange, + escapedString, enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat, leadingTriviaChars: [], }); @@ -808,7 +812,8 @@ export class ComponentDecoratorHandler implements styles, ngContentSelectors, errors, - template: templateStr, templateUrl, + template: templateStr, + templateUrl, isInline: component.has('template'), file: new ParseSourceFile(templateStr, templateUrl), }; @@ -820,7 +825,7 @@ export class ComponentDecoratorHandler implements } // Figure out what file is being imported. - return this.moduleResolver.resolveModule(expr.value.moduleName !, origin.fileName); + return this.moduleResolver.resolveModule(expr.value.moduleName!, origin.fileName); } private _isCyclicImport(expr: Expression, origin: ts.SourceFile): boolean { diff --git a/packages/compiler-cli/src/ngtsc/annotations/src/diagnostics.ts b/packages/compiler-cli/src/ngtsc/annotations/src/diagnostics.ts index 8b2853eefb..0b4c1da3c5 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/src/diagnostics.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/src/diagnostics.ts @@ -36,9 +36,13 @@ export function getProviderDiagnostics( const contextNode = provider.getOriginForDiagnostics(providersDeclaration); diagnostics.push(makeDiagnostic( ErrorCode.UNDECORATED_PROVIDER, contextNode, - `The class '${provider.node.name.text}' cannot be created via dependency injection, as it does not have an Angular decorator. This will result in an error at runtime. + `The class '${ + provider.node.name + .text}' cannot be created via dependency injection, as it does not have an Angular decorator. This will result in an error at runtime. -Either add the @Injectable() decorator to '${provider.node.name.text}', or configure a different provider (such as a provider with 'useFactory'). +Either add the @Injectable() decorator to '${ + provider.node.name + .text}', or configure a different provider (such as a provider with 'useFactory'). `, [{node: provider.node, messageText: `'${provider.node.name.text}' is declared here.`}])); } @@ -52,7 +56,7 @@ export function getDirectiveDiagnostics( kind: string): ts.Diagnostic[]|null { let diagnostics: ts.Diagnostic[]|null = []; - const addDiagnostics = (more: ts.Diagnostic | ts.Diagnostic[] | null) => { + const addDiagnostics = (more: ts.Diagnostic|ts.Diagnostic[]|null) => { if (more === null) { return; } else if (diagnostics === null) { @@ -121,14 +125,16 @@ export function checkInheritanceOfDirective( function getInheritedUndecoratedCtorDiagnostic( node: ClassDeclaration, baseClass: Reference, reader: MetadataReader) { - const subclassMeta = reader.getDirectiveMetadata(new Reference(node)) !; + const subclassMeta = reader.getDirectiveMetadata(new Reference(node))!; const dirOrComp = subclassMeta.isComponent ? 'Component' : 'Directive'; const baseClassName = baseClass.debugName; return makeDiagnostic( ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR, node.name, - `The ${dirOrComp.toLowerCase()} ${node.name.text} inherits its constructor from ${baseClassName}, ` + + `The ${dirOrComp.toLowerCase()} ${node.name.text} inherits its constructor from ${ + baseClassName}, ` + `but the latter does not have an Angular decorator of its own. Dependency injection will not be able to ` + - `resolve the parameters of ${baseClassName}'s constructor. Either add a @Directive decorator ` + + `resolve the parameters of ${ + baseClassName}'s constructor. Either add a @Directive decorator ` + `to ${baseClassName}, or add an explicit constructor to ${node.name.text}.`); } diff --git a/packages/compiler-cli/src/ngtsc/annotations/src/directive.ts b/packages/compiler-cli/src/ngtsc/annotations/src/directive.ts index 9a20073865..1c86f3d0b3 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/src/directive.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/src/directive.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {ConstantPool, Expression, Identifiers, ParseError, ParsedHostBindings, R3DependencyMetadata, R3DirectiveMetadata, R3FactoryTarget, R3QueryMetadata, Statement, WrappedNodeExpr, compileDirectiveFromMetadata, makeBindingParser, parseHostBindings, verifyHostBindings} from '@angular/compiler'; +import {compileDirectiveFromMetadata, ConstantPool, Expression, Identifiers, makeBindingParser, ParsedHostBindings, ParseError, parseHostBindings, R3DependencyMetadata, R3DirectiveMetadata, R3FactoryTarget, R3QueryMetadata, Statement, verifyHostBindings, WrappedNodeExpr} from '@angular/compiler'; import * as ts from 'typescript'; import {ErrorCode, FatalDiagnosticError} from '../../diagnostics'; @@ -14,7 +14,7 @@ import {DefaultImportRecorder, Reference} from '../../imports'; import {InjectableClassRegistry, MetadataReader, MetadataRegistry} from '../../metadata'; import {extractDirectiveGuards} from '../../metadata/src/util'; import {DynamicValue, EnumValue, PartialEvaluator} from '../../partial_evaluator'; -import {ClassDeclaration, ClassMember, ClassMemberKind, Decorator, ReflectionHost, filterToMembersWithDecorator, reflectObjectLiteral} from '../../reflection'; +import {ClassDeclaration, ClassMember, ClassMemberKind, Decorator, filterToMembersWithDecorator, ReflectionHost, reflectObjectLiteral} from '../../reflection'; import {LocalModuleScopeRegistry} from '../../scope'; import {AnalysisOutput, CompileResult, DecoratorHandler, DetectResult, HandlerFlags, HandlerPrecedence, ResolveResult} from '../../transform'; @@ -92,7 +92,7 @@ export class DirectiveDecoratorHandler implements let providersRequiringFactory: Set>|null = null; if (directiveResult !== undefined && directiveResult.decorator.has('providers')) { providersRequiringFactory = resolveProvidersRequiringFactory( - directiveResult.decorator.get('providers') !, this.reflector, this.evaluator); + directiveResult.decorator.get('providers')!, this.reflector, this.evaluator); } return { @@ -102,7 +102,8 @@ export class DirectiveDecoratorHandler implements node, this.reflector, this.defaultImportRecorder, this.isCore, this.annotateForClosureCompiler), baseClass: readBaseClass(node, this.reflector, this.evaluator), - guards: extractDirectiveGuards(node, this.reflector), providersRequiringFactory + guards: extractDirectiveGuards(node, this.reflector), + providersRequiringFactory } }; } @@ -120,7 +121,8 @@ export class DirectiveDecoratorHandler implements outputs: analysis.meta.outputs, queries: analysis.meta.queries.map(query => query.propertyName), isComponent: false, - baseClass: analysis.baseClass, ...analysis.guards, + baseClass: analysis.baseClass, + ...analysis.guards, }); this.injectableRegistry.registerInjectable(node); @@ -132,7 +134,7 @@ export class DirectiveDecoratorHandler implements if (analysis.providersRequiringFactory !== null && analysis.meta.providers instanceof WrappedNodeExpr) { const providerDiagnostics = getProviderDiagnostics( - analysis.providersRequiringFactory, analysis.meta.providers !.node, + analysis.providersRequiringFactory, analysis.meta.providers!.node, this.injectableRegistry); diagnostics.push(...providerDiagnostics); } @@ -176,9 +178,8 @@ export class DirectiveDecoratorHandler implements export function extractDirectiveMetadata( clazz: ClassDeclaration, decorator: Readonly, reflector: ReflectionHost, evaluator: PartialEvaluator, defaultImportRecorder: DefaultImportRecorder, isCore: boolean, - flags: HandlerFlags, annotateForClosureCompiler: boolean, - defaultSelector: string | null = - null): {decorator: Map, metadata: R3DirectiveMetadata}|undefined { + flags: HandlerFlags, annotateForClosureCompiler: boolean, defaultSelector: string|null = null): + {decorator: Map, metadata: R3DirectiveMetadata}|undefined { let directive: Map; if (decorator === null || decorator.args === null || decorator.args.length === 0) { directive = new Map(); @@ -220,9 +221,10 @@ export function extractDirectiveMetadata( // And outputs. const outputsFromMeta = parseFieldToPropertyMapping(directive, 'outputs', evaluator); - const outputsFromFields = parseDecoratedFields( - filterToMembersWithDecorator(decoratedElements, 'Output', coreModule), evaluator, - resolveOutput) as{[field: string]: string}; + const outputsFromFields = + parseDecoratedFields( + filterToMembersWithDecorator(decoratedElements, 'Output', coreModule), evaluator, + resolveOutput) as {[field: string]: string}; // Construct the list of queries. const contentChildFromFields = queriesFromFields( filterToMembersWithDecorator(decoratedElements, 'ContentChild', coreModule), reflector, @@ -244,7 +246,7 @@ export function extractDirectiveMetadata( if (directive.has('queries')) { const queriesFromDecorator = - extractQueriesFromDecorator(directive.get('queries') !, reflector, evaluator, isCore); + extractQueriesFromDecorator(directive.get('queries')!, reflector, evaluator, isCore); queries.push(...queriesFromDecorator.content); viewQueries.push(...queriesFromDecorator.view); } @@ -252,7 +254,7 @@ export function extractDirectiveMetadata( // Parse the selector. let selector = defaultSelector; if (directive.has('selector')) { - const expr = directive.get('selector') !; + const expr = directive.get('selector')!; const resolved = evaluator.evaluate(expr); if (typeof resolved !== 'string') { throw new FatalDiagnosticError( @@ -272,8 +274,8 @@ export function extractDirectiveMetadata( const providers: Expression|null = directive.has('providers') ? new WrappedNodeExpr( annotateForClosureCompiler ? - wrapFunctionExpressionsInParens(directive.get('providers') !) : - directive.get('providers') !) : + wrapFunctionExpressionsInParens(directive.get('providers')!) : + directive.get('providers')!) : null; // Determine if `ngOnChanges` is a lifecycle hook defined on the component. @@ -284,7 +286,7 @@ export function extractDirectiveMetadata( // Parse exportAs. let exportAs: string[]|null = null; if (directive.has('exportAs')) { - const expr = directive.get('exportAs') !; + const expr = directive.get('exportAs')!; const resolved = evaluator.evaluate(expr); if (typeof resolved !== 'string') { throw new FatalDiagnosticError( @@ -312,15 +314,24 @@ export function extractDirectiveMetadata( const metadata: R3DirectiveMetadata = { name: clazz.name.text, - deps: ctorDeps, host, + deps: ctorDeps, + host, lifecycle: { - usesOnChanges, + usesOnChanges, }, inputs: {...inputsFromMeta, ...inputsFromFields}, - outputs: {...outputsFromMeta, ...outputsFromFields}, queries, viewQueries, selector, - fullInheritance: !!(flags & HandlerFlags.FULL_INHERITANCE), type, internalType, + outputs: {...outputsFromMeta, ...outputsFromFields}, + queries, + viewQueries, + selector, + fullInheritance: !!(flags & HandlerFlags.FULL_INHERITANCE), + type, + internalType, typeArgumentCount: reflector.getGenericArityOfClass(clazz) || 0, - typeSourceSpan: createSourceSpan(clazz.name), usesInheritance, exportAs, providers + typeSourceSpan: createSourceSpan(clazz.name), + usesInheritance, + exportAs, + providers }; return {decorator: directive, metadata}; } @@ -366,11 +377,11 @@ export function extractQueryMetadata( } const options = reflectObjectLiteral(optionsExpr); if (options.has('read')) { - read = new WrappedNodeExpr(options.get('read') !); + read = new WrappedNodeExpr(options.get('read')!); } if (options.has('descendants')) { - const descendantsExpr = options.get('descendants') !; + const descendantsExpr = options.get('descendants')!; const descendantsValue = evaluator.evaluate(descendantsExpr); if (typeof descendantsValue !== 'boolean') { throw new FatalDiagnosticError( @@ -381,7 +392,7 @@ export function extractQueryMetadata( } if (options.has('static')) { - const staticValue = evaluator.evaluate(options.get('static') !); + const staticValue = evaluator.evaluate(options.get('static')!); if (typeof staticValue !== 'boolean') { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, node, `@${name} options.static must be a boolean`); @@ -466,7 +477,7 @@ export function parseFieldArrayValue( } // Resolve the field of interest from the directive metadata to a string[]. - const expression = directive.get(field) !; + const expression = directive.get(field)!; const value = evaluator.evaluate(expression); if (!isStringArrayOrDie(value, field, expression)) { throw new FatalDiagnosticError( @@ -489,15 +500,13 @@ function parseFieldToPropertyMapping( return EMPTY_OBJECT; } - return metaValues.reduce( - (results, value) => { - // Either the value is 'field' or 'field: property'. In the first case, `property` will - // be undefined, in which case the field name should also be used as the property name. - const [field, property] = value.split(':', 2).map(str => str.trim()); - results[field] = property || field; - return results; - }, - {} as{[field: string]: string}); + return metaValues.reduce((results, value) => { + // Either the value is 'field' or 'field: property'. In the first case, `property` will + // be undefined, in which case the field name should also be used as the property name. + const [field, property] = value.split(':', 2).map(str => str.trim()); + results[field] = property || field; + return results; + }, {} as {[field: string]: string}); } /** @@ -507,33 +516,32 @@ function parseFieldToPropertyMapping( function parseDecoratedFields( fields: {member: ClassMember, decorators: Decorator[]}[], evaluator: PartialEvaluator, mapValueResolver: (publicName: string, internalName: string) => - string | [string, string]): {[field: string]: string | [string, string]} { - return fields.reduce( - (results, field) => { - const fieldName = field.member.name; - field.decorators.forEach(decorator => { - // The decorator either doesn't have an argument (@Input()) in which case the property - // name is used, or it has one argument (@Output('named')). - if (decorator.args == null || decorator.args.length === 0) { - results[fieldName] = fieldName; - } else if (decorator.args.length === 1) { - const property = evaluator.evaluate(decorator.args[0]); - if (typeof property !== 'string') { - throw new FatalDiagnosticError( - ErrorCode.VALUE_HAS_WRONG_TYPE, Decorator.nodeForError(decorator), - `@${decorator.name} decorator argument must resolve to a string`); - } - results[fieldName] = mapValueResolver(property, fieldName); - } else { - // Too many arguments. - throw new FatalDiagnosticError( - ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), - `@${decorator.name} can have at most one argument, got ${decorator.args.length} argument(s)`); - } - }); - return results; - }, - {} as{[field: string]: string | [string, string]}); + string | [string, string]): {[field: string]: string|[string, string]} { + return fields.reduce((results, field) => { + const fieldName = field.member.name; + field.decorators.forEach(decorator => { + // The decorator either doesn't have an argument (@Input()) in which case the property + // name is used, or it has one argument (@Output('named')). + if (decorator.args == null || decorator.args.length === 0) { + results[fieldName] = fieldName; + } else if (decorator.args.length === 1) { + const property = evaluator.evaluate(decorator.args[0]); + if (typeof property !== 'string') { + throw new FatalDiagnosticError( + ErrorCode.VALUE_HAS_WRONG_TYPE, Decorator.nodeForError(decorator), + `@${decorator.name} decorator argument must resolve to a string`); + } + results[fieldName] = mapValueResolver(property, fieldName); + } else { + // Too many arguments. + throw new FatalDiagnosticError( + ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), + `@${decorator.name} can have at most one argument, got ${ + decorator.args.length} argument(s)`); + } + }); + return results; + }, {} as {[field: string]: string | [string, string]}); } function resolveInput(publicName: string, internalName: string): [string, string] { @@ -552,7 +560,7 @@ export function queriesFromFields( const node = member.node || Decorator.nodeForError(decorator); // Throw in case of `@Input() @ContentChild('foo') foo: any`, which is not supported in Ivy - if (member.decorators !.some(v => v.name === 'Input')) { + if (member.decorators!.some(v => v.name === 'Input')) { throw new FatalDiagnosticError( ErrorCode.DECORATOR_COLLISION, node, 'Cannot combine @Input decorators with query decorators'); @@ -626,38 +634,40 @@ function evaluateHostExpressionBindings( } export function extractHostBindings( - members: ClassMember[], evaluator: PartialEvaluator, coreModule: string | undefined, + members: ClassMember[], evaluator: PartialEvaluator, coreModule: string|undefined, metadata?: Map): ParsedHostBindings { let bindings: ParsedHostBindings; if (metadata && metadata.has('host')) { - bindings = evaluateHostExpressionBindings(metadata.get('host') !, evaluator); + bindings = evaluateHostExpressionBindings(metadata.get('host')!, evaluator); } else { bindings = parseHostBindings({}); } - filterToMembersWithDecorator(members, 'HostBinding', coreModule).forEach(({member, decorators}) => { - decorators.forEach(decorator => { - let hostPropertyName: string = member.name; - if (decorator.args !== null && decorator.args.length > 0) { - if (decorator.args.length !== 1) { - throw new FatalDiagnosticError( - ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), - `@HostBinding can have at most one argument, got ${decorator.args.length} argument(s)`); - } + filterToMembersWithDecorator(members, 'HostBinding', coreModule) + .forEach(({member, decorators}) => { + decorators.forEach(decorator => { + let hostPropertyName: string = member.name; + if (decorator.args !== null && decorator.args.length > 0) { + if (decorator.args.length !== 1) { + throw new FatalDiagnosticError( + ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), + `@HostBinding can have at most one argument, got ${ + decorator.args.length} argument(s)`); + } - const resolved = evaluator.evaluate(decorator.args[0]); - if (typeof resolved !== 'string') { - throw new FatalDiagnosticError( - ErrorCode.VALUE_HAS_WRONG_TYPE, Decorator.nodeForError(decorator), - `@HostBinding's argument must be a string`); - } + const resolved = evaluator.evaluate(decorator.args[0]); + if (typeof resolved !== 'string') { + throw new FatalDiagnosticError( + ErrorCode.VALUE_HAS_WRONG_TYPE, Decorator.nodeForError(decorator), + `@HostBinding's argument must be a string`); + } - hostPropertyName = resolved; - } + hostPropertyName = resolved; + } - bindings.properties[hostPropertyName] = member.name; - }); - }); + bindings.properties[hostPropertyName] = member.name; + }); + }); filterToMembersWithDecorator(members, 'HostListener', coreModule) .forEach(({member, decorators}) => { diff --git a/packages/compiler-cli/src/ngtsc/annotations/src/factory.ts b/packages/compiler-cli/src/ngtsc/annotations/src/factory.ts index 0aa284ca76..e7a3308e99 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/src/factory.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/src/factory.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {R3FactoryMetadata, compileFactoryFunction} from '@angular/compiler'; +import {compileFactoryFunction, R3FactoryMetadata} from '@angular/compiler'; import {CompileResult} from '../../transform'; diff --git a/packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts b/packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts index 98b81843f9..6578c7aebf 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Expression, Identifiers, LiteralExpr, R3DependencyMetadata, R3FactoryTarget, R3InjectableMetadata, R3ResolvedDependencyType, Statement, WrappedNodeExpr, compileInjectable as compileIvyInjectable} from '@angular/compiler'; +import {compileInjectable as compileIvyInjectable, Expression, Identifiers, LiteralExpr, R3DependencyMetadata, R3FactoryTarget, R3InjectableMetadata, R3ResolvedDependencyType, Statement, WrappedNodeExpr} from '@angular/compiler'; import * as ts from 'typescript'; import {ErrorCode, FatalDiagnosticError} from '../../diagnostics'; @@ -83,7 +83,9 @@ export class InjectableDecoratorHandler implements }; } - register(node: ClassDeclaration): void { this.injectableRegistry.registerInjectable(node); } + register(node: ClassDeclaration): void { + this.injectableRegistry.registerInjectable(node); + } compile(node: ClassDeclaration, analysis: Readonly): CompileResult[] { const res = compileIvyInjectable(analysis.meta); @@ -165,12 +167,12 @@ function extractInjectableMetadata( const meta = reflectObjectLiteral(metaNode); let providedIn: Expression = new LiteralExpr(null); if (meta.has('providedIn')) { - providedIn = new WrappedNodeExpr(meta.get('providedIn') !); + providedIn = new WrappedNodeExpr(meta.get('providedIn')!); } let userDeps: R3DependencyMetadata[]|undefined = undefined; if ((meta.has('useClass') || meta.has('useFactory')) && meta.has('deps')) { - const depsExpr = meta.get('deps') !; + const depsExpr = meta.get('deps')!; if (!ts.isArrayLiteralExpression(depsExpr)) { throw new FatalDiagnosticError( ErrorCode.VALUE_NOT_LITERAL, depsExpr, @@ -186,7 +188,7 @@ function extractInjectableMetadata( typeArgumentCount, internalType, providedIn, - useValue: new WrappedNodeExpr(unwrapForwardRef(meta.get('useValue') !, reflector)), + useValue: new WrappedNodeExpr(unwrapForwardRef(meta.get('useValue')!, reflector)), }; } else if (meta.has('useExisting')) { return { @@ -195,7 +197,7 @@ function extractInjectableMetadata( typeArgumentCount, internalType, providedIn, - useExisting: new WrappedNodeExpr(unwrapForwardRef(meta.get('useExisting') !, reflector)), + useExisting: new WrappedNodeExpr(unwrapForwardRef(meta.get('useExisting')!, reflector)), }; } else if (meta.has('useClass')) { return { @@ -204,19 +206,20 @@ function extractInjectableMetadata( typeArgumentCount, internalType, providedIn, - useClass: new WrappedNodeExpr(unwrapForwardRef(meta.get('useClass') !, reflector)), + useClass: new WrappedNodeExpr(unwrapForwardRef(meta.get('useClass')!, reflector)), userDeps, }; } else if (meta.has('useFactory')) { // useFactory is special - the 'deps' property must be analyzed. - const factory = new WrappedNodeExpr(meta.get('useFactory') !); + const factory = new WrappedNodeExpr(meta.get('useFactory')!); return { name, type, typeArgumentCount, internalType, providedIn, - useFactory: factory, userDeps, + useFactory: factory, + userDeps, }; } else { return {name, type, typeArgumentCount, internalType, providedIn}; diff --git a/packages/compiler-cli/src/ngtsc/annotations/src/metadata.ts b/packages/compiler-cli/src/ngtsc/annotations/src/metadata.ts index e779f8d817..bca360ad5e 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/src/metadata.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/src/metadata.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Expression, ExternalExpr, FunctionExpr, Identifiers, InvokeFunctionExpr, LiteralArrayExpr, LiteralExpr, NONE_TYPE, ReturnStatement, Statement, WrappedNodeExpr, literalMap} from '@angular/compiler'; +import {Expression, ExternalExpr, FunctionExpr, Identifiers, InvokeFunctionExpr, LiteralArrayExpr, LiteralExpr, literalMap, NONE_TYPE, ReturnStatement, Statement, WrappedNodeExpr} from '@angular/compiler'; import * as ts from 'typescript'; import {DefaultImportRecorder} from '../../imports'; @@ -71,7 +71,7 @@ export function generateSetClassMetadataCall( duplicateDecoratedMemberNames.join(', ')); } const decoratedMembers = - classMembers.map(member => classMemberToMetadata(member.name, member.decorators !, isCore)); + classMembers.map(member => classMemberToMetadata(member.name, member.decorators!, isCore)); if (decoratedMembers.length > 0) { metaPropDecorators = ts.createObjectLiteral(decoratedMembers); } diff --git a/packages/compiler-cli/src/ngtsc/annotations/src/ng_module.ts b/packages/compiler-cli/src/ngtsc/annotations/src/ng_module.ts index 940ef2458c..ad66da3d1b 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/src/ng_module.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/src/ng_module.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {CUSTOM_ELEMENTS_SCHEMA, Expression, ExternalExpr, InvokeFunctionExpr, LiteralArrayExpr, LiteralExpr, NO_ERRORS_SCHEMA, R3Identifiers, R3InjectorMetadata, R3NgModuleMetadata, R3Reference, STRING_TYPE, SchemaMetadata, Statement, WrappedNodeExpr, compileInjector, compileNgModule} from '@angular/compiler'; +import {compileInjector, compileNgModule, CUSTOM_ELEMENTS_SCHEMA, Expression, ExternalExpr, InvokeFunctionExpr, LiteralArrayExpr, LiteralExpr, NO_ERRORS_SCHEMA, R3Identifiers, R3InjectorMetadata, R3NgModuleMetadata, R3Reference, SchemaMetadata, Statement, STRING_TYPE, WrappedNodeExpr} from '@angular/compiler'; import * as ts from 'typescript'; import {ErrorCode, FatalDiagnosticError, makeDiagnostic} from '../../diagnostics'; @@ -40,7 +40,9 @@ export interface NgModuleAnalysis { providers: ts.Expression|null; } -export interface NgModuleResolution { injectorImports: Expression[]; } +export interface NgModuleResolution { + injectorImports: Expression[]; +} /** * Compiles @NgModule annotations to ngModuleDef fields. @@ -116,7 +118,7 @@ export class NgModuleDecoratorHandler implements let declarationRefs: Reference[] = []; let rawDeclarations: ts.Expression|null = null; if (ngModule.has('declarations')) { - rawDeclarations = ngModule.get('declarations') !; + rawDeclarations = ngModule.get('declarations')!; const declarationMeta = this.evaluator.evaluate(rawDeclarations, forwardRefResolver); declarationRefs = this.resolveTypeList(rawDeclarations, declarationMeta, name, 'declarations'); @@ -128,7 +130,9 @@ export class NgModuleDecoratorHandler implements diagnostics.push(makeDiagnostic( ErrorCode.NGMODULE_INVALID_DECLARATION, errorNode, - `Cannot declare '${ref.node.name.text}' in an NgModule as it's not a part of the current compilation.`, + `Cannot declare '${ + ref.node.name + .text}' in an NgModule as it's not a part of the current compilation.`, [{ node: ref.node.name, messageText: `'${ref.node.name.text}' is declared here.`, @@ -144,28 +148,28 @@ export class NgModuleDecoratorHandler implements let importRefs: Reference[] = []; let rawImports: ts.Expression|null = null; if (ngModule.has('imports')) { - rawImports = ngModule.get('imports') !; + rawImports = ngModule.get('imports')!; const importsMeta = this.evaluator.evaluate(rawImports, moduleResolvers); importRefs = this.resolveTypeList(rawImports, importsMeta, name, 'imports'); } let exportRefs: Reference[] = []; let rawExports: ts.Expression|null = null; if (ngModule.has('exports')) { - rawExports = ngModule.get('exports') !; + rawExports = ngModule.get('exports')!; const exportsMeta = this.evaluator.evaluate(rawExports, moduleResolvers); exportRefs = this.resolveTypeList(rawExports, exportsMeta, name, 'exports'); this.referencesRegistry.add(node, ...exportRefs); } let bootstrapRefs: Reference[] = []; if (ngModule.has('bootstrap')) { - const expr = ngModule.get('bootstrap') !; + const expr = ngModule.get('bootstrap')!; const bootstrapMeta = this.evaluator.evaluate(expr, forwardRefResolver); bootstrapRefs = this.resolveTypeList(expr, bootstrapMeta, name, 'bootstrap'); } const schemas: SchemaMetadata[] = []; if (ngModule.has('schemas')) { - const rawExpr = ngModule.get('schemas') !; + const rawExpr = ngModule.get('schemas')!; const result = this.evaluator.evaluate(rawExpr); if (!Array.isArray(result)) { throw new FatalDiagnosticError( @@ -203,7 +207,7 @@ export class NgModuleDecoratorHandler implements } const id: Expression|null = - ngModule.has('id') ? new WrappedNodeExpr(ngModule.get('id') !) : null; + ngModule.has('id') ? new WrappedNodeExpr(ngModule.get('id')!) : null; const valueContext = node.getSourceFile(); let typeContext = valueContext; @@ -220,7 +224,7 @@ export class NgModuleDecoratorHandler implements const exports = exportRefs.map(exp => this._toR3Reference(exp, valueContext, typeContext)); const isForwardReference = (ref: R3Reference) => - isExpressionForwardReference(ref.value, node.name !, valueContext); + isExpressionForwardReference(ref.value, node.name!, valueContext); const containsForwardDecls = bootstrap.some(isForwardReference) || declarations.some(isForwardReference) || imports.some(isForwardReference) || exports.some(isForwardReference); @@ -244,7 +248,7 @@ export class NgModuleDecoratorHandler implements schemas: [], }; - const rawProviders = ngModule.has('providers') ? ngModule.get('providers') ! : null; + const rawProviders = ngModule.has('providers') ? ngModule.get('providers')! : null; const wrapperProviders = rawProviders !== null ? new WrappedNodeExpr( this.annotateForClosureCompiler ? wrapFunctionExpressionsInParens(rawProviders) : @@ -256,7 +260,7 @@ export class NgModuleDecoratorHandler implements // and pipes from the module exports. const injectorImports: WrappedNodeExpr[] = []; if (ngModule.has('imports')) { - injectorImports.push(new WrappedNodeExpr(ngModule.get('imports') !)); + injectorImports.push(new WrappedNodeExpr(ngModule.get('imports')!)); } if (this.routeAnalyzer !== null) { @@ -279,7 +283,8 @@ export class NgModuleDecoratorHandler implements schemas: schemas, mod: ngModuleDef, inj: ngInjectorDef, - declarations: declarationRefs, rawDeclarations, + declarations: declarationRefs, + rawDeclarations, imports: importRefs, exports: exportRefs, providers: rawProviders, @@ -326,7 +331,7 @@ export class NgModuleDecoratorHandler implements if (analysis.providersRequiringFactory !== null) { const providerDiagnostics = getProviderDiagnostics( - analysis.providersRequiringFactory, analysis.providers !, this.injectableRegistry); + analysis.providersRequiringFactory, analysis.providers!, this.injectableRegistry); diagnostics.push(...providerDiagnostics); } @@ -396,7 +401,7 @@ export class NgModuleDecoratorHandler implements const pipes = scope.compilation.pipes.map(pipe => this.refEmitter.emit(pipe.ref, context)); const directiveArray = new LiteralArrayExpr(directives); const pipesArray = new LiteralArrayExpr(pipes); - const declExpr = this.refEmitter.emit(decl, context) !; + const declExpr = this.refEmitter.emit(decl, context)!; const setComponentScope = new ExternalExpr(R3Identifiers.setComponentScope); const callExpr = new InvokeFunctionExpr(setComponentScope, [declExpr, directiveArray, pipesArray]); @@ -472,8 +477,9 @@ export class NgModuleDecoratorHandler implements return null; } - const typeName = type && (ts.isIdentifier(type.typeName) && type.typeName || - ts.isQualifiedName(type.typeName) && type.typeName.right) || + const typeName = type && + (ts.isIdentifier(type.typeName) && type.typeName || + ts.isQualifiedName(type.typeName) && type.typeName.right) || null; if (typeName === null) { return null; @@ -559,7 +565,7 @@ export class NgModuleDecoratorHandler implements // Unwrap ModuleWithProviders for modules that are locally declared (and thus static // resolution was able to descend into the function and return an object literal, a Map). if (entry instanceof Map && entry.has('ngModule')) { - entry = entry.get('ngModule') !; + entry = entry.get('ngModule')!; } if (Array.isArray(entry)) { @@ -569,14 +575,16 @@ export class NgModuleDecoratorHandler implements if (!this.isClassDeclarationReference(entry)) { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, entry.node, - `Value at position ${idx} in the NgModule.${arrayName} of ${className} is not a class`); + `Value at position ${idx} in the NgModule.${arrayName} of ${ + className} is not a class`); } refList.push(entry); } else { // TODO(alxhub): Produce a better diagnostic here - the array index may be an inner array. throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, expr, - `Value at position ${idx} in the NgModule.${arrayName} of ${className} is not a reference: ${entry}`); + `Value at position ${idx} in the NgModule.${arrayName} of ${ + className} is not a reference: ${entry}`); } }); diff --git a/packages/compiler-cli/src/ngtsc/annotations/src/pipe.ts b/packages/compiler-cli/src/ngtsc/annotations/src/pipe.ts index cc99211d16..60b0a058d6 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/src/pipe.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/src/pipe.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Identifiers, R3FactoryTarget, R3PipeMetadata, Statement, WrappedNodeExpr, compilePipeFromMetadata} from '@angular/compiler'; +import {compilePipeFromMetadata, Identifiers, R3FactoryTarget, R3PipeMetadata, Statement, WrappedNodeExpr} from '@angular/compiler'; import * as ts from 'typescript'; import {ErrorCode, FatalDiagnosticError} from '../../diagnostics'; @@ -79,7 +79,7 @@ export class PipeDecoratorHandler implements DecoratorHandler isCore || isAngularCore(dec)).forEach(dec => { - const name = isCore || dec.import === null ? dec.name : dec.import !.name; + const name = isCore || dec.import === null ? dec.name : dec.import!.name; if (name === 'Inject') { if (dec.args === null || dec.args.length !== 1) { throw new FatalDiagnosticError( @@ -97,7 +96,8 @@ export function getConstructorDependencies( if (token === null) { errors.push({ index: idx, - kind: ConstructorDepErrorKind.NO_SUITABLE_TOKEN, param, + kind: ConstructorDepErrorKind.NO_SUITABLE_TOKEN, + param, }); } else { deps.push({token, attribute, optional, self, skipSelf, host, resolved}); @@ -122,10 +122,10 @@ export function valueReferenceToExpression( export function valueReferenceToExpression( valueRef: null, defaultImportRecorder: DefaultImportRecorder): null; export function valueReferenceToExpression( - valueRef: TypeValueReference | null, defaultImportRecorder: DefaultImportRecorder): Expression| + valueRef: TypeValueReference|null, defaultImportRecorder: DefaultImportRecorder): Expression| null; export function valueReferenceToExpression( - valueRef: TypeValueReference | null, defaultImportRecorder: DefaultImportRecorder): Expression| + valueRef: TypeValueReference|null, defaultImportRecorder: DefaultImportRecorder): Expression| null { if (valueRef === null) { return null; @@ -138,7 +138,7 @@ export function valueReferenceToExpression( return new WrappedNodeExpr(valueRef.expression); } else { // TODO(alxhub): this cast is necessary because the g3 typescript version doesn't narrow here. - return new ExternalExpr(valueRef as{moduleName: string, name: string}); + return new ExternalExpr(valueRef as {moduleName: string, name: string}); } } @@ -148,7 +148,7 @@ export function valueReferenceToExpression( * * This is a companion function to `validateConstructorDependencies` which accepts invalid deps. */ -export function unwrapConstructorDependencies(deps: ConstructorDeps | null): R3DependencyMetadata[]| +export function unwrapConstructorDependencies(deps: ConstructorDeps|null): R3DependencyMetadata[]| 'invalid'|null { if (deps === null) { return null; @@ -176,18 +176,19 @@ export function getValidConstructorDependencies( * deps. */ export function validateConstructorDependencies( - clazz: ClassDeclaration, deps: ConstructorDeps | null): R3DependencyMetadata[]|null { + clazz: ClassDeclaration, deps: ConstructorDeps|null): R3DependencyMetadata[]|null { if (deps === null) { return null; } else if (deps.deps !== null) { return deps.deps; } else { // TODO(alxhub): this cast is necessary because the g3 typescript version doesn't narrow here. - const {param, index} = (deps as{errors: ConstructorDepError[]}).errors[0]; + const {param, index} = (deps as {errors: ConstructorDepError[]}).errors[0]; // There is at least one error. throw new FatalDiagnosticError( ErrorCode.PARAM_MISSING_TOKEN, param.nameNode, - `No suitable injection token for parameter '${param.name || index}' of class '${clazz.name.text}'.\n` + + `No suitable injection token for parameter '${param.name || index}' of class '${ + clazz.name.text}'.\n` + (param.typeNode !== null ? `Found ${param.typeNode.getText()}` : 'no type or decorator')); } @@ -319,8 +320,7 @@ export function forwardRefResolver( */ export function combineResolvers(resolvers: ForeignFunctionResolver[]): ForeignFunctionResolver { return (ref: Reference, - args: ReadonlyArray): ts.Expression | - null => { + args: ReadonlyArray): ts.Expression|null => { for (const resolver of resolvers) { const resolved = resolver(ref, args); if (resolved !== null) { @@ -406,8 +406,8 @@ export function makeDuplicateDeclarationError( const contextNode = decl.ref.getOriginForDiagnostics(decl.rawDeclarations, decl.ngModule.name); context.push({ node: contextNode, - messageText: - `'${node.name.text}' is listed in the declarations of the NgModule '${decl.ngModule.name.text}'.`, + messageText: `'${node.name.text}' is listed in the declarations of the NgModule '${ + decl.ngModule.name.text}'.`, }); } @@ -441,7 +441,7 @@ export function resolveProvidersRequiringFactory( } else if (provider instanceof Reference) { tokenClass = provider; } else if (provider instanceof Map && provider.has('useClass') && !provider.has('deps')) { - const useExisting = provider.get('useClass') !; + const useExisting = provider.get('useClass')!; if (useExisting instanceof Reference) { tokenClass = useExisting; } diff --git a/packages/compiler-cli/src/ngtsc/annotations/test/component_spec.ts b/packages/compiler-cli/src/ngtsc/annotations/test/component_spec.ts index 02772389e3..fa952d1a60 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/test/component_spec.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/test/component_spec.ts @@ -12,17 +12,23 @@ import {runInEachFileSystem} from '../../file_system/testing'; import {ModuleResolver, NOOP_DEFAULT_IMPORT_RECORDER, ReferenceEmitter} from '../../imports'; import {CompoundMetadataReader, DtsMetadataReader, InjectableClassRegistry, LocalMetadataRegistry} from '../../metadata'; import {PartialEvaluator} from '../../partial_evaluator'; -import {TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection'; +import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../scope'; import {getDeclaration, makeProgram} from '../../testing'; import {ResourceLoader} from '../src/api'; import {ComponentDecoratorHandler} from '../src/component'; export class NoopResourceLoader implements ResourceLoader { - resolve(): string { throw new Error('Not implemented.'); } + resolve(): string { + throw new Error('Not implemented.'); + } canPreload = false; - load(): string { throw new Error('Not implemented'); } - preload(): Promise|undefined { throw new Error('Not implemented'); } + load(): string { + throw new Error('Not implemented'); + } + preload(): Promise|undefined { + throw new Error('Not implemented'); + } } runInEachFileSystem(() => { describe('ComponentDecoratorHandler', () => { @@ -83,10 +89,12 @@ runInEachFileSystem(() => { const diag = err.toDiagnostic(); expect(diag.code).toEqual(ivyCode(ErrorCode.DECORATOR_ARG_NOT_LITERAL)); expect(diag.file.fileName.endsWith('entry.ts')).toBe(true); - expect(diag.start).toBe(detected.metadata.args ![0].getStart()); + expect(diag.start).toBe(detected.metadata.args![0].getStart()); } }); }); - function ivyCode(code: ErrorCode): number { return Number('-99' + code.valueOf()); } + function ivyCode(code: ErrorCode): number { + return Number('-99' + code.valueOf()); + } }); diff --git a/packages/compiler-cli/src/ngtsc/annotations/test/directive_spec.ts b/packages/compiler-cli/src/ngtsc/annotations/test/directive_spec.ts index 62ecab624e..0cd61336f1 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/test/directive_spec.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/test/directive_spec.ts @@ -6,12 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; + import {absoluteFrom} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {NOOP_DEFAULT_IMPORT_RECORDER, ReferenceEmitter} from '../../imports'; import {DtsMetadataReader, InjectableClassRegistry, LocalMetadataRegistry} from '../../metadata'; import {PartialEvaluator} from '../../partial_evaluator'; -import {ClassDeclaration, TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection'; +import {ClassDeclaration, isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../scope'; import {getDeclaration, makeProgram} from '../../testing'; import {DirectiveDecoratorHandler} from '../src/directive'; @@ -77,9 +78,13 @@ runInEachFileSystem(() => { // Helpers function analyzeDirective(program: ts.Program, dirName: string, hasBaseClass: boolean = false) { class TestReflectionHost extends TypeScriptReflectionHost { - constructor(checker: ts.TypeChecker) { super(checker); } + constructor(checker: ts.TypeChecker) { + super(checker); + } - hasBaseClass(_class: ClassDeclaration): boolean { return hasBaseClass; } + hasBaseClass(_class: ClassDeclaration): boolean { + return hasBaseClass; + } } const checker = program.getTypeChecker(); diff --git a/packages/compiler-cli/src/ngtsc/annotations/test/injectable_spec.ts b/packages/compiler-cli/src/ngtsc/annotations/test/injectable_spec.ts index fed17853d4..104f9d48a0 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/test/injectable_spec.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/test/injectable_spec.ts @@ -10,7 +10,7 @@ import {absoluteFrom} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {NOOP_DEFAULT_IMPORT_RECORDER} from '../../imports'; import {InjectableClassRegistry} from '../../metadata'; -import {TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection'; +import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {InjectableDecoratorHandler} from '../src/injectable'; @@ -31,7 +31,7 @@ runInEachFileSystem(() => { const diag = err.toDiagnostic(); expect(diag.code).toEqual(ngErrorCode(ErrorCode.INJECTABLE_DUPLICATE_PROV)); expect(diag.file.fileName.endsWith('entry.ts')).toBe(true); - expect(diag.start).toBe(ɵprov.nameNode !.getStart()); + expect(diag.start).toBe(ɵprov.nameNode!.getStart()); } }); @@ -43,7 +43,6 @@ runInEachFileSystem(() => { expect(res).not.toContain(jasmine.objectContaining({name: 'ɵprov'})); }); }); - }); }); diff --git a/packages/compiler-cli/src/ngtsc/annotations/test/metadata_spec.ts b/packages/compiler-cli/src/ngtsc/annotations/test/metadata_spec.ts index 536bb02c4d..5bf1fc82f9 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/test/metadata_spec.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/test/metadata_spec.ts @@ -6,8 +6,9 @@ * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; + import {absoluteFrom, getSourceFileOrError} from '../../file_system'; -import {TestFile, runInEachFileSystem} from '../../file_system/testing'; +import {runInEachFileSystem, TestFile} from '../../file_system/testing'; import {NOOP_DEFAULT_IMPORT_RECORDER, NoopImportRewriter} from '../../imports'; import {TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; diff --git a/packages/compiler-cli/src/ngtsc/annotations/test/ng_module_spec.ts b/packages/compiler-cli/src/ngtsc/annotations/test/ng_module_spec.ts index 2e89ddca33..0495a5c03f 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/test/ng_module_spec.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/test/ng_module_spec.ts @@ -14,7 +14,7 @@ import {runInEachFileSystem} from '../../file_system/testing'; import {LocalIdentifierStrategy, NOOP_DEFAULT_IMPORT_RECORDER, ReferenceEmitter} from '../../imports'; import {CompoundMetadataReader, DtsMetadataReader, InjectableClassRegistry, LocalMetadataRegistry} from '../../metadata'; import {PartialEvaluator} from '../../partial_evaluator'; -import {TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection'; +import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../scope'; import {getDeclaration, makeProgram} from '../../testing'; import {NgModuleDecoratorHandler} from '../src/ng_module'; @@ -79,7 +79,7 @@ runInEachFileSystem(() => { if (detected === undefined) { return fail('Failed to recognize @NgModule'); } - const moduleDef = handler.analyze(TestModule, detected.metadata).analysis !.mod; + const moduleDef = handler.analyze(TestModule, detected.metadata).analysis!.mod; expect(getReferenceIdentifierTexts(moduleDef.declarations)).toEqual(['TestComp']); expect(getReferenceIdentifierTexts(moduleDef.exports)).toEqual(['TestComp']); diff --git a/packages/compiler-cli/src/ngtsc/annotations/test/util_spec.ts b/packages/compiler-cli/src/ngtsc/annotations/test/util_spec.ts index 95fc30ef1c..6318ea4fc8 100644 --- a/packages/compiler-cli/src/ngtsc/annotations/test/util_spec.ts +++ b/packages/compiler-cli/src/ngtsc/annotations/test/util_spec.ts @@ -13,8 +13,9 @@ import {unwrapExpression} from '../src/util'; describe('ngtsc annotation utilities', () => { describe('unwrapExpression', () => { const obj = ts.createObjectLiteral(); - it('should pass through an ObjectLiteralExpression', - () => { expect(unwrapExpression(obj)).toBe(obj); }); + it('should pass through an ObjectLiteralExpression', () => { + expect(unwrapExpression(obj)).toBe(obj); + }); it('should unwrap an ObjectLiteralExpression in parentheses', () => { const wrapped = ts.createParen(obj); diff --git a/packages/compiler-cli/src/ngtsc/core/api/src/interfaces.ts b/packages/compiler-cli/src/ngtsc/core/api/src/interfaces.ts index fb67d80a60..fa84da22a0 100644 --- a/packages/compiler-cli/src/ngtsc/core/api/src/interfaces.ts +++ b/packages/compiler-cli/src/ngtsc/core/api/src/interfaces.ts @@ -56,7 +56,7 @@ export interface ResourceHost { * core interface. */ export interface ExtendedTsCompilerHost extends ts.CompilerHost, Partial, - Partial {} + Partial {} export interface LazyRoute { route: string; diff --git a/packages/compiler-cli/src/ngtsc/core/api/src/options.ts b/packages/compiler-cli/src/ngtsc/core/api/src/options.ts index 5bcbcc67b0..a27ceb3b04 100644 --- a/packages/compiler-cli/src/ngtsc/core/api/src/options.ts +++ b/packages/compiler-cli/src/ngtsc/core/api/src/options.ts @@ -36,7 +36,8 @@ export interface TestOnlyOptions { */ ivyTemplateTypeCheck?: boolean; - /** An option to enable ngtsc's internal performance tracing. + /** + * An option to enable ngtsc's internal performance tracing. * * This should be a path to a JSON file where trace information will be written. An optional 'ts:' * prefix will cause the trace to be written via the TS host instead of directly to the filesystem @@ -54,4 +55,5 @@ export interface TestOnlyOptions { * Also includes a few miscellaneous options. */ export interface NgCompilerOptions extends ts.CompilerOptions, LegacyNgcOptions, BazelAndG3Options, - NgcCompatibilityOptions, StrictTemplateOptions, TestOnlyOptions, I18nOptions, MiscOptions {} \ No newline at end of file + NgcCompatibilityOptions, StrictTemplateOptions, + TestOnlyOptions, I18nOptions, MiscOptions {} \ No newline at end of file diff --git a/packages/compiler-cli/src/ngtsc/core/src/compiler.ts b/packages/compiler-cli/src/ngtsc/core/src/compiler.ts index 9f315059b9..f932927066 100644 --- a/packages/compiler-cli/src/ngtsc/core/src/compiler.ts +++ b/packages/compiler-cli/src/ngtsc/core/src/compiler.ts @@ -12,23 +12,23 @@ import * as ts from 'typescript'; import {ComponentDecoratorHandler, DirectiveDecoratorHandler, InjectableDecoratorHandler, NgModuleDecoratorHandler, NoopReferencesRegistry, PipeDecoratorHandler, ReferencesRegistry} from '../../annotations'; import {CycleAnalyzer, ImportGraph} from '../../cycles'; import {ErrorCode, ngErrorCode} from '../../diagnostics'; -import {ReferenceGraph, checkForPrivateExports} from '../../entry_point'; -import {LogicalFileSystem, getSourceFileOrError} from '../../file_system'; -import {AbsoluteModuleStrategy, AliasStrategy, AliasingHost, DefaultImportTracker, ImportRewriter, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NoopImportRewriter, PrivateExportAliasingHost, R3SymbolsImportRewriter, Reference, ReferenceEmitStrategy, ReferenceEmitter, RelativePathStrategy, UnifiedModulesAliasingHost, UnifiedModulesStrategy} from '../../imports'; +import {checkForPrivateExports, ReferenceGraph} from '../../entry_point'; +import {getSourceFileOrError, LogicalFileSystem} from '../../file_system'; +import {AbsoluteModuleStrategy, AliasingHost, AliasStrategy, DefaultImportTracker, ImportRewriter, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NoopImportRewriter, PrivateExportAliasingHost, R3SymbolsImportRewriter, Reference, ReferenceEmitStrategy, ReferenceEmitter, RelativePathStrategy, UnifiedModulesAliasingHost, UnifiedModulesStrategy} from '../../imports'; import {IncrementalDriver} from '../../incremental'; -import {IndexedComponent, IndexingContext, generateAnalysis} from '../../indexer'; +import {generateAnalysis, IndexedComponent, IndexingContext} from '../../indexer'; import {CompoundMetadataReader, CompoundMetadataRegistry, DtsMetadataReader, InjectableClassRegistry, LocalMetadataRegistry, MetadataReader} from '../../metadata'; import {ModuleWithProvidersScanner} from '../../modulewithproviders'; import {PartialEvaluator} from '../../partial_evaluator'; import {NOOP_PERF_RECORDER, PerfRecorder} from '../../perf'; import {TypeScriptReflectionHost} from '../../reflection'; import {HostResourceLoader} from '../../resource'; -import {NgModuleRouteAnalyzer, entryPointKeyFor} from '../../routing'; +import {entryPointKeyFor, NgModuleRouteAnalyzer} from '../../routing'; import {ComponentScopeReader, LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../scope'; import {generatedFactoryTransform} from '../../shims'; import {ivySwitchTransform} from '../../switch'; -import {DecoratorHandler, DtsTransformRegistry, TraitCompiler, aliasTransformFactory, declarationTransformFactory, ivyTransformFactory} from '../../transform'; -import {TypeCheckContext, TypeCheckingConfig, isTemplateDiagnostic} from '../../typecheck'; +import {aliasTransformFactory, declarationTransformFactory, DecoratorHandler, DtsTransformRegistry, ivyTransformFactory, TraitCompiler} from '../../transform'; +import {isTemplateDiagnostic, TypeCheckContext, TypeCheckingConfig} from '../../typecheck'; import {getSourceFileOrNull, isDtsPath, resolveModuleName} from '../../util/src/typescript'; import {LazyRoute, NgCompilerOptions} from '../api'; @@ -191,7 +191,9 @@ export class NgCompiler { /** * Get all setup-related diagnostics for this compilation. */ - getOptionDiagnostics(): ts.Diagnostic[] { return this.constructionDiagnostics; } + getOptionDiagnostics(): ts.Diagnostic[] { + return this.constructionDiagnostics; + } /** * Get the `ts.Program` to use as a starting point when spawning a subsequent incremental @@ -202,7 +204,9 @@ export class NgCompiler { * operation, the consumer's `ts.Program` is no longer usable for starting a new incremental * compilation. `getNextProgram` retrieves the `ts.Program` which can be used instead. */ - getNextProgram(): ts.Program { return this.nextProgram; } + getNextProgram(): ts.Program { + return this.nextProgram; + } /** * Perform Angular's analysis step (as a precursor to `getDiagnostics` or `prepareEmit`) @@ -262,8 +266,8 @@ export class NgCompiler { // Relative entry paths are disallowed. if (entryRoute.startsWith('.')) { - throw new Error( - `Failed to list lazy routes: Resolution of relative paths (${entryRoute}) is not supported.`); + throw new Error(`Failed to list lazy routes: Resolution of relative paths (${ + entryRoute}) is not supported.`); } // Non-relative entry paths fall into one of the following categories: @@ -349,7 +353,7 @@ export class NgCompiler { if (this.compilation === null) { this.analyzeSync(); } - return this.compilation !; + return this.compilation!; } private analyzeSync(): void { @@ -482,7 +486,7 @@ export class NgCompiler { // Execute the typeCheck phase of each decorator in the program. const prepSpan = this.perfRecorder.start('typeCheckPrep'); const ctx = new TypeCheckContext( - typeCheckingConfig, compilation.refEmitter !, compilation.reflector, host.typeCheckFile); + typeCheckingConfig, compilation.refEmitter!, compilation.reflector, host.typeCheckFile); compilation.traitCompiler.typeCheck(ctx); this.perfRecorder.stop(prepSpan); @@ -505,7 +509,7 @@ export class NgCompiler { const recordSpan = this.perfRecorder.start('recordDependencies'); const depGraph = this.incrementalDriver.depGraph; - for (const scope of this.compilation !.scopeRegistry !.getCompilationScopes()) { + for (const scope of this.compilation!.scopeRegistry!.getCompilationScopes()) { const file = scope.declaration.getSourceFile(); const ngModuleFile = scope.ngModule.getSourceFile(); @@ -517,7 +521,7 @@ export class NgCompiler { depGraph.addDependency(file, ngModuleFile); const meta = - this.compilation !.metaReader.getDirectiveMetadata(new Reference(scope.declaration)); + this.compilation!.metaReader.getDirectiveMetadata(new Reference(scope.declaration)); if (meta !== null && meta.isComponent) { // If a component's template changes, it might have affected the import graph, and thus the // remote scoping feature which is activated in the event of potential import cycles. Thus, @@ -543,12 +547,11 @@ export class NgCompiler { } private scanForMwp(sf: ts.SourceFile): void { - this.compilation !.mwpScanner.scan(sf, { + this.compilation!.mwpScanner.scan(sf, { addTypeReplacement: (node: ts.Declaration, type: Type): void => { // Only obtain the return type transform for the source file once there's a type to replace, // so that no transform is allocated when there's nothing to do. - this.compilation !.dtsTransforms !.getReturnTypeTransform(sf).addTypeReplacement( - node, type); + this.compilation!.dtsTransforms!.getReturnTypeTransform(sf).addTypeReplacement(node, type); } }); } @@ -686,9 +689,18 @@ export class NgCompiler { this.options.compileNonExportedClasses !== false, dtsTransforms); return { - isCore, traitCompiler, reflector, scopeRegistry, - dtsTransforms, exportReferenceGraph, routeAnalyzer, mwpScanner, - metaReader, defaultImportTracker, aliasingHost, refEmitter, + isCore, + traitCompiler, + reflector, + scopeRegistry, + dtsTransforms, + exportReferenceGraph, + routeAnalyzer, + mwpScanner, + metaReader, + defaultImportTracker, + aliasingHost, + refEmitter, }; } } diff --git a/packages/compiler-cli/src/ngtsc/core/src/host.ts b/packages/compiler-cli/src/ngtsc/core/src/host.ts index 90c684394c..474e08c05f 100644 --- a/packages/compiler-cli/src/ngtsc/core/src/host.ts +++ b/packages/compiler-cli/src/ngtsc/core/src/host.ts @@ -9,7 +9,7 @@ import * as ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../diagnostics'; -import {FlatIndexGenerator, findFlatIndexEntryPoint} from '../../entry_point'; +import {findFlatIndexEntryPoint, FlatIndexGenerator} from '../../entry_point'; import {AbsoluteFsPath, resolve} from '../../file_system'; import {FactoryGenerator, FactoryTracker, ShimGenerator, SummaryGenerator, TypeCheckShimGenerator} from '../../shims'; import {typeCheckFilePath} from '../../typecheck'; @@ -88,8 +88,7 @@ export class DelegatingCompilerHost implements * `ExtendedTsCompilerHost` methods whenever present. */ export class NgCompilerHost extends DelegatingCompilerHost implements - RequiredCompilerHostDelegations, - ExtendedTsCompilerHost { + RequiredCompilerHostDelegations, ExtendedTsCompilerHost { readonly factoryTracker: FactoryTracker|null = null; readonly entryPoint: AbsoluteFsPath|null = null; readonly diagnostics: ts.Diagnostic[]; diff --git a/packages/compiler-cli/src/ngtsc/core/test/compiler_test.ts b/packages/compiler-cli/src/ngtsc/core/test/compiler_test.ts index 493f0a8860..eb8db2ed16 100644 --- a/packages/compiler-cli/src/ngtsc/core/test/compiler_test.ts +++ b/packages/compiler-cli/src/ngtsc/core/test/compiler_test.ts @@ -8,7 +8,7 @@ import * as ts from 'typescript'; -import {FileSystem, NgtscCompilerHost, absoluteFrom as _, getFileSystem, getSourceFileOrError, setFileSystem} from '../../file_system'; +import {absoluteFrom as _, FileSystem, getFileSystem, getSourceFileOrError, NgtscCompilerHost, setFileSystem} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {NgCompilerOptions} from '../api'; import {NgCompiler} from '../src/compiler'; @@ -16,7 +16,6 @@ import {NgCompilerHost} from '../src/host'; runInEachFileSystem(() => { - describe('NgCompiler', () => { let fs: FileSystem; diff --git a/packages/compiler-cli/src/ngtsc/cycles/src/imports.ts b/packages/compiler-cli/src/ngtsc/cycles/src/imports.ts index 37d876c1ba..c14642c1f8 100644 --- a/packages/compiler-cli/src/ngtsc/cycles/src/imports.ts +++ b/packages/compiler-cli/src/ngtsc/cycles/src/imports.ts @@ -30,7 +30,7 @@ export class ImportGraph { if (!this.map.has(sf)) { this.map.set(sf, this.scanImports(sf)); } - return this.map.get(sf) !; + return this.map.get(sf)!; } /** @@ -47,7 +47,9 @@ export class ImportGraph { return; } results.add(sf); - this.importsOf(sf).forEach(imported => { this.transitiveImportsOfHelper(imported, results); }); + this.importsOf(sf).forEach(imported => { + this.transitiveImportsOfHelper(imported, results); + }); } /** diff --git a/packages/compiler-cli/src/ngtsc/diagnostics/src/error.ts b/packages/compiler-cli/src/ngtsc/diagnostics/src/error.ts index 2454c86418..54b03dd5d9 100644 --- a/packages/compiler-cli/src/ngtsc/diagnostics/src/error.ts +++ b/packages/compiler-cli/src/ngtsc/diagnostics/src/error.ts @@ -33,7 +33,8 @@ export function makeDiagnostic(code: ErrorCode, node: ts.Node, messageText: stri code: Number('-99' + code.valueOf()), file: ts.getOriginalNode(node).getSourceFile(), start: node.getStart(undefined, false), - length: node.getWidth(), messageText, + length: node.getWidth(), + messageText, }; if (relatedInfo !== undefined) { diag.relatedInformation = relatedInfo.map(info => { diff --git a/packages/compiler-cli/src/ngtsc/entry_point/src/generator.ts b/packages/compiler-cli/src/ngtsc/entry_point/src/generator.ts index fcf3b760d2..96d95677d3 100644 --- a/packages/compiler-cli/src/ngtsc/entry_point/src/generator.ts +++ b/packages/compiler-cli/src/ngtsc/entry_point/src/generator.ts @@ -24,7 +24,9 @@ export class FlatIndexGenerator implements ShimGenerator { join(dirname(entryPoint), relativeFlatIndexPath).replace(/\.js$/, '') + '.ts'; } - recognize(fileName: string): boolean { return fileName === this.flatIndexPath; } + recognize(fileName: string): boolean { + return fileName === this.flatIndexPath; + } generate(): ts.SourceFile { const relativeEntryPoint = relativePathBetween(this.flatIndexPath, this.entryPoint); diff --git a/packages/compiler-cli/src/ngtsc/entry_point/src/private_export_checker.ts b/packages/compiler-cli/src/ngtsc/entry_point/src/private_export_checker.ts index 06e04d4cd5..57ea95bcec 100644 --- a/packages/compiler-cli/src/ngtsc/entry_point/src/private_export_checker.ts +++ b/packages/compiler-cli/src/ngtsc/entry_point/src/private_export_checker.ts @@ -95,9 +95,11 @@ export function checkForPrivateExports( const diagnostic: ts.Diagnostic = { category: ts.DiagnosticCategory.Error, code: ngErrorCode(ErrorCode.SYMBOL_NOT_EXPORTED), - file: transitiveReference.getSourceFile(), ...getPosOfDeclaration(transitiveReference), - messageText: - `Unsupported private ${descriptor} ${name}. This ${descriptor} is visible to consumers via ${visibleVia}, but is not exported from the top-level library entrypoint.`, + file: transitiveReference.getSourceFile(), + ...getPosOfDeclaration(transitiveReference), + messageText: `Unsupported private ${descriptor} ${name}. This ${ + descriptor} is visible to consumers via ${ + visibleVia}, but is not exported from the top-level library entrypoint.`, }; diagnostics.push(diagnostic); diff --git a/packages/compiler-cli/src/ngtsc/entry_point/src/reference_graph.ts b/packages/compiler-cli/src/ngtsc/entry_point/src/reference_graph.ts index 396e90c5e9..7691df63c3 100644 --- a/packages/compiler-cli/src/ngtsc/entry_point/src/reference_graph.ts +++ b/packages/compiler-cli/src/ngtsc/entry_point/src/reference_graph.ts @@ -15,7 +15,7 @@ export class ReferenceGraph { if (!this.references.has(from)) { this.references.set(from, new Set()); } - this.references.get(from) !.add(to); + this.references.get(from)!.add(to); } transitiveReferencesOf(target: T): Set { @@ -47,7 +47,7 @@ export class ReferenceGraph { // Look through the outgoing edges of `source`. // TODO(alxhub): use proper iteration when the legacy build is removed. (#27762) let candidatePath: T[]|null = null; - this.references.get(source) !.forEach(edge => { + this.references.get(source)!.forEach(edge => { // Early exit if a path has already been found. if (candidatePath !== null) { return; @@ -67,7 +67,7 @@ export class ReferenceGraph { private collectTransitiveReferences(set: Set, decl: T): void { if (this.references.has(decl)) { // TODO(alxhub): use proper iteration when the legacy build is removed. (#27762) - this.references.get(decl) !.forEach(ref => { + this.references.get(decl)!.forEach(ref => { if (!set.has(ref)) { set.add(ref); this.collectTransitiveReferences(set, ref); diff --git a/packages/compiler-cli/src/ngtsc/entry_point/test/entry_point_spec.ts b/packages/compiler-cli/src/ngtsc/entry_point/test/entry_point_spec.ts index 7099cb8cb6..ed77965149 100644 --- a/packages/compiler-cli/src/ngtsc/entry_point/test/entry_point_spec.ts +++ b/packages/compiler-cli/src/ngtsc/entry_point/test/entry_point_spec.ts @@ -16,9 +16,9 @@ runInEachFileSystem(() => { beforeEach(() => _ = absoluteFrom); describe('findFlatIndexEntryPoint', () => { - - it('should use the only source file if only a single one is specified', - () => { expect(findFlatIndexEntryPoint([_('/src/index.ts')])).toBe(_('/src/index.ts')); }); + it('should use the only source file if only a single one is specified', () => { + expect(findFlatIndexEntryPoint([_('/src/index.ts')])).toBe(_('/src/index.ts')); + }); it('should use the shortest source file ending with "index.ts" for multiple files', () => { expect(findFlatIndexEntryPoint([ diff --git a/packages/compiler-cli/src/ngtsc/entry_point/test/reference_graph_spec.ts b/packages/compiler-cli/src/ngtsc/entry_point/test/reference_graph_spec.ts index 78be9e7e6b..6ed312b942 100644 --- a/packages/compiler-cli/src/ngtsc/entry_point/test/reference_graph_spec.ts +++ b/packages/compiler-cli/src/ngtsc/entry_point/test/reference_graph_spec.ts @@ -12,8 +12,9 @@ import {ReferenceGraph} from '../src/reference_graph'; describe('entry_point reference graph', () => { let graph: ReferenceGraph; - const refs = - (target: string) => { return Array.from(graph.transitiveReferencesOf(target)).sort(); }; + const refs = (target: string) => { + return Array.from(graph.transitiveReferencesOf(target)).sort(); + }; beforeEach(() => { graph = new ReferenceGraph(); @@ -45,6 +46,7 @@ describe('entry_point reference graph', () => { expect(graph.pathFrom('beta', 'alpha')).toEqual(['beta', 'delta', 'alpha']); }); - it('should not report a path that doesn\'t exist', - () => { expect(graph.pathFrom('gamma', 'beta')).toBeNull(); }); + it('should not report a path that doesn\'t exist', () => { + expect(graph.pathFrom('gamma', 'beta')).toBeNull(); + }); }); diff --git a/packages/compiler-cli/src/ngtsc/file_system/src/cached_file_system.ts b/packages/compiler-cli/src/ngtsc/file_system/src/cached_file_system.ts index 25e9ff81de..1f04bb2bab 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/src/cached_file_system.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/src/cached_file_system.ts @@ -25,7 +25,7 @@ export class CachedFileSystem implements FileSystem { if (!this.existsCache.has(path)) { this.existsCache.set(path, this.delegate.exists(path)); } - return this.existsCache.get(path) !; + return this.existsCache.get(path)!; } invalidateCaches(path: AbsoluteFsPath) { @@ -131,15 +131,33 @@ export class CachedFileSystem implements FileSystem { } // The following methods simply call through to the delegate. - readdir(path: AbsoluteFsPath): PathSegment[] { return this.delegate.readdir(path); } - pwd(): AbsoluteFsPath { return this.delegate.pwd(); } - chdir(path: AbsoluteFsPath): void { this.delegate.chdir(path); } - extname(path: AbsoluteFsPath|PathSegment): string { return this.delegate.extname(path); } - isCaseSensitive(): boolean { return this.delegate.isCaseSensitive(); } - isRoot(path: AbsoluteFsPath): boolean { return this.delegate.isRoot(path); } - isRooted(path: string): boolean { return this.delegate.isRooted(path); } - resolve(...paths: string[]): AbsoluteFsPath { return this.delegate.resolve(...paths); } - dirname(file: T): T { return this.delegate.dirname(file); } + readdir(path: AbsoluteFsPath): PathSegment[] { + return this.delegate.readdir(path); + } + pwd(): AbsoluteFsPath { + return this.delegate.pwd(); + } + chdir(path: AbsoluteFsPath): void { + this.delegate.chdir(path); + } + extname(path: AbsoluteFsPath|PathSegment): string { + return this.delegate.extname(path); + } + isCaseSensitive(): boolean { + return this.delegate.isCaseSensitive(); + } + isRoot(path: AbsoluteFsPath): boolean { + return this.delegate.isRoot(path); + } + isRooted(path: string): boolean { + return this.delegate.isRooted(path); + } + resolve(...paths: string[]): AbsoluteFsPath { + return this.delegate.resolve(...paths); + } + dirname(file: T): T { + return this.delegate.dirname(file); + } join(basePath: T, ...paths: string[]): T { return this.delegate.join(basePath, ...paths); } @@ -149,7 +167,13 @@ export class CachedFileSystem implements FileSystem { basename(filePath: string, extension?: string|undefined): PathSegment { return this.delegate.basename(filePath, extension); } - realpath(filePath: AbsoluteFsPath): AbsoluteFsPath { return this.delegate.realpath(filePath); } - getDefaultLibLocation(): AbsoluteFsPath { return this.delegate.getDefaultLibLocation(); } - normalize(path: T): T { return this.delegate.normalize(path); } + realpath(filePath: AbsoluteFsPath): AbsoluteFsPath { + return this.delegate.realpath(filePath); + } + getDefaultLibLocation(): AbsoluteFsPath { + return this.delegate.getDefaultLibLocation(); + } + normalize(path: T): T { + return this.delegate.normalize(path); + } } diff --git a/packages/compiler-cli/src/ngtsc/file_system/src/compiler_host.ts b/packages/compiler-cli/src/ngtsc/file_system/src/compiler_host.ts index 3c7b62b26d..40717c44f5 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/src/compiler_host.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/src/compiler_host.ts @@ -26,7 +26,9 @@ export class NgtscCompilerHost implements ts.CompilerHost { return this.fs.join(this.getDefaultLibLocation(), ts.getDefaultLibFileName(options)); } - getDefaultLibLocation(): string { return this.fs.getDefaultLibLocation(); } + getDefaultLibLocation(): string { + return this.fs.getDefaultLibLocation(); + } writeFile( fileName: string, data: string, writeByteOrderMark: boolean, @@ -37,13 +39,17 @@ export class NgtscCompilerHost implements ts.CompilerHost { this.fs.writeFile(path, data); } - getCurrentDirectory(): string { return this.fs.pwd(); } + getCurrentDirectory(): string { + return this.fs.pwd(); + } getCanonicalFileName(fileName: string): string { return this.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } - useCaseSensitiveFileNames(): boolean { return this.fs.isCaseSensitive(); } + useCaseSensitiveFileNames(): boolean { + return this.fs.isCaseSensitive(); + } getNewLine(): string { switch (this.options.newLine) { diff --git a/packages/compiler-cli/src/ngtsc/file_system/src/invalid_file_system.ts b/packages/compiler-cli/src/ngtsc/file_system/src/invalid_file_system.ts index 2fcf235afe..b9a9c4af21 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/src/invalid_file_system.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/src/invalid_file_system.ts @@ -16,32 +16,84 @@ import {AbsoluteFsPath, FileStats, FileSystem, PathSegment, PathString} from './ * the `FileSystem` under the hood. */ export class InvalidFileSystem implements FileSystem { - exists(path: AbsoluteFsPath): boolean { throw makeError(); } - readFile(path: AbsoluteFsPath): string { throw makeError(); } - writeFile(path: AbsoluteFsPath, data: string, exclusive?: boolean): void { throw makeError(); } - removeFile(path: AbsoluteFsPath): void { throw makeError(); } - symlink(target: AbsoluteFsPath, path: AbsoluteFsPath): void { throw makeError(); } - readdir(path: AbsoluteFsPath): PathSegment[] { throw makeError(); } - lstat(path: AbsoluteFsPath): FileStats { throw makeError(); } - stat(path: AbsoluteFsPath): FileStats { throw makeError(); } - pwd(): AbsoluteFsPath { throw makeError(); } - chdir(path: AbsoluteFsPath): void { throw makeError(); } - extname(path: AbsoluteFsPath|PathSegment): string { throw makeError(); } - copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { throw makeError(); } - moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { throw makeError(); } - ensureDir(path: AbsoluteFsPath): void { throw makeError(); } - removeDeep(path: AbsoluteFsPath): void { throw makeError(); } - isCaseSensitive(): boolean { throw makeError(); } - resolve(...paths: string[]): AbsoluteFsPath { throw makeError(); } - dirname(file: T): T { throw makeError(); } - join(basePath: T, ...paths: string[]): T { throw makeError(); } - isRoot(path: AbsoluteFsPath): boolean { throw makeError(); } - isRooted(path: string): boolean { throw makeError(); } - relative(from: T, to: T): PathSegment { throw makeError(); } - basename(filePath: string, extension?: string): PathSegment { throw makeError(); } - realpath(filePath: AbsoluteFsPath): AbsoluteFsPath { throw makeError(); } - getDefaultLibLocation(): AbsoluteFsPath { throw makeError(); } - normalize(path: T): T { throw makeError(); } + exists(path: AbsoluteFsPath): boolean { + throw makeError(); + } + readFile(path: AbsoluteFsPath): string { + throw makeError(); + } + writeFile(path: AbsoluteFsPath, data: string, exclusive?: boolean): void { + throw makeError(); + } + removeFile(path: AbsoluteFsPath): void { + throw makeError(); + } + symlink(target: AbsoluteFsPath, path: AbsoluteFsPath): void { + throw makeError(); + } + readdir(path: AbsoluteFsPath): PathSegment[] { + throw makeError(); + } + lstat(path: AbsoluteFsPath): FileStats { + throw makeError(); + } + stat(path: AbsoluteFsPath): FileStats { + throw makeError(); + } + pwd(): AbsoluteFsPath { + throw makeError(); + } + chdir(path: AbsoluteFsPath): void { + throw makeError(); + } + extname(path: AbsoluteFsPath|PathSegment): string { + throw makeError(); + } + copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { + throw makeError(); + } + moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { + throw makeError(); + } + ensureDir(path: AbsoluteFsPath): void { + throw makeError(); + } + removeDeep(path: AbsoluteFsPath): void { + throw makeError(); + } + isCaseSensitive(): boolean { + throw makeError(); + } + resolve(...paths: string[]): AbsoluteFsPath { + throw makeError(); + } + dirname(file: T): T { + throw makeError(); + } + join(basePath: T, ...paths: string[]): T { + throw makeError(); + } + isRoot(path: AbsoluteFsPath): boolean { + throw makeError(); + } + isRooted(path: string): boolean { + throw makeError(); + } + relative(from: T, to: T): PathSegment { + throw makeError(); + } + basename(filePath: string, extension?: string): PathSegment { + throw makeError(); + } + realpath(filePath: AbsoluteFsPath): AbsoluteFsPath { + throw makeError(); + } + getDefaultLibLocation(): AbsoluteFsPath { + throw makeError(); + } + normalize(path: T): T { + throw makeError(); + } } function makeError() { diff --git a/packages/compiler-cli/src/ngtsc/file_system/src/logical.ts b/packages/compiler-cli/src/ngtsc/file_system/src/logical.ts index 312cd0d6d4..15b5c24ae7 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/src/logical.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/src/logical.ts @@ -91,7 +91,7 @@ export class LogicalFileSystem { } this.cache.set(physicalFile, logicalFile); } - return this.cache.get(physicalFile) !; + return this.cache.get(physicalFile)!; } private createLogicalProjectPath(file: AbsoluteFsPath, rootDir: AbsoluteFsPath): diff --git a/packages/compiler-cli/src/ngtsc/file_system/src/node_js_file_system.ts b/packages/compiler-cli/src/ngtsc/file_system/src/node_js_file_system.ts index b373e8e567..2a1a41a7b5 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/src/node_js_file_system.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/src/node_js_file_system.ts @@ -17,20 +17,42 @@ import {AbsoluteFsPath, FileStats, FileSystem, PathSegment, PathString} from './ */ export class NodeJSFileSystem implements FileSystem { private _caseSensitive: boolean|undefined = undefined; - exists(path: AbsoluteFsPath): boolean { return fs.existsSync(path); } - readFile(path: AbsoluteFsPath): string { return fs.readFileSync(path, 'utf8'); } + exists(path: AbsoluteFsPath): boolean { + return fs.existsSync(path); + } + readFile(path: AbsoluteFsPath): string { + return fs.readFileSync(path, 'utf8'); + } writeFile(path: AbsoluteFsPath, data: string, exclusive: boolean = false): void { fs.writeFileSync(path, data, exclusive ? {flag: 'wx'} : undefined); } - removeFile(path: AbsoluteFsPath): void { fs.unlinkSync(path); } - symlink(target: AbsoluteFsPath, path: AbsoluteFsPath): void { fs.symlinkSync(target, path); } - readdir(path: AbsoluteFsPath): PathSegment[] { return fs.readdirSync(path) as PathSegment[]; } - lstat(path: AbsoluteFsPath): FileStats { return fs.lstatSync(path); } - stat(path: AbsoluteFsPath): FileStats { return fs.statSync(path); } - pwd(): AbsoluteFsPath { return this.normalize(process.cwd()) as AbsoluteFsPath; } - chdir(dir: AbsoluteFsPath): void { process.chdir(dir); } - copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { fs.copyFileSync(from, to); } - moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { fs.renameSync(from, to); } + removeFile(path: AbsoluteFsPath): void { + fs.unlinkSync(path); + } + symlink(target: AbsoluteFsPath, path: AbsoluteFsPath): void { + fs.symlinkSync(target, path); + } + readdir(path: AbsoluteFsPath): PathSegment[] { + return fs.readdirSync(path) as PathSegment[]; + } + lstat(path: AbsoluteFsPath): FileStats { + return fs.lstatSync(path); + } + stat(path: AbsoluteFsPath): FileStats { + return fs.statSync(path); + } + pwd(): AbsoluteFsPath { + return this.normalize(process.cwd()) as AbsoluteFsPath; + } + chdir(dir: AbsoluteFsPath): void { + process.chdir(dir); + } + copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { + fs.copyFileSync(from, to); + } + moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { + fs.renameSync(from, to); + } ensureDir(path: AbsoluteFsPath): void { const parents: AbsoluteFsPath[] = []; while (!this.isRoot(path) && !this.exists(path)) { @@ -38,10 +60,12 @@ export class NodeJSFileSystem implements FileSystem { path = this.dirname(path); } while (parents.length) { - this.safeMkdir(parents.pop() !); + this.safeMkdir(parents.pop()!); } } - removeDeep(path: AbsoluteFsPath): void { fsExtra.removeSync(path); } + removeDeep(path: AbsoluteFsPath): void { + fsExtra.removeSync(path); + } isCaseSensitive(): boolean { if (this._caseSensitive === undefined) { this._caseSensitive = this.exists(togglePathCase(__filename)); @@ -52,20 +76,30 @@ export class NodeJSFileSystem implements FileSystem { return this.normalize(p.resolve(...paths)) as AbsoluteFsPath; } - dirname(file: T): T { return this.normalize(p.dirname(file)) as T; } + dirname(file: T): T { + return this.normalize(p.dirname(file)) as T; + } join(basePath: T, ...paths: string[]): T { return this.normalize(p.join(basePath, ...paths)) as T; } - isRoot(path: AbsoluteFsPath): boolean { return this.dirname(path) === this.normalize(path); } - isRooted(path: string): boolean { return p.isAbsolute(path); } + isRoot(path: AbsoluteFsPath): boolean { + return this.dirname(path) === this.normalize(path); + } + isRooted(path: string): boolean { + return p.isAbsolute(path); + } relative(from: T, to: T): PathSegment { return relativeFrom(this.normalize(p.relative(from, to))); } basename(filePath: string, extension?: string): PathSegment { return p.basename(filePath, extension) as PathSegment; } - extname(path: AbsoluteFsPath|PathSegment): string { return p.extname(path); } - realpath(path: AbsoluteFsPath): AbsoluteFsPath { return this.resolve(fs.realpathSync(path)); } + extname(path: AbsoluteFsPath|PathSegment): string { + return p.extname(path); + } + realpath(path: AbsoluteFsPath): AbsoluteFsPath { + return this.resolve(fs.realpathSync(path)); + } getDefaultLibLocation(): AbsoluteFsPath { return this.resolve(require.resolve('typescript'), '..'); } diff --git a/packages/compiler-cli/src/ngtsc/file_system/src/types.ts b/packages/compiler-cli/src/ngtsc/file_system/src/types.ts index 520b41bead..365de3b851 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/src/types.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/src/types.ts @@ -12,7 +12,7 @@ * A `string` is not assignable to a `BrandedPath`, but a `BrandedPath` is assignable to a `string`. * Two `BrandedPath`s with different brands are not mutually assignable. */ -export type BrandedPath = string & { +export type BrandedPath = string&{ _brand: B; }; @@ -63,7 +63,7 @@ export interface FileSystem { normalize(path: T): T; } -export type PathString = string | AbsoluteFsPath | PathSegment; +export type PathString = string|AbsoluteFsPath|PathSegment; /** * Information about an object in the FileSystem. diff --git a/packages/compiler-cli/src/ngtsc/file_system/src/util.ts b/packages/compiler-cli/src/ngtsc/file_system/src/util.ts index be2863e9ac..41f6c2b391 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/src/util.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/src/util.ts @@ -28,8 +28,8 @@ export function stripExtension(path: string): string { export function getSourceFileOrError(program: ts.Program, fileName: AbsoluteFsPath): ts.SourceFile { const sf = program.getSourceFile(fileName); if (sf === undefined) { - throw new Error( - `Program does not contain "${fileName}" - available files are ${program.getSourceFiles().map(sf => sf.fileName).join(', ')}`); + throw new Error(`Program does not contain "${fileName}" - available files are ${ + program.getSourceFiles().map(sf => sf.fileName).join(', ')}`); } return sf; } diff --git a/packages/compiler-cli/src/ngtsc/file_system/test/helpers_spec.ts b/packages/compiler-cli/src/ngtsc/file_system/test/helpers_spec.ts index b14d44cc70..6cc36eee82 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/test/helpers_spec.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/test/helpers_spec.ts @@ -11,37 +11,49 @@ import {absoluteFrom, relativeFrom, setFileSystem} from '../src/helpers'; import {NodeJSFileSystem} from '../src/node_js_file_system'; describe('path types', () => { - beforeEach(() => { setFileSystem(new NodeJSFileSystem()); }); + beforeEach(() => { + setFileSystem(new NodeJSFileSystem()); + }); describe('absoluteFrom', () => { - it('should not throw when creating one from an absolute path', - () => { expect(() => absoluteFrom('/test.txt')).not.toThrow(); }); + it('should not throw when creating one from an absolute path', () => { + expect(() => absoluteFrom('/test.txt')).not.toThrow(); + }); if (os.platform() === 'win32') { - it('should not throw when creating one from a windows absolute path', - () => { expect(absoluteFrom('C:\\test.txt')).toEqual('C:/test.txt'); }); + it('should not throw when creating one from a windows absolute path', () => { + expect(absoluteFrom('C:\\test.txt')).toEqual('C:/test.txt'); + }); it('should not throw when creating one from a windows absolute path with POSIX separators', - () => { expect(absoluteFrom('C:/test.txt')).toEqual('C:/test.txt'); }); - it('should support windows drive letters', - () => { expect(absoluteFrom('D:\\foo\\test.txt')).toEqual('D:/foo/test.txt'); }); - it('should convert Windows path separators to POSIX separators', - () => { expect(absoluteFrom('C:\\foo\\test.txt')).toEqual('C:/foo/test.txt'); }); + () => { + expect(absoluteFrom('C:/test.txt')).toEqual('C:/test.txt'); + }); + it('should support windows drive letters', () => { + expect(absoluteFrom('D:\\foo\\test.txt')).toEqual('D:/foo/test.txt'); + }); + it('should convert Windows path separators to POSIX separators', () => { + expect(absoluteFrom('C:\\foo\\test.txt')).toEqual('C:/foo/test.txt'); + }); } - it('should throw when creating one from a non-absolute path', - () => { expect(() => absoluteFrom('test.txt')).toThrow(); }); + it('should throw when creating one from a non-absolute path', () => { + expect(() => absoluteFrom('test.txt')).toThrow(); + }); }); describe('relativeFrom', () => { - it('should not throw when creating one from a relative path', - () => { expect(() => relativeFrom('a/b/c.txt')).not.toThrow(); }); + it('should not throw when creating one from a relative path', () => { + expect(() => relativeFrom('a/b/c.txt')).not.toThrow(); + }); - it('should throw when creating one from an absolute path', - () => { expect(() => relativeFrom('/a/b/c.txt')).toThrow(); }); + it('should throw when creating one from an absolute path', () => { + expect(() => relativeFrom('/a/b/c.txt')).toThrow(); + }); if (os.platform() === 'win32') { - it('should throw when creating one from a Windows absolute path', - () => { expect(() => relativeFrom('C:/a/b/c.txt')).toThrow(); }); + it('should throw when creating one from a Windows absolute path', () => { + expect(() => relativeFrom('C:/a/b/c.txt')).toThrow(); + }); } }); }); diff --git a/packages/compiler-cli/src/ngtsc/file_system/testing/index.ts b/packages/compiler-cli/src/ngtsc/file_system/testing/index.ts index c41ab26f7b..b5fb9f1084 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/testing/index.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/testing/index.ts @@ -10,4 +10,4 @@ export {Folder, MockFileSystem} from './src/mock_file_system'; export {MockFileSystemNative} from './src/mock_file_system_native'; export {MockFileSystemPosix} from './src/mock_file_system_posix'; export {MockFileSystemWindows} from './src/mock_file_system_windows'; -export {TestFile, initMockFileSystem, runInEachFileSystem} from './src/test_helper'; +export {initMockFileSystem, runInEachFileSystem, TestFile} from './src/test_helper'; diff --git a/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts b/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts index cf3c625878..7731f5fea6 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts @@ -21,9 +21,13 @@ export abstract class MockFileSystem implements FileSystem { this._cwd = this.normalize(cwd); } - isCaseSensitive() { return this._isCaseSensitive; } + isCaseSensitive() { + return this._isCaseSensitive; + } - exists(path: AbsoluteFsPath): boolean { return this.findFromPath(path).entity !== null; } + exists(path: AbsoluteFsPath): boolean { + return this.findFromPath(path).entity !== null; + } readFile(path: AbsoluteFsPath): string { const {entity} = this.findFromPath(path); @@ -142,7 +146,9 @@ export abstract class MockFileSystem implements FileSystem { delete entity[basename]; } - isRoot(path: AbsoluteFsPath): boolean { return this.dirname(path) === path; } + isRoot(path: AbsoluteFsPath): boolean { + return this.dirname(path) === path; + } extname(path: AbsoluteFsPath|PathSegment): string { const match = /.+(\.[^.]*)$/.exec(path); @@ -159,9 +165,13 @@ export abstract class MockFileSystem implements FileSystem { } } - pwd(): AbsoluteFsPath { return this._cwd; } + pwd(): AbsoluteFsPath { + return this._cwd; + } - chdir(path: AbsoluteFsPath): void { this._cwd = this.normalize(path); } + chdir(path: AbsoluteFsPath): void { + this._cwd = this.normalize(path); + } getDefaultLibLocation(): AbsoluteFsPath { // Mimic the node module resolution algorithm and start in the current directory, then look @@ -201,8 +211,12 @@ export abstract class MockFileSystem implements FileSystem { abstract normalize(path: T): T; protected abstract splitPath(path: T): string[]; - dump(): Folder { return cloneFolder(this._fileTree); } - init(folder: Folder): void { this._fileTree = cloneFolder(folder); } + dump(): Folder { + return cloneFolder(this._fileTree); + } + init(folder: Folder): void { + this._fileTree = cloneFolder(folder); + } protected findFromPath(path: AbsoluteFsPath, options?: {followSymLinks: boolean}): FindResult { const followSymLinks = !!options && options.followSymLinks; @@ -215,7 +229,7 @@ export abstract class MockFileSystem implements FileSystem { segments[0] = ''; let current: Entity|null = this._fileTree; while (segments.length) { - current = current[segments.shift() !]; + current = current[segments.shift()!]; if (current === undefined) { return {path, entity: null}; } @@ -239,7 +253,7 @@ export abstract class MockFileSystem implements FileSystem { protected splitIntoFolderAndFile(path: AbsoluteFsPath): [AbsoluteFsPath, string] { const segments = this.splitPath(path); - const file = segments.pop() !; + const file = segments.pop()!; return [path.substring(0, path.length - file.length - 1) as AbsoluteFsPath, file]; } } @@ -247,8 +261,10 @@ export interface FindResult { path: AbsoluteFsPath; entity: Entity|null; } -export type Entity = Folder | File | SymLink; -export interface Folder { [pathSegments: string]: Entity; } +export type Entity = Folder|File|SymLink; +export interface Folder { + [pathSegments: string]: Entity; +} export type File = string; export class SymLink { constructor(public path: AbsoluteFsPath) {} @@ -256,24 +272,32 @@ export class SymLink { class MockFileStats implements FileStats { constructor(private entity: Entity) {} - isFile(): boolean { return isFile(this.entity); } - isDirectory(): boolean { return isFolder(this.entity); } - isSymbolicLink(): boolean { return isSymLink(this.entity); } + isFile(): boolean { + return isFile(this.entity); + } + isDirectory(): boolean { + return isFolder(this.entity); + } + isSymbolicLink(): boolean { + return isSymLink(this.entity); + } } class MockFileSystemError extends Error { - constructor(public code: string, public path: string, message: string) { super(message); } + constructor(public code: string, public path: string, message: string) { + super(message); + } } -export function isFile(item: Entity | null): item is File { +export function isFile(item: Entity|null): item is File { return typeof item === 'string'; } -export function isSymLink(item: Entity | null): item is SymLink { +export function isSymLink(item: Entity|null): item is SymLink { return item instanceof SymLink; } -export function isFolder(item: Entity | null): item is Folder { +export function isFolder(item: Entity|null): item is Folder { return item !== null && !isFile(item) && !isSymLink(item); } diff --git a/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_native.ts b/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_native.ts index f4539fb048..da97516e24 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_native.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_native.ts @@ -15,7 +15,9 @@ import {MockFileSystem} from './mock_file_system'; const isWindows = os.platform() === 'win32'; export class MockFileSystemNative extends MockFileSystem { - constructor(cwd: AbsoluteFsPath = '/' as AbsoluteFsPath) { super(undefined, cwd); } + constructor(cwd: AbsoluteFsPath = '/' as AbsoluteFsPath) { + super(undefined, cwd); + } // Delegate to the real NodeJSFileSystem for these path related methods @@ -36,9 +38,13 @@ export class MockFileSystemNative extends MockFileSystem { return NodeJSFileSystem.prototype.basename.call(this, filePath, extension); } - isCaseSensitive() { return NodeJSFileSystem.prototype.isCaseSensitive.call(this); } + isCaseSensitive() { + return NodeJSFileSystem.prototype.isCaseSensitive.call(this); + } - isRooted(path: string): boolean { return NodeJSFileSystem.prototype.isRooted.call(this, path); } + isRooted(path: string): boolean { + return NodeJSFileSystem.prototype.isRooted.call(this, path); + } isRoot(path: AbsoluteFsPath): boolean { return NodeJSFileSystem.prototype.isRoot.call(this, path); @@ -57,5 +63,7 @@ export class MockFileSystemNative extends MockFileSystem { return NodeJSFileSystem.prototype.normalize.call(this, path) as T; } - protected splitPath(path: string): string[] { return path.split(/[\\\/]/); } + protected splitPath(path: string): string[] { + return path.split(/[\\\/]/); + } } diff --git a/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_posix.ts b/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_posix.ts index 2778997240..74c528cad2 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_posix.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_posix.ts @@ -17,7 +17,9 @@ export class MockFileSystemPosix extends MockFileSystem { return this.normalize(resolved) as AbsoluteFsPath; } - dirname(file: T): T { return this.normalize(p.posix.dirname(file)) as T; } + dirname(file: T): T { + return this.normalize(p.posix.dirname(file)) as T; + } join(basePath: T, ...paths: string[]): T { return this.normalize(p.posix.join(basePath, ...paths)) as T; @@ -31,9 +33,13 @@ export class MockFileSystemPosix extends MockFileSystem { return p.posix.basename(filePath, extension) as PathSegment; } - isRooted(path: string): boolean { return path.startsWith('/'); } + isRooted(path: string): boolean { + return path.startsWith('/'); + } - protected splitPath(path: T): string[] { return path.split('/'); } + protected splitPath(path: T): string[] { + return path.split('/'); + } normalize(path: T): T { return path.replace(/^[a-z]:\//i, '/').replace(/\\/g, '/') as T; diff --git a/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_windows.ts b/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_windows.ts index 3ec01f4ed8..9cabd0a2b9 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_windows.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_windows.ts @@ -17,7 +17,9 @@ export class MockFileSystemWindows extends MockFileSystem { return this.normalize(resolved as AbsoluteFsPath); } - dirname(path: T): T { return this.normalize(p.win32.dirname(path) as T); } + dirname(path: T): T { + return this.normalize(p.win32.dirname(path) as T); + } join(basePath: T, ...paths: string[]): T { return this.normalize(p.win32.join(basePath, ...paths)) as T; @@ -31,9 +33,13 @@ export class MockFileSystemWindows extends MockFileSystem { return p.win32.basename(filePath, extension) as PathSegment; } - isRooted(path: string): boolean { return /^([A-Z]:)?([\\\/]|$)/i.test(path); } + isRooted(path: string): boolean { + return /^([A-Z]:)?([\\\/]|$)/i.test(path); + } - protected splitPath(path: T): string[] { return path.split(/[\\\/]/); } + protected splitPath(path: T): string[] { + return path.split(/[\\\/]/); + } normalize(path: T): T { return path.replace(/^[\/\\]/i, 'C:/').replace(/\\/g, '/') as T; diff --git a/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts b/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts index f9ff163cc9..2272d55b3b 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts @@ -47,7 +47,9 @@ function runInFileSystem(os: string, callback: (os: string) => void, error: bool afterEach(() => setFileSystem(new InvalidFileSystem())); callback(os); if (error) { - afterAll(() => { throw new Error(`runInFileSystem limited to ${os}, cannot pass`); }); + afterAll(() => { + throw new Error(`runInFileSystem limited to ${os}, cannot pass`); + }); } }); } @@ -125,14 +127,16 @@ function monkeyPatchTypeScript(os: string, fs: MockFileSystem) { return {files, directories}; } - function realPath(path: string): string { return fs.realpath(fs.resolve(path)); } + function realPath(path: string): string { + return fs.realpath(fs.resolve(path)); + } // Rather than completely re-implementing we are using the `ts.matchFiles` function, // which is internal to the `ts` namespace. const tsMatchFiles: ( - path: string, extensions: ReadonlyArray| undefined, - excludes: ReadonlyArray| undefined, includes: ReadonlyArray| undefined, - useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, + path: string, extensions: ReadonlyArray|undefined, + excludes: ReadonlyArray|undefined, includes: ReadonlyArray|undefined, + useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number|undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string) => string[] = (ts as any).matchFiles; diff --git a/packages/compiler-cli/src/ngtsc/imports/index.ts b/packages/compiler-cli/src/ngtsc/imports/index.ts index d43beaaa30..858f77c7e3 100644 --- a/packages/compiler-cli/src/ngtsc/imports/index.ts +++ b/packages/compiler-cli/src/ngtsc/imports/index.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -export {AliasStrategy, AliasingHost, PrivateExportAliasingHost, UnifiedModulesAliasingHost} from './src/alias'; +export {AliasingHost, AliasStrategy, PrivateExportAliasingHost, UnifiedModulesAliasingHost} from './src/alias'; export {ImportRewriter, NoopImportRewriter, R3SymbolsImportRewriter, validateAndRewriteCoreSymbol} from './src/core'; export {DefaultImportRecorder, DefaultImportTracker, NOOP_DEFAULT_IMPORT_RECORDER} from './src/default'; export {AbsoluteModuleStrategy, ImportFlags, LocalIdentifierStrategy, LogicalProjectStrategy, ReferenceEmitStrategy, ReferenceEmitter, RelativePathStrategy, UnifiedModulesStrategy} from './src/emitter'; diff --git a/packages/compiler-cli/src/ngtsc/imports/src/alias.ts b/packages/compiler-cli/src/ngtsc/imports/src/alias.ts index 6795705e2f..94b4a11444 100644 --- a/packages/compiler-cli/src/ngtsc/imports/src/alias.ts +++ b/packages/compiler-cli/src/ngtsc/imports/src/alias.ts @@ -10,7 +10,7 @@ import {Expression, ExternalExpr} from '@angular/compiler'; import * as ts from 'typescript'; import {UnifiedModulesHost} from '../../core/api'; -import {ClassDeclaration, ReflectionHost, isNamedClassDeclaration} from '../../reflection'; +import {ClassDeclaration, isNamedClassDeclaration, ReflectionHost} from '../../reflection'; import {ImportFlags, ReferenceEmitStrategy} from './emitter'; import {Reference} from './references'; @@ -203,7 +203,9 @@ export class PrivateExportAliasingHost implements AliasingHost { * * Thus, `getAliasIn` always returns `null`. */ - getAliasIn(): null { return null; } + getAliasIn(): null { + return null; + } } /** diff --git a/packages/compiler-cli/src/ngtsc/imports/src/core.ts b/packages/compiler-cli/src/ngtsc/imports/src/core.ts index a20b0c3097..027f814978 100644 --- a/packages/compiler-cli/src/ngtsc/imports/src/core.ts +++ b/packages/compiler-cli/src/ngtsc/imports/src/core.ts @@ -36,11 +36,17 @@ export interface ImportRewriter { * `ImportRewriter` that does no rewriting. */ export class NoopImportRewriter implements ImportRewriter { - shouldImportSymbol(symbol: string, specifier: string): boolean { return true; } + shouldImportSymbol(symbol: string, specifier: string): boolean { + return true; + } - rewriteSymbol(symbol: string, specifier: string): string { return symbol; } + rewriteSymbol(symbol: string, specifier: string): string { + return symbol; + } - rewriteSpecifier(specifier: string, inContextOfFile: string): string { return specifier; } + rewriteSpecifier(specifier: string, inContextOfFile: string): string { + return specifier; + } } /** @@ -70,7 +76,9 @@ const CORE_MODULE = '@angular/core'; export class R3SymbolsImportRewriter implements ImportRewriter { constructor(private r3SymbolsPath: string) {} - shouldImportSymbol(symbol: string, specifier: string): boolean { return true; } + shouldImportSymbol(symbol: string, specifier: string): boolean { + return true; + } rewriteSymbol(symbol: string, specifier: string): string { if (specifier !== CORE_MODULE) { @@ -89,8 +97,8 @@ export class R3SymbolsImportRewriter implements ImportRewriter { const relativePathToR3Symbols = relativePathBetween(inContextOfFile, this.r3SymbolsPath); if (relativePathToR3Symbols === null) { - throw new Error( - `Failed to rewrite import inside ${CORE_MODULE}: ${inContextOfFile} -> ${this.r3SymbolsPath}`); + throw new Error(`Failed to rewrite import inside ${CORE_MODULE}: ${inContextOfFile} -> ${ + this.r3SymbolsPath}`); } return relativePathToR3Symbols; @@ -101,5 +109,5 @@ export function validateAndRewriteCoreSymbol(name: string): string { if (!CORE_SUPPORTED_SYMBOLS.has(name)) { throw new Error(`Importing unexpected symbol ${name} while compiling ${CORE_MODULE}`); } - return CORE_SUPPORTED_SYMBOLS.get(name) !; + return CORE_SUPPORTED_SYMBOLS.get(name)!; } diff --git a/packages/compiler-cli/src/ngtsc/imports/src/default.ts b/packages/compiler-cli/src/ngtsc/imports/src/default.ts index aa36af2eb7..ae92d05eb6 100644 --- a/packages/compiler-cli/src/ngtsc/imports/src/default.ts +++ b/packages/compiler-cli/src/ngtsc/imports/src/default.ts @@ -1,10 +1,10 @@ /** -* @license -* Copyright Google Inc. 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 -*/ + * @license + * Copyright Google Inc. 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 * as ts from 'typescript'; @@ -96,7 +96,7 @@ export class DefaultImportTracker implements DefaultImportRecorder { if (!this.sourceFileToImportMap.has(sf)) { this.sourceFileToImportMap.set(sf, new Map()); } - this.sourceFileToImportMap.get(sf) !.set(id, decl); + this.sourceFileToImportMap.get(sf)!.set(id, decl); } recordUsedIdentifier(id: ts.Identifier): void { @@ -105,18 +105,18 @@ export class DefaultImportTracker implements DefaultImportRecorder { // The identifier's source file has no registered default imports at all. return; } - const identiferToDeclaration = this.sourceFileToImportMap.get(sf) !; + const identiferToDeclaration = this.sourceFileToImportMap.get(sf)!; if (!identiferToDeclaration.has(id)) { // The identifier isn't from a registered default import. return; } - const decl = identiferToDeclaration.get(id) !; + const decl = identiferToDeclaration.get(id)!; // Add the default import declaration to the set of used import declarations for the file. if (!this.sourceFileToUsedImports.has(sf)) { this.sourceFileToUsedImports.set(sf, new Set()); } - this.sourceFileToUsedImports.get(sf) !.add(decl); + this.sourceFileToUsedImports.get(sf)!.add(decl); } /** @@ -127,7 +127,9 @@ export class DefaultImportTracker implements DefaultImportRecorder { */ importPreservingTransformer(): ts.TransformerFactory { return (context: ts.TransformationContext) => { - return (sf: ts.SourceFile) => { return this.transformSourceFile(sf); }; + return (sf: ts.SourceFile) => { + return this.transformSourceFile(sf); + }; }; } @@ -142,7 +144,7 @@ export class DefaultImportTracker implements DefaultImportRecorder { } // There are declarations that need to be preserved. - const importsToPreserve = this.sourceFileToUsedImports.get(originalSf) !; + const importsToPreserve = this.sourceFileToUsedImports.get(originalSf)!; // Generate a new statement list which preserves any imports present in `importsToPreserve`. const statements = sf.statements.map(stmt => { diff --git a/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts b/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts index 6515cf49aa..23206dcc26 100644 --- a/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts +++ b/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts @@ -9,7 +9,7 @@ import {Expression, ExternalExpr, ExternalReference, WrappedNodeExpr} from '@ang import * as ts from 'typescript'; import {UnifiedModulesHost} from '../../core/api'; -import {LogicalFileSystem, LogicalProjectPath, PathSegment, absoluteFromSourceFile, dirname, relative} from '../../file_system'; +import {absoluteFromSourceFile, dirname, LogicalFileSystem, LogicalProjectPath, PathSegment, relative} from '../../file_system'; import {stripExtension} from '../../file_system/src/util'; import {ReflectionHost} from '../../reflection'; import {getSourceFile, isDeclaration, isTypeDeclaration, nodeNameForError} from '../../util/src/typescript'; @@ -93,8 +93,8 @@ export class ReferenceEmitter { return emitted; } } - throw new Error( - `Unable to write a reference to ${nodeNameForError(ref.node)} in ${ref.node.getSourceFile().fileName} from ${context.fileName}`); + throw new Error(`Unable to write a reference to ${nodeNameForError(ref.node)} in ${ + ref.node.getSourceFile().fileName} from ${context.fileName}`); } } @@ -149,11 +149,11 @@ export class AbsoluteModuleStrategy implements ReferenceEmitStrategy { return null; } else if (!isDeclaration(ref.node)) { // It's not possible to import something which isn't a declaration. - throw new Error( - `Debug assert: unable to import a Reference to non-declaration of type ${ts.SyntaxKind[ref.node.kind]}.`); + throw new Error(`Debug assert: unable to import a Reference to non-declaration of type ${ + ts.SyntaxKind[ref.node.kind]}.`); } else if ((importFlags & ImportFlags.AllowTypeImports) === 0 && isTypeDeclaration(ref.node)) { - throw new Error( - `Importing a type-only declaration of type ${ts.SyntaxKind[ref.node.kind]} in a value position is not allowed.`); + throw new Error(`Importing a type-only declaration of type ${ + ts.SyntaxKind[ref.node.kind]} in a value position is not allowed.`); } // Try to find the exported name of the declaration, if one is available. @@ -162,8 +162,9 @@ export class AbsoluteModuleStrategy implements ReferenceEmitStrategy { if (symbolName === null) { // TODO(alxhub): make this error a ts.Diagnostic pointing at whatever caused this import to be // triggered. - throw new Error( - `Symbol ${ref.debugName} declared in ${getSourceFile(ref.node).fileName} is not exported from ${specifier} (import into ${context.fileName})`); + throw new Error(`Symbol ${ref.debugName} declared in ${ + getSourceFile(ref.node).fileName} is not exported from ${specifier} (import into ${ + context.fileName})`); } return new ExternalExpr(new ExternalReference(specifier, symbolName)); @@ -173,7 +174,7 @@ export class AbsoluteModuleStrategy implements ReferenceEmitStrategy { |null { const exports = this.getExportsOfModule(moduleName, fromFile); if (exports !== null && exports.has(target)) { - return exports.get(target) !; + return exports.get(target)!; } else { return null; } @@ -184,7 +185,7 @@ export class AbsoluteModuleStrategy implements ReferenceEmitStrategy { if (!this.moduleExportsCache.has(moduleName)) { this.moduleExportsCache.set(moduleName, this.enumerateExportsOfModule(moduleName, fromFile)); } - return this.moduleExportsCache.get(moduleName) !; + return this.moduleExportsCache.get(moduleName)!; } protected enumerateExportsOfModule(specifier: string, fromFile: string): diff --git a/packages/compiler-cli/src/ngtsc/imports/src/references.ts b/packages/compiler-cli/src/ngtsc/imports/src/references.ts index 8b1df442cc..f6150394b3 100644 --- a/packages/compiler-cli/src/ngtsc/imports/src/references.ts +++ b/packages/compiler-cli/src/ngtsc/imports/src/references.ts @@ -80,7 +80,9 @@ export class Reference { * * See `bestGuessOwningModule`. */ - get hasOwningModuleGuess(): boolean { return this.bestGuessOwningModule !== null; } + get hasOwningModuleGuess(): boolean { + return this.bestGuessOwningModule !== null; + } /** * A name for the node, if one is available. @@ -93,14 +95,18 @@ export class Reference { return id !== null ? id.text : null; } - get alias(): Expression|null { return this._alias; } + get alias(): Expression|null { + return this._alias; + } /** * Record a `ts.Identifier` by which it's valid to refer to this node, within the context of this * `Reference`. */ - addIdentifier(identifier: ts.Identifier): void { this.identifiers.push(identifier); } + addIdentifier(identifier: ts.Identifier): void { + this.identifiers.push(identifier); + } /** * Get a `ts.Identifier` within this `Reference` that can be used to refer within the context of a diff --git a/packages/compiler-cli/src/ngtsc/imports/test/default_spec.ts b/packages/compiler-cli/src/ngtsc/imports/test/default_spec.ts index defa93505a..8cfc4bd1c7 100644 --- a/packages/compiler-cli/src/ngtsc/imports/test/default_spec.ts +++ b/packages/compiler-cli/src/ngtsc/imports/test/default_spec.ts @@ -39,7 +39,7 @@ runInEachFileSystem(() => { module: ts.ModuleKind.ES2015, }); const fooClause = getDeclaration(program, _('/test.ts'), 'Foo', ts.isImportClause); - const fooId = fooClause.name !; + const fooId = fooClause.name!; const fooDecl = fooClause.parent; const tracker = new DefaultImportTracker(); @@ -48,7 +48,7 @@ runInEachFileSystem(() => { program.emit(undefined, undefined, undefined, undefined, { before: [tracker.importPreservingTransformer()], }); - const testContents = host.readFile('/test.js') !; + const testContents = host.readFile('/test.js')!; expect(testContents).toContain(`import Foo from './dep';`); // The control should have the import elided. @@ -69,7 +69,7 @@ runInEachFileSystem(() => { module: ts.ModuleKind.CommonJS, }); const fooClause = getDeclaration(program, _('/test.ts'), 'Foo', ts.isImportClause); - const fooId = ts.updateIdentifier(fooClause.name !); + const fooId = ts.updateIdentifier(fooClause.name!); const fooDecl = fooClause.parent; const tracker = new DefaultImportTracker(); @@ -81,7 +81,7 @@ runInEachFileSystem(() => { tracker.importPreservingTransformer(), ], }); - const testContents = host.readFile('/test.js') !; + const testContents = host.readFile('/test.js')!; expect(testContents).toContain(`var dep_1 = require("./dep");`); expect(testContents).toContain(`var ref = dep_1["default"];`); }); diff --git a/packages/compiler-cli/src/ngtsc/imports/test/emitter_spec.ts b/packages/compiler-cli/src/ngtsc/imports/test/emitter_spec.ts index 567c6143fa..eb6bc7ac53 100644 --- a/packages/compiler-cli/src/ngtsc/imports/test/emitter_spec.ts +++ b/packages/compiler-cli/src/ngtsc/imports/test/emitter_spec.ts @@ -8,8 +8,8 @@ import {ExternalExpr} from '@angular/compiler'; import * as ts from 'typescript'; -import {LogicalFileSystem, absoluteFrom as _} from '../../file_system'; -import {TestFile, runInEachFileSystem} from '../../file_system/testing'; +import {absoluteFrom as _, LogicalFileSystem} from '../../file_system'; +import {runInEachFileSystem, TestFile} from '../../file_system/testing'; import {Declaration, TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {AbsoluteModuleStrategy, ImportFlags, LogicalProjectStrategy} from '../src/emitter'; @@ -42,7 +42,7 @@ runInEachFileSystem(() => { ]); const decl = getDeclaration(program, _('/node_modules/external.d.ts'), 'Foo', ts.isClassDeclaration); - const context = program.getSourceFile(_('/context.ts')) !; + const context = program.getSourceFile(_('/context.ts'))!; const reference = new Reference(decl); const emitted = strategy.emit(reference, context, ImportFlags.None); @@ -65,7 +65,7 @@ runInEachFileSystem(() => { ]); const decl = getDeclaration(program, _('/node_modules/external.d.ts'), 'Foo', ts.isClassDeclaration); - const context = program.getSourceFile(_('/context.ts')) !; + const context = program.getSourceFile(_('/context.ts'))!; const reference = new Reference(decl, { specifier: 'external', @@ -92,7 +92,7 @@ runInEachFileSystem(() => { ]); const decl = getDeclaration( program, _('/node_modules/external.d.ts'), 'Foo', ts.isInterfaceDeclaration); - const context = program.getSourceFile(_('/context.ts')) !; + const context = program.getSourceFile(_('/context.ts'))!; const reference = new Reference(decl, { specifier: 'external', @@ -116,7 +116,7 @@ runInEachFileSystem(() => { ]); const decl = getDeclaration( program, _('/node_modules/external.d.ts'), 'Foo', ts.isInterfaceDeclaration); - const context = program.getSourceFile(_('/context.ts')) !; + const context = program.getSourceFile(_('/context.ts'))!; const reference = new Reference(decl, {specifier: 'external', resolutionContext: context.fileName}); @@ -139,7 +139,9 @@ runInEachFileSystem(() => { return null; } const fakeExports = new Map(); - realExports.forEach((decl, name) => { fakeExports.set(`test${name}`, decl); }); + realExports.forEach((decl, name) => { + fakeExports.set(`test${name}`, decl); + }); return fakeExports; } } @@ -158,12 +160,12 @@ runInEachFileSystem(() => { const logicalFs = new LogicalFileSystem([_('/')]); const strategy = new LogicalProjectStrategy(new TestHost(checker), logicalFs); const decl = getDeclaration(program, _('/index.ts'), 'Foo', ts.isClassDeclaration); - const context = program.getSourceFile(_('/context.ts')) !; + const context = program.getSourceFile(_('/context.ts'))!; const ref = strategy.emit(new Reference(decl), context); expect(ref).not.toBeNull(); // Expect the prefixed name from the TestHost. - expect((ref !as ExternalExpr).value.name).toEqual('testFoo'); + expect((ref! as ExternalExpr).value.name).toEqual('testFoo'); }); }); }); diff --git a/packages/compiler-cli/src/ngtsc/incremental/api.ts b/packages/compiler-cli/src/ngtsc/incremental/api.ts index e987cd59ec..41c3f61bbf 100644 --- a/packages/compiler-cli/src/ngtsc/incremental/api.ts +++ b/packages/compiler-cli/src/ngtsc/incremental/api.ts @@ -25,7 +25,7 @@ export interface IncrementalBuild { /** * Tracks dependencies between source files or resources in the application. */ -export interface DependencyTracker { +export interface DependencyTracker { /** * Record that the file `from` depends on the file `on`. */ diff --git a/packages/compiler-cli/src/ngtsc/incremental/src/dependency_tracking.ts b/packages/compiler-cli/src/ngtsc/incremental/src/dependency_tracking.ts index fdd2f8ce1c..0c42a13824 100644 --- a/packages/compiler-cli/src/ngtsc/incremental/src/dependency_tracking.ts +++ b/packages/compiler-cli/src/ngtsc/incremental/src/dependency_tracking.ts @@ -23,11 +23,13 @@ import {DependencyTracker} from '../api'; * 2. One of its dependencies has physically changed. * 3. One of its resource dependencies has physically changed. */ -export class FileDependencyGraph implements +export class FileDependencyGraph implements DependencyTracker { private nodes = new Map(); - addDependency(from: T, on: T): void { this.nodeFor(from).dependsOn.add(on.fileName); } + addDependency(from: T, on: T): void { + this.nodeFor(from).dependsOn.add(on.fileName); + } addResourceDependency(from: T, resource: AbsoluteFsPath): void { this.nodeFor(from).usesResources.add(resource); @@ -103,7 +105,7 @@ export class FileDependencyGraph im usesResources: new Set(), }); } - return this.nodes.get(sf) !; + return this.nodes.get(sf)!; } } @@ -111,7 +113,7 @@ export class FileDependencyGraph im * Determine whether `sf` has logically changed, given its dependencies and the set of physically * changed files and resources. */ -function isLogicallyChanged( +function isLogicallyChanged( sf: T, node: FileNode, changedTsPaths: ReadonlySet, deletedTsPaths: ReadonlySet, changedResources: ReadonlySet): boolean { // A file is logically changed if it has physically changed itself (including being deleted). diff --git a/packages/compiler-cli/src/ngtsc/incremental/src/state.ts b/packages/compiler-cli/src/ngtsc/incremental/src/state.ts index 21f3ef680b..f2497cbb87 100644 --- a/packages/compiler-cli/src/ngtsc/incremental/src/state.ts +++ b/packages/compiler-cli/src/ngtsc/incremental/src/state.ts @@ -8,7 +8,7 @@ import * as ts from 'typescript'; -import {AbsoluteFsPath, absoluteFrom} from '../../file_system'; +import {absoluteFrom, AbsoluteFsPath} from '../../file_system'; import {ClassRecord, TraitCompiler} from '../../transform'; import {IncrementalBuild} from '../api'; @@ -194,9 +194,13 @@ export class IncrementalDriver implements IncrementalBuild { }; } - recordSuccessfulEmit(sf: ts.SourceFile): void { this.state.pendingEmit.delete(sf.fileName); } + recordSuccessfulEmit(sf: ts.SourceFile): void { + this.state.pendingEmit.delete(sf.fileName); + } - safeToSkipEmit(sf: ts.SourceFile): boolean { return !this.state.pendingEmit.has(sf.fileName); } + safeToSkipEmit(sf: ts.SourceFile): boolean { + return !this.state.pendingEmit.has(sf.fileName); + } priorWorkFor(sf: ts.SourceFile): ClassRecord[]|null { if (this.state.lastGood === null || this.logicalChanges === null) { @@ -212,7 +216,7 @@ export class IncrementalDriver implements IncrementalBuild { } } -type BuildState = PendingBuildState | AnalyzedBuildState; +type BuildState = PendingBuildState|AnalyzedBuildState; enum BuildStateKind { Pending, diff --git a/packages/compiler-cli/src/ngtsc/indexer/src/api.ts b/packages/compiler-cli/src/ngtsc/indexer/src/api.ts index 2f6095d499..0227717709 100644 --- a/packages/compiler-cli/src/ngtsc/indexer/src/api.ts +++ b/packages/compiler-cli/src/ngtsc/indexer/src/api.ts @@ -43,13 +43,19 @@ interface ExpressionIdentifier extends TemplateIdentifier { } /** Describes a property accessed in a template. */ -export interface PropertyIdentifier extends ExpressionIdentifier { kind: IdentifierKind.Property; } +export interface PropertyIdentifier extends ExpressionIdentifier { + kind: IdentifierKind.Property; +} /** Describes a method accessed in a template. */ -export interface MethodIdentifier extends ExpressionIdentifier { kind: IdentifierKind.Method; } +export interface MethodIdentifier extends ExpressionIdentifier { + kind: IdentifierKind.Method; +} /** Describes an element attribute in a template. */ -export interface AttributeIdentifier extends TemplateIdentifier { kind: IdentifierKind.Attribute; } +export interface AttributeIdentifier extends TemplateIdentifier { + kind: IdentifierKind.Attribute; +} /** A reference to a directive node and its selector. */ interface DirectiveReference { @@ -85,7 +91,7 @@ export interface ReferenceIdentifier extends TemplateIdentifier { /** The target of this reference. If the target is not known, this is `null`. */ target: { /** The template AST node that the reference targets. */ - node: ElementIdentifier | TemplateIdentifier; + node: ElementIdentifier|TemplateIdentifier; /** * The directive on `node` that the reference targets. If no directive is targeted, this is @@ -96,14 +102,16 @@ export interface ReferenceIdentifier extends TemplateIdentifier { } /** Describes a template variable like "foo" in `
`. */ -export interface VariableIdentifier extends TemplateIdentifier { kind: IdentifierKind.Variable; } +export interface VariableIdentifier extends TemplateIdentifier { + kind: IdentifierKind.Variable; +} /** * Identifiers recorded at the top level of the template, without any context about the HTML nodes * they were discovered in. */ -export type TopLevelIdentifier = PropertyIdentifier | MethodIdentifier | ElementIdentifier | - TemplateNodeIdentifier | ReferenceIdentifier | VariableIdentifier; +export type TopLevelIdentifier = PropertyIdentifier|MethodIdentifier|ElementIdentifier| + TemplateNodeIdentifier|ReferenceIdentifier|VariableIdentifier; /** * Describes the absolute byte offsets of a text anchor in a source code. diff --git a/packages/compiler-cli/src/ngtsc/indexer/src/context.ts b/packages/compiler-cli/src/ngtsc/indexer/src/context.ts index 1881ec01f0..c4c5801c65 100644 --- a/packages/compiler-cli/src/ngtsc/indexer/src/context.ts +++ b/packages/compiler-cli/src/ngtsc/indexer/src/context.ts @@ -56,5 +56,7 @@ export class IndexingContext { /** * Adds a component to the context. */ - addComponent(info: ComponentInfo) { this.components.add(info); } + addComponent(info: ComponentInfo) { + this.components.add(info); + } } diff --git a/packages/compiler-cli/src/ngtsc/indexer/src/template.ts b/packages/compiler-cli/src/ngtsc/indexer/src/template.ts index 84d32411e9..f0b2eacf18 100644 --- a/packages/compiler-cli/src/ngtsc/indexer/src/template.ts +++ b/packages/compiler-cli/src/ngtsc/indexer/src/template.ts @@ -18,9 +18,9 @@ interface HTMLNode extends TmplAstNode { name?: string; } -type ExpressionIdentifier = PropertyIdentifier | MethodIdentifier; -type TmplTarget = TmplAstReference | TmplAstVariable; -type TargetIdentifier = ReferenceIdentifier | VariableIdentifier; +type ExpressionIdentifier = PropertyIdentifier|MethodIdentifier; +type TmplTarget = TmplAstReference|TmplAstVariable; +type TargetIdentifier = ReferenceIdentifier|VariableIdentifier; type TargetIdentifierMap = Map; /** @@ -62,7 +62,9 @@ class ExpressionVisitor extends RecursiveAstVisitor { return visitor.identifiers; } - visit(ast: AST) { ast.visit(this); } + visit(ast: AST) { + ast.visit(this); + } visitMethodCall(ast: MethodCall, context: {}) { this.visitIdentifier(ast, IdentifierKind.Method); @@ -144,16 +146,22 @@ class TemplateVisitor extends TmplAstRecursiveVisitor { * * @param boundTemplate bound template target */ - constructor(private boundTemplate: BoundTarget) { super(); } + constructor(private boundTemplate: BoundTarget) { + super(); + } /** * Visits a node in the template. * * @param node node to visit */ - visit(node: HTMLNode) { node.visit(this); } + visit(node: HTMLNode) { + node.visit(this); + } - visitAll(nodes: TmplAstNode[]) { nodes.forEach(node => this.visit(node)); } + visitAll(nodes: TmplAstNode[]) { + nodes.forEach(node => this.visit(node)); + } /** * Add an identifier for an HTML element and visit its children recursively. @@ -204,8 +212,12 @@ class TemplateVisitor extends TmplAstRecursiveVisitor { this.targetToIdentifier.bind(this)); identifiers.forEach(id => this.identifiers.add(id)); } - visitBoundEvent(attribute: TmplAstBoundEvent) { this.visitExpression(attribute.handler); } - visitBoundText(text: TmplAstBoundText) { this.visitExpression(text.value); } + visitBoundEvent(attribute: TmplAstBoundEvent) { + this.visitExpression(attribute.handler); + } + visitBoundText(text: TmplAstBoundText) { + this.visitExpression(text.value); + } visitReference(reference: TmplAstReference) { const referenceIdentifer = this.targetToIdentifier(reference); @@ -222,7 +234,7 @@ class TemplateVisitor extends TmplAstRecursiveVisitor { |TemplateNodeIdentifier { // If this node has already been seen, return the cached result. if (this.elementAndTemplateIdentifierCache.has(node)) { - return this.elementAndTemplateIdentifierCache.get(node) !; + return this.elementAndTemplateIdentifierCache.get(node)!; } let name: string; @@ -254,7 +266,8 @@ class TemplateVisitor extends TmplAstRecursiveVisitor { const identifier = { name, - span: absoluteSpan, kind, + span: absoluteSpan, + kind, attributes: new Set(attributes), usedDirectives: new Set(usedDirectives.map(dir => { return { @@ -274,7 +287,7 @@ class TemplateVisitor extends TmplAstRecursiveVisitor { private targetToIdentifier(node: TmplAstReference|TmplAstVariable): TargetIdentifier { // If this node has already been seen, return the cached result. if (this.targetIdentifierCache.has(node)) { - return this.targetIdentifierCache.get(node) !; + return this.targetIdentifierCache.get(node)!; } const {name, sourceSpan} = node; @@ -304,7 +317,8 @@ class TemplateVisitor extends TmplAstRecursiveVisitor { identifier = { name, span, - kind: IdentifierKind.Reference, target, + kind: IdentifierKind.Reference, + target, }; } else { identifier = { diff --git a/packages/compiler-cli/src/ngtsc/indexer/test/context_spec.ts b/packages/compiler-cli/src/ngtsc/indexer/test/context_spec.ts index 070234844b..b95fb7502c 100644 --- a/packages/compiler-cli/src/ngtsc/indexer/test/context_spec.ts +++ b/packages/compiler-cli/src/ngtsc/indexer/test/context_spec.ts @@ -19,7 +19,8 @@ runInEachFileSystem(() => { context.addComponent({ declaration, - selector: 'c-selector', boundTemplate, + selector: 'c-selector', + boundTemplate, templateMeta: { isInline: false, file: new ParseSourceFile('
', util.getTestFilePath()), @@ -29,7 +30,8 @@ runInEachFileSystem(() => { expect(context.components).toEqual(new Set([ { declaration, - selector: 'c-selector', boundTemplate, + selector: 'c-selector', + boundTemplate, templateMeta: { isInline: false, file: new ParseSourceFile('
', util.getTestFilePath()), diff --git a/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts b/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts index 831de6640f..0f7b7e7aeb 100644 --- a/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts +++ b/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts @@ -219,11 +219,11 @@ runInEachFileSystem(() => { const refArr = Array.from(refs); expect(refArr).toEqual(jasmine.arrayContaining([{ - name: 'foo', - kind: IdentifierKind.Property, - span: new AbsoluteSourceSpan(20, 23), - target: null, - }] as TopLevelIdentifier[])); + name: 'foo', + kind: IdentifierKind.Property, + span: new AbsoluteSourceSpan(20, 23), + target: null, + }] as TopLevelIdentifier[])); }); it('should ignore property writes that are not implicitly received by the template', () => { @@ -314,12 +314,13 @@ runInEachFileSystem(() => { }; const refArray = Array.from(refs); - expect(refArray).toEqual(jasmine.arrayContaining([{ - name: 'foo', - kind: IdentifierKind.Reference, - span: new AbsoluteSourceSpan(6, 9), - target: {node: elementReference, directive: null}, - }] as TopLevelIdentifier[])); + expect(refArray).toEqual( + jasmine.arrayContaining([{ + name: 'foo', + kind: IdentifierKind.Reference, + span: new AbsoluteSourceSpan(6, 9), + target: {node: elementReference, directive: null}, + }] as TopLevelIdentifier[])); }); it('should discover nested references', () => { @@ -334,12 +335,13 @@ runInEachFileSystem(() => { }; const refArray = Array.from(refs); - expect(refArray).toEqual(jasmine.arrayContaining([{ - name: 'foo', - kind: IdentifierKind.Reference, - span: new AbsoluteSourceSpan(12, 15), - target: {node: elementReference, directive: null}, - }] as TopLevelIdentifier[])); + expect(refArray).toEqual( + jasmine.arrayContaining([{ + name: 'foo', + kind: IdentifierKind.Reference, + span: new AbsoluteSourceSpan(12, 15), + target: {node: elementReference, directive: null}, + }] as TopLevelIdentifier[])); }); it('should discover references to references', () => { @@ -409,14 +411,14 @@ runInEachFileSystem(() => { const refArr = Array.from(refs); let fooRef = refArr.find(id => id.name === 'foo'); expect(fooRef).toBeDefined(); - expect(fooRef !.kind).toBe(IdentifierKind.Reference); + expect(fooRef!.kind).toBe(IdentifierKind.Reference); fooRef = fooRef as ReferenceIdentifier; expect(fooRef.target).toBeDefined(); - expect(fooRef.target !.node.kind).toBe(IdentifierKind.Element); - expect(fooRef.target !.node.name).toBe('div'); - expect(fooRef.target !.node.span).toEqual(new AbsoluteSourceSpan(1, 4)); - expect(fooRef.target !.directive).toEqual(declB); + expect(fooRef.target!.node.kind).toBe(IdentifierKind.Element); + expect(fooRef.target!.node.name).toBe('div'); + expect(fooRef.target!.node.span).toEqual(new AbsoluteSourceSpan(1, 4)); + expect(fooRef.target!.directive).toEqual(declB); }); it('should discover references to references', () => { @@ -455,10 +457,10 @@ runInEachFileSystem(() => { const refArray = Array.from(refs); expect(refArray).toEqual(jasmine.arrayContaining([{ - name: 'foo', - kind: IdentifierKind.Variable, - span: new AbsoluteSourceSpan(17, 20), - }] as TopLevelIdentifier[])); + name: 'foo', + kind: IdentifierKind.Variable, + span: new AbsoluteSourceSpan(17, 20), + }] as TopLevelIdentifier[])); }); it('should discover variables with let- syntax', () => { @@ -467,10 +469,10 @@ runInEachFileSystem(() => { const refArray = Array.from(refs); expect(refArray).toEqual(jasmine.arrayContaining([{ - name: 'var', - kind: IdentifierKind.Variable, - span: new AbsoluteSourceSpan(17, 20), - }] as TopLevelIdentifier[])); + name: 'var', + kind: IdentifierKind.Variable, + span: new AbsoluteSourceSpan(17, 20), + }] as TopLevelIdentifier[])); }); it('should discover nested variables', () => { @@ -479,10 +481,10 @@ runInEachFileSystem(() => { const refArray = Array.from(refs); expect(refArray).toEqual(jasmine.arrayContaining([{ - name: 'foo', - kind: IdentifierKind.Variable, - span: new AbsoluteSourceSpan(23, 26), - }] as TopLevelIdentifier[])); + name: 'foo', + kind: IdentifierKind.Variable, + span: new AbsoluteSourceSpan(23, 26), + }] as TopLevelIdentifier[])); }); it('should discover references to variables', () => { diff --git a/packages/compiler-cli/src/ngtsc/indexer/test/transform_spec.ts b/packages/compiler-cli/src/ngtsc/indexer/test/transform_spec.ts index e77763f7c7..8dac5ec4b5 100644 --- a/packages/compiler-cli/src/ngtsc/indexer/test/transform_spec.ts +++ b/packages/compiler-cli/src/ngtsc/indexer/test/transform_spec.ts @@ -68,7 +68,7 @@ runInEachFileSystem(() => { const info = analysis.get(decl); expect(info).toBeDefined(); - expect(info !.template.file) + expect(info!.template.file) .toEqual(new ParseSourceFile('class C {}', util.getTestFilePath())); }); @@ -83,7 +83,7 @@ runInEachFileSystem(() => { const info = analysis.get(decl); expect(info).toBeDefined(); - expect(info !.template.file) + expect(info!.template.file) .toEqual(new ParseSourceFile('
{{foo}}
', util.getTestFilePath())); }); @@ -110,11 +110,11 @@ runInEachFileSystem(() => { const infoA = analysis.get(declA); expect(infoA).toBeDefined(); - expect(infoA !.template.usedComponents).toEqual(new Set([declB])); + expect(infoA!.template.usedComponents).toEqual(new Set([declB])); const infoB = analysis.get(declB); expect(infoB).toBeDefined(); - expect(infoB !.template.usedComponents).toEqual(new Set([declA])); + expect(infoB!.template.usedComponents).toEqual(new Set([declA])); }); }); }); diff --git a/packages/compiler-cli/src/ngtsc/indexer/test/util.ts b/packages/compiler-cli/src/ngtsc/indexer/test/util.ts index 55bf78fb19..67b200f39f 100644 --- a/packages/compiler-cli/src/ngtsc/indexer/test/util.ts +++ b/packages/compiler-cli/src/ngtsc/indexer/test/util.ts @@ -6,9 +6,10 @@ * found in the LICENSE file at https://angular.io/license */ -import {BoundTarget, CssSelector, ParseTemplateOptions, R3TargetBinder, SelectorMatcher, parseTemplate} from '@angular/compiler'; +import {BoundTarget, CssSelector, parseTemplate, ParseTemplateOptions, R3TargetBinder, SelectorMatcher} from '@angular/compiler'; import * as ts from 'typescript'; -import {AbsoluteFsPath, absoluteFrom} from '../../file_system'; + +import {absoluteFrom, AbsoluteFsPath} from '../../file_system'; import {Reference} from '../../imports'; import {ClassDeclaration} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; diff --git a/packages/compiler-cli/src/ngtsc/metadata/src/dts.ts b/packages/compiler-cli/src/ngtsc/metadata/src/dts.ts index 9e85145fd9..1f72300077 100644 --- a/packages/compiler-cli/src/ngtsc/metadata/src/dts.ts +++ b/packages/compiler-cli/src/ngtsc/metadata/src/dts.ts @@ -9,7 +9,7 @@ import * as ts from 'typescript'; import {Reference} from '../../imports'; -import {ClassDeclaration, ReflectionHost, isNamedClassDeclaration} from '../../reflection'; +import {ClassDeclaration, isNamedClassDeclaration, ReflectionHost} from '../../reflection'; import {DirectiveMeta, MetadataReader, NgModuleMeta, PipeMeta} from './api'; import {extractDirectiveGuards, extractReferencesFromType, readStringArrayType, readStringMapType, readStringType} from './util'; diff --git a/packages/compiler-cli/src/ngtsc/metadata/src/inheritance.ts b/packages/compiler-cli/src/ngtsc/metadata/src/inheritance.ts index c6265188d1..86d5f9588b 100644 --- a/packages/compiler-cli/src/ngtsc/metadata/src/inheritance.ts +++ b/packages/compiler-cli/src/ngtsc/metadata/src/inheritance.ts @@ -25,7 +25,7 @@ export function flattenInheritedDirectiveMetadata( throw new Error(`Metadata not found for directive: ${dir.debugName}`); } - let inputs: {[key: string]: string | [string, string]} = {}; + let inputs: {[key: string]: string|[string, string]} = {}; let outputs: {[key: string]: string} = {}; let coercedInputFields = new Set(); let isDynamic = false; diff --git a/packages/compiler-cli/src/ngtsc/metadata/src/registry.ts b/packages/compiler-cli/src/ngtsc/metadata/src/registry.ts index b1bd7a5ffb..585af36c7b 100644 --- a/packages/compiler-cli/src/ngtsc/metadata/src/registry.ts +++ b/packages/compiler-cli/src/ngtsc/metadata/src/registry.ts @@ -22,18 +22,24 @@ export class LocalMetadataRegistry implements MetadataRegistry, MetadataReader { private pipes = new Map(); getDirectiveMetadata(ref: Reference): DirectiveMeta|null { - return this.directives.has(ref.node) ? this.directives.get(ref.node) ! : null; + return this.directives.has(ref.node) ? this.directives.get(ref.node)! : null; } getNgModuleMetadata(ref: Reference): NgModuleMeta|null { - return this.ngModules.has(ref.node) ? this.ngModules.get(ref.node) ! : null; + return this.ngModules.has(ref.node) ? this.ngModules.get(ref.node)! : null; } getPipeMetadata(ref: Reference): PipeMeta|null { - return this.pipes.has(ref.node) ? this.pipes.get(ref.node) ! : null; + return this.pipes.has(ref.node) ? this.pipes.get(ref.node)! : null; } - registerDirectiveMetadata(meta: DirectiveMeta): void { this.directives.set(meta.ref.node, meta); } - registerNgModuleMetadata(meta: NgModuleMeta): void { this.ngModules.set(meta.ref.node, meta); } - registerPipeMetadata(meta: PipeMeta): void { this.pipes.set(meta.ref.node, meta); } + registerDirectiveMetadata(meta: DirectiveMeta): void { + this.directives.set(meta.ref.node, meta); + } + registerNgModuleMetadata(meta: NgModuleMeta): void { + this.ngModules.set(meta.ref.node, meta); + } + registerPipeMetadata(meta: PipeMeta): void { + this.pipes.set(meta.ref.node, meta); + } } /** @@ -70,7 +76,9 @@ export class InjectableClassRegistry { constructor(private host: ReflectionHost) {} - registerInjectable(declaration: ClassDeclaration): void { this.classes.add(declaration); } + registerInjectable(declaration: ClassDeclaration): void { + this.classes.add(declaration); + } isInjectable(declaration: ClassDeclaration): boolean { // Figure out whether the class is injectable based on the registered classes, otherwise diff --git a/packages/compiler-cli/src/ngtsc/metadata/src/util.ts b/packages/compiler-cli/src/ngtsc/metadata/src/util.ts index 48b6a3a4a9..c3fc520dd2 100644 --- a/packages/compiler-cli/src/ngtsc/metadata/src/util.ts +++ b/packages/compiler-cli/src/ngtsc/metadata/src/util.ts @@ -9,13 +9,13 @@ import * as ts from 'typescript'; import {Reference} from '../../imports'; -import {ClassDeclaration, ClassMember, ClassMemberKind, ReflectionHost, isNamedClassDeclaration, reflectTypeEntityToDeclaration} from '../../reflection'; +import {ClassDeclaration, ClassMember, ClassMemberKind, isNamedClassDeclaration, ReflectionHost, reflectTypeEntityToDeclaration} from '../../reflection'; import {nodeDebugInfo} from '../../util/src/typescript'; import {DirectiveMeta, MetadataReader, NgModuleMeta, PipeMeta, TemplateGuardMeta} from './api'; export function extractReferencesFromType( - checker: ts.TypeChecker, def: ts.TypeNode, ngModuleImportedFrom: string | null, + checker: ts.TypeChecker, def: ts.TypeNode, ngModuleImportedFrom: string|null, resolutionContext: string): Reference[] { if (!ts.isTupleTypeNode(def)) { return []; @@ -122,7 +122,7 @@ function extractTemplateGuard(member: ClassMember): TemplateGuardMeta|null { function extractCoercedInput(member: ClassMember): string|null { if (member.kind !== ClassMemberKind.Property || !member.name.startsWith('ngAcceptInputType_')) { - return null !; + return null!; } return afterUnderscore(member.name); } diff --git a/packages/compiler-cli/src/ngtsc/modulewithproviders/src/scanner.ts b/packages/compiler-cli/src/ngtsc/modulewithproviders/src/scanner.ts index 137151ed5b..52320a8793 100644 --- a/packages/compiler-cli/src/ngtsc/modulewithproviders/src/scanner.ts +++ b/packages/compiler-cli/src/ngtsc/modulewithproviders/src/scanner.ts @@ -13,7 +13,9 @@ import {ImportFlags, Reference, ReferenceEmitter} from '../../imports'; import {PartialEvaluator, ResolvedValueMap} from '../../partial_evaluator'; import {ReflectionHost} from '../../reflection'; -export interface DtsHandler { addTypeReplacement(node: ts.Declaration, type: Type): void; } +export interface DtsHandler { + addTypeReplacement(node: ts.Declaration, type: Type): void; +} export class ModuleWithProvidersScanner { constructor( diff --git a/packages/compiler-cli/src/ngtsc/perf/src/noop.ts b/packages/compiler-cli/src/ngtsc/perf/src/noop.ts index 01e4c9c680..8cd7c799c5 100644 --- a/packages/compiler-cli/src/ngtsc/perf/src/noop.ts +++ b/packages/compiler-cli/src/ngtsc/perf/src/noop.ts @@ -12,9 +12,11 @@ import {PerfRecorder} from './api'; export const NOOP_PERF_RECORDER: PerfRecorder = { enabled: false, - mark: (name: string, node: ts.SourceFile | ts.Declaration, category?: string, detail?: string): - void => {}, - start: (name: string, node: ts.SourceFile | ts.Declaration, category?: string, detail?: string): - number => { return 0;}, - stop: (span: number | false): void => {}, + mark: (name: string, node: ts.SourceFile|ts.Declaration, category?: string, detail?: string): + void => {}, + start: (name: string, node: ts.SourceFile|ts.Declaration, category?: string, detail?: string): + number => { + return 0; + }, + stop: (span: number|false): void => {}, }; diff --git a/packages/compiler-cli/src/ngtsc/perf/src/tracking.ts b/packages/compiler-cli/src/ngtsc/perf/src/tracking.ts index 0eb6251b91..80c4a8d32d 100644 --- a/packages/compiler-cli/src/ngtsc/perf/src/tracking.ts +++ b/packages/compiler-cli/src/ngtsc/perf/src/tracking.ts @@ -20,7 +20,9 @@ export class PerfTracker implements PerfRecorder { private constructor(private zeroTime: HrTime) {} - static zeroedToNow(): PerfTracker { return new PerfTracker(mark()); } + static zeroedToNow(): PerfTracker { + return new PerfTracker(mark()); + } mark(name: string, node?: ts.SourceFile|ts.Declaration, category?: string, detail?: string): void { @@ -73,7 +75,9 @@ export class PerfTracker implements PerfRecorder { return msg; } - asJson(): unknown { return this.log; } + asJson(): unknown { + return this.log; + } serializeToFile(target: string, host: ts.CompilerHost): void { const json = JSON.stringify(this.log, null, 2); diff --git a/packages/compiler-cli/src/ngtsc/program.ts b/packages/compiler-cli/src/ngtsc/program.ts index 84a3f75397..5e250ddc7b 100644 --- a/packages/compiler-cli/src/ngtsc/program.ts +++ b/packages/compiler-cli/src/ngtsc/program.ts @@ -77,7 +77,9 @@ export class NgtscProgram implements api.Program { new NgCompiler(this.host, options, this.tsProgram, reuseProgram, this.perfRecorder); } - getTsProgram(): ts.Program { return this.tsProgram; } + getTsProgram(): ts.Program { + return this.tsProgram; + } getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken| undefined): readonly ts.Diagnostic[] { @@ -137,8 +139,8 @@ export class NgtscProgram implements api.Program { } getNgSemanticDiagnostics( - fileName?: string|undefined, cancellationToken?: ts.CancellationToken| - undefined): readonly(ts.Diagnostic|api.Diagnostic)[] { + fileName?: string|undefined, cancellationToken?: ts.CancellationToken|undefined): + readonly(ts.Diagnostic|api.Diagnostic)[] { let sf: ts.SourceFile|undefined = undefined; if (fileName !== undefined) { sf = this.tsProgram.getSourceFile(fileName); @@ -161,14 +163,17 @@ export class NgtscProgram implements api.Program { * This is used by the Angular CLI to allow for spawning (async) child compilations for things * like SASS files used in `styleUrls`. */ - loadNgStructureAsync(): Promise { return this.compiler.analyzeAsync(); } + loadNgStructureAsync(): Promise { + return this.compiler.analyzeAsync(); + } listLazyRoutes(entryRoute?: string|undefined): api.LazyRoute[] { return this.compiler.listLazyRoutes(entryRoute); } emit(opts?: { - emitFlags?: api.EmitFlags | undefined; cancellationToken?: ts.CancellationToken | undefined; + emitFlags?: api.EmitFlags|undefined; + cancellationToken?: ts.CancellationToken | undefined; customTransformers?: api.CustomTransformers | undefined; emitCallback?: api.TsEmitCallback | undefined; mergeEmitResultsCallback?: api.TsMergeEmitResultsCallback | undefined; @@ -179,8 +184,8 @@ export class NgtscProgram implements api.Program { const writeFile: ts.WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, - onError: ((message: string) => void) | undefined, - sourceFiles: ReadonlyArray| undefined) => { + onError: ((message: string) => void)|undefined, + sourceFiles: ReadonlyArray|undefined) => { if (sourceFiles !== undefined) { // Record successful writes for any `ts.SourceFile` (that's not a declaration file) // that's an input to this write. @@ -221,7 +226,8 @@ export class NgtscProgram implements api.Program { program: this.tsProgram, host: this.host, options: this.options, - emitOnlyDtsFiles: false, writeFile, + emitOnlyDtsFiles: false, + writeFile, customTransformers: { before: beforeTransforms, after: customTransforms && customTransforms.afterTs, @@ -257,11 +263,16 @@ export class NgtscProgram implements api.Program { } } -const defaultEmitCallback: api.TsEmitCallback = - ({program, targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, - customTransformers}) => - program.emit( - targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); +const defaultEmitCallback: api.TsEmitCallback = ({ + program, + targetSourceFile, + writeFile, + cancellationToken, + emitOnlyDtsFiles, + customTransformers +}) => + program.emit( + targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); function mergeEmitResults(emitResults: ts.EmitResult[]): ts.EmitResult { const diagnostics: ts.Diagnostic[] = []; diff --git a/packages/compiler-cli/src/ngtsc/reflection/src/host.ts b/packages/compiler-cli/src/ngtsc/reflection/src/host.ts index 6879769e16..6a5940d93c 100644 --- a/packages/compiler-cli/src/ngtsc/reflection/src/host.ts +++ b/packages/compiler-cli/src/ngtsc/reflection/src/host.ts @@ -12,7 +12,7 @@ import * as ts from 'typescript'; * Metadata extracted from an instance of a decorator on another declaration, or synthesized from * other information about a class. */ -export type Decorator = ConcreteDecorator | SyntheticDecorator; +export type Decorator = ConcreteDecorator|SyntheticDecorator; export interface BaseDecorator { /** @@ -28,11 +28,11 @@ export interface BaseDecorator { */ identifier: DecoratorIdentifier|null; - /** - * `Import` by which the decorator was brought into the module in which it was invoked, or `null` - * if the decorator was declared in the same module and not imported. - */ - import : Import | null; +/** + * `Import` by which the decorator was brought into the module in which it was invoked, or `null` + * if the decorator was declared in the same module and not imported. + */ +import: Import|null; /** * TypeScript reference to the decorator itself, or `null` if the decorator is synthesized (e.g. @@ -87,8 +87,8 @@ export const Decorator = { * A decorator is identified by either a simple identifier (e.g. `Decorator`) or, in some cases, * a namespaced property access (e.g. `core.Decorator`). */ -export type DecoratorIdentifier = ts.Identifier | NamespacedIdentifier; -export type NamespacedIdentifier = ts.PropertyAccessExpression & { +export type DecoratorIdentifier = ts.Identifier|NamespacedIdentifier; +export type NamespacedIdentifier = ts.PropertyAccessExpression&{ expression: ts.Identifier; name: ts.Identifier }; @@ -113,7 +113,7 @@ export function isDecoratorIdentifier(exp: ts.Expression): exp is DecoratorIdent * For `ReflectionHost` purposes, a class declaration should always have a `name` identifier, * because we need to be able to reference it in other parts of the program. */ -export type ClassDeclaration = T & {name: ts.Identifier}; +export type ClassDeclaration = T&{name: ts.Identifier}; /** * An enumeration of possible kinds of class members. @@ -241,8 +241,7 @@ export interface ClassMember { */ export type TypeValueReference = { local: true; expression: ts.Expression; defaultImportStatement: ts.ImportDeclaration | null; -} | -{ +}|{ local: false; name: string; moduleName: string; @@ -447,7 +446,7 @@ export interface InlineDeclaration extends BaseDeclaration { * downlevelings to a `ts.Expression` instead. */ export type Declaration = - ConcreteDeclaration| InlineDeclaration; + ConcreteDeclaration|InlineDeclaration; /** * Abstracts reflection operations on a TypeScript AST. diff --git a/packages/compiler-cli/src/ngtsc/reflection/src/type_to_value.ts b/packages/compiler-cli/src/ngtsc/reflection/src/type_to_value.ts index edcab882ab..ca930904d0 100644 --- a/packages/compiler-cli/src/ngtsc/reflection/src/type_to_value.ts +++ b/packages/compiler-cli/src/ngtsc/reflection/src/type_to_value.ts @@ -18,7 +18,7 @@ import {TypeValueReference} from './host'; * declaration, or if it is not possible to statically understand. */ export function typeToValue( - typeNode: ts.TypeNode | null, checker: ts.TypeChecker): TypeValueReference|null { + typeNode: ts.TypeNode|null, checker: ts.TypeChecker): TypeValueReference|null { // It's not possible to get a value expression if the parameter doesn't even have a type. if (typeNode === null || !ts.isTypeReferenceNode(typeNode)) { return null; @@ -95,7 +95,7 @@ export function typeNodeToValueExpr(node: ts.TypeNode): ts.Expression|null { * give the identifier name within the current file by which the import is known. */ function resolveTypeSymbols(typeRef: ts.TypeReferenceNode, checker: ts.TypeChecker): - {local: ts.Symbol, decl: ts.Symbol, importName: string | null}|null { + {local: ts.Symbol, decl: ts.Symbol, importName: string|null}|null { const typeName = typeRef.typeName; // typeRefSymbol is the ts.Symbol of the entire type reference. const typeRefSymbol: ts.Symbol|undefined = checker.getSymbolAtLocation(typeName); @@ -156,8 +156,8 @@ function isImportSource(node: ts.Declaration): node is(ts.ImportSpecifier | ts.N } function extractModuleAndNameFromImport( - node: ts.ImportSpecifier | ts.NamespaceImport | ts.ImportClause, - localName: string | null): {name: string, moduleName: string} { + node: ts.ImportSpecifier|ts.NamespaceImport|ts.ImportClause, + localName: string|null): {name: string, moduleName: string} { let name: string; let moduleSpecifier: ts.Expression; switch (node.kind) { diff --git a/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts b/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts index c96ae69a09..ec66a14014 100644 --- a/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts +++ b/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts @@ -8,7 +8,7 @@ import * as ts from 'typescript'; -import {ClassDeclaration, ClassMember, ClassMemberKind, CtorParameter, Declaration, Decorator, FunctionDefinition, Import, ReflectionHost, isDecoratorIdentifier} from './host'; +import {ClassDeclaration, ClassMember, ClassMemberKind, CtorParameter, Declaration, Decorator, FunctionDefinition, Import, isDecoratorIdentifier, ReflectionHost} from './host'; import {typeToValue} from './type_to_value'; /** @@ -76,8 +76,10 @@ export class TypeScriptReflectionHost implements ReflectionHost { return { name, - nameNode: node.name, typeValueReference, - typeNode: originalTypeNode, decorators, + nameNode: node.name, + typeValueReference, + typeNode: originalTypeNode, + decorators, }; }); } @@ -183,11 +185,17 @@ export class TypeScriptReflectionHost implements ReflectionHost { return declaration.initializer || null; } - getDtsDeclaration(_: ts.Declaration): ts.Declaration|null { return null; } + getDtsDeclaration(_: ts.Declaration): ts.Declaration|null { + return null; + } - getInternalNameOfClass(clazz: ClassDeclaration): ts.Identifier { return clazz.name; } + getInternalNameOfClass(clazz: ClassDeclaration): ts.Identifier { + return clazz.name; + } - getAdjacentNameOfClass(clazz: ClassDeclaration): ts.Identifier { return clazz.name; } + getAdjacentNameOfClass(clazz: ClassDeclaration): ts.Identifier { + return clazz.name; + } protected getDirectImportOfIdentifier(id: ts.Identifier): Import|null { const symbol = this.checker.getSymbolAtLocation(id); @@ -305,12 +313,14 @@ export class TypeScriptReflectionHost implements ReflectionHost { if (symbol.valueDeclaration !== undefined) { return { node: symbol.valueDeclaration, - known: null, viaModule, + known: null, + viaModule, }; } else if (symbol.declarations !== undefined && symbol.declarations.length > 0) { return { node: symbol.declarations[0], - known: null, viaModule, + known: null, + viaModule, }; } else { return null; @@ -342,7 +352,9 @@ export class TypeScriptReflectionHost implements ReflectionHost { return { name: decoratorIdentifier.text, identifier: decoratorExpr, - import: importDecl, node, args, + import: importDecl, + node, + args, }; } @@ -382,8 +394,14 @@ export class TypeScriptReflectionHost implements ReflectionHost { return { node, - implementation: node, kind, - type: node.type || null, name, nameNode, decorators, value, isStatic, + implementation: node, + kind, + type: node.type || null, + name, + nameNode, + decorators, + value, + isStatic, }; } } @@ -405,7 +423,7 @@ export function reflectIdentifierOfDeclaration(decl: ts.Declaration): ts.Identif } export function reflectTypeEntityToDeclaration( - type: ts.EntityName, checker: ts.TypeChecker): {node: ts.Declaration, from: string | null} { + type: ts.EntityName, checker: ts.TypeChecker): {node: ts.Declaration, from: string|null} { let realSymbol = checker.getSymbolAtLocation(type); if (realSymbol === undefined) { throw new Error(`Cannot resolve type entity ${type.getText()} to symbol`); @@ -434,8 +452,8 @@ export function reflectTypeEntityToDeclaration( } const decl = symbol.declarations[0]; if (ts.isNamespaceImport(decl)) { - const clause = decl.parent !; - const importDecl = clause.parent !; + const clause = decl.parent!; + const importDecl = clause.parent!; if (!ts.isStringLiteral(importDecl.moduleSpecifier)) { throw new Error(`Module specifier is not a string`); } @@ -552,7 +570,7 @@ function getFarLeftIdentifier(propertyAccess: ts.PropertyAccessExpression): ts.I * `NamespaceImport`. If not return `null`. */ function getContainingImportDeclaration(node: ts.Node): ts.ImportDeclaration|null { - return ts.isImportSpecifier(node) ? node.parent !.parent !.parent ! : + return ts.isImportSpecifier(node) ? node.parent!.parent!.parent! : ts.isNamespaceImport(node) ? node.parent.parent : null; } diff --git a/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts b/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts index 9427afb376..30eb1c551a 100644 --- a/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts +++ b/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts @@ -34,7 +34,7 @@ runInEachFileSystem(() => { const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration); const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); - const args = host.getConstructorParameters(clazz) !; + const args = host.getConstructorParameters(clazz)!; expect(args.length).toBe(1); expectParameter(args[0], 'bar', 'Bar'); }); @@ -63,7 +63,7 @@ runInEachFileSystem(() => { const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration); const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); - const args = host.getConstructorParameters(clazz) !; + const args = host.getConstructorParameters(clazz)!; expect(args.length).toBe(1); expectParameter(args[0], 'bar', 'Bar', 'dec', './dec'); }); @@ -92,7 +92,7 @@ runInEachFileSystem(() => { const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration); const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); - const args = host.getConstructorParameters(clazz) !; + const args = host.getConstructorParameters(clazz)!; expect(args.length).toBe(1); expectParameter(args[0], 'bar', 'Bar', 'dec', './dec'); }); @@ -120,7 +120,7 @@ runInEachFileSystem(() => { const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration); const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); - const args = host.getConstructorParameters(clazz) !; + const args = host.getConstructorParameters(clazz)!; expect(args.length).toBe(2); expectParameter(args[0], 'bar', {moduleName: './bar', name: 'Bar'}); expectParameter(args[1], 'otherBar', {moduleName: './bar', name: 'Bar'}); @@ -148,7 +148,7 @@ runInEachFileSystem(() => { const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration); const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); - const args = host.getConstructorParameters(clazz) !; + const args = host.getConstructorParameters(clazz)!; expect(args.length).toBe(1); expectParameter(args[0], 'bar', {moduleName: './bar', name: 'Bar'}); }); @@ -175,7 +175,7 @@ runInEachFileSystem(() => { const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration); const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); - const args = host.getConstructorParameters(clazz) !; + const args = host.getConstructorParameters(clazz)!; expect(args.length).toBe(1); const param = args[0].typeValueReference; if (param === null || !param.local) { @@ -207,7 +207,7 @@ runInEachFileSystem(() => { const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration); const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); - const args = host.getConstructorParameters(clazz) !; + const args = host.getConstructorParameters(clazz)!; expect(args.length).toBe(1); expectParameter(args[0], 'bar', {moduleName: './bar', name: 'Bar'}); }); @@ -228,12 +228,11 @@ runInEachFileSystem(() => { const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration); const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); - const args = host.getConstructorParameters(clazz) !; + const args = host.getConstructorParameters(clazz)!; expect(args.length).toBe(2); expectParameter(args[0], 'bar', 'Bar'); expectParameter(args[1], 'baz', 'Baz'); }); - }); @@ -330,9 +329,9 @@ runInEachFileSystem(() => { } else if (directTargetDecl === null) { return fail('No declaration found for DirectTarget'); } - expect(targetDecl.node !.getSourceFile().fileName) + expect(targetDecl.node!.getSourceFile().fileName) .toBe(_('/node_modules/absolute/index.ts')); - expect(ts.isClassDeclaration(targetDecl.node !)).toBe(true); + expect(ts.isClassDeclaration(targetDecl.node!)).toBe(true); expect(directTargetDecl.viaModule).toBe('absolute'); expect(directTargetDecl.node).toBe(targetDecl.node); }); @@ -415,9 +414,9 @@ runInEachFileSystem(() => { const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); const exportedDeclarations = - host.getExportsOfModule(program.getSourceFile(_('/entry.ts')) !); - expect(Array.from(exportedDeclarations !.keys())).toEqual(['foo', 'x', 'T', 'I', 'E']); - expect(Array.from(exportedDeclarations !.values()).map(v => v.viaModule)).toEqual([ + host.getExportsOfModule(program.getSourceFile(_('/entry.ts'))!); + expect(Array.from(exportedDeclarations!.keys())).toEqual(['foo', 'x', 'T', 'I', 'E']); + expect(Array.from(exportedDeclarations!.values()).map(v => v.viaModule)).toEqual([ null, null, null, null, null ]); }); @@ -440,11 +439,11 @@ runInEachFileSystem(() => { const checker = program.getTypeChecker(); const host = new TypeScriptReflectionHost(checker); const exportedDeclarations = - host.getExportsOfModule(program.getSourceFile(_('/entry.ts')) !); - expect(Array.from(exportedDeclarations !.keys())).toEqual([ + host.getExportsOfModule(program.getSourceFile(_('/entry.ts'))!); + expect(Array.from(exportedDeclarations!.keys())).toEqual([ 'Target1', 'AliasTarget', 'AliasTarget2', 'Target' ]); - expect(Array.from(exportedDeclarations !.values()).map(v => v.viaModule)).toEqual([ + expect(Array.from(exportedDeclarations!.values()).map(v => v.viaModule)).toEqual([ null, null, null, null ]); }); @@ -452,9 +451,9 @@ runInEachFileSystem(() => { }); function expectParameter( - param: CtorParameter, name: string, type?: string | {name: string, moduleName: string}, + param: CtorParameter, name: string, type?: string|{name: string, moduleName: string}, decorator?: string, decoratorFrom?: string): void { - expect(param.name !).toEqual(name); + expect(param.name!).toEqual(name); if (type === undefined) { expect(param.typeValueReference).toBeNull(); } else { @@ -467,21 +466,21 @@ runInEachFileSystem(() => { expect(param.typeValueReference.moduleName).toEqual(type.moduleName); expect(param.typeValueReference.name).toEqual(type.name); } else { - return fail( - `Mismatch between typeValueReference and expected type: ${param.name} / ${param.typeValueReference.local}`); + return fail(`Mismatch between typeValueReference and expected type: ${param.name} / ${ + param.typeValueReference.local}`); } } if (decorator !== undefined) { expect(param.decorators).not.toBeNull(); - expect(param.decorators !.length).toBeGreaterThan(0); - expect(param.decorators !.some( + expect(param.decorators!.length).toBeGreaterThan(0); + expect(param.decorators!.some( dec => dec.name === decorator && dec.import !== null && dec.import.from === decoratorFrom)) .toBe(true); } } - function argExpressionToString(name: ts.Node | null): string { + function argExpressionToString(name: ts.Node|null): string { if (name == null) { throw new Error('\'name\' argument can\'t be null'); } diff --git a/packages/compiler-cli/src/ngtsc/resource/src/loader.ts b/packages/compiler-cli/src/ngtsc/resource/src/loader.ts index 041b8f0594..67a698b534 100644 --- a/packages/compiler-cli/src/ngtsc/resource/src/loader.ts +++ b/packages/compiler-cli/src/ngtsc/resource/src/loader.ts @@ -10,7 +10,7 @@ import * as ts from 'typescript'; import {ResourceLoader} from '../../annotations'; import {ExtendedTsCompilerHost} from '../../core/api'; -import {AbsoluteFsPath, PathSegment, join} from '../../file_system'; +import {AbsoluteFsPath, join, PathSegment} from '../../file_system'; import {getRootDirs} from '../../util/src/typescript'; const CSS_PREPROCESSOR_EXT = /(\.scss|\.sass|\.less|\.styl)$/; @@ -101,7 +101,7 @@ export class HostResourceLoader implements ResourceLoader { */ load(resolvedUrl: string): string { if (this.cache.has(resolvedUrl)) { - return this.cache.get(resolvedUrl) !; + return this.cache.get(resolvedUrl)!; } const result = this.host.readResource ? this.host.readResource(resolvedUrl) : @@ -169,14 +169,15 @@ export class HostResourceLoader implements ResourceLoader { // but is marked @internal in TypeScript. See // https://github.com/Microsoft/TypeScript/issues/28770. type ResolvedModuleWithFailedLookupLocations = - ts.ResolvedModuleWithFailedLookupLocations & {failedLookupLocations: ReadonlyArray}; + ts.ResolvedModuleWithFailedLookupLocations&{failedLookupLocations: ReadonlyArray}; // clang-format off const failedLookup = ts.resolveModuleName(url + '.$ngresource$', fromFile, this.options, this.host) as ResolvedModuleWithFailedLookupLocations; // clang-format on if (failedLookup.failedLookupLocations === undefined) { throw new Error( - `Internal error: expected to find failedLookupLocations during resolution of resource '${url}' in context of ${fromFile}`); + `Internal error: expected to find failedLookupLocations during resolution of resource '${ + url}' in context of ${fromFile}`); } return failedLookup.failedLookupLocations diff --git a/packages/compiler-cli/src/ngtsc/routing/src/analyzer.ts b/packages/compiler-cli/src/ngtsc/routing/src/analyzer.ts index d6ef4b4020..f51ffb6d0d 100644 --- a/packages/compiler-cli/src/ngtsc/routing/src/analyzer.ts +++ b/packages/compiler-cli/src/ngtsc/routing/src/analyzer.ts @@ -12,7 +12,7 @@ import {ModuleResolver} from '../../imports'; import {PartialEvaluator} from '../../partial_evaluator'; import {scanForCandidateTransitiveModules, scanForRouteEntryPoints} from './lazy'; -import {RouterEntryPointManager, entryPointKeyFor} from './route'; +import {entryPointKeyFor, RouterEntryPointManager} from './route'; export interface NgModuleRawRouteData { sourceFile: ts.SourceFile; @@ -42,10 +42,13 @@ export class NgModuleRouteAnalyzer { if (this.modules.has(key)) { throw new Error(`Double route analyzing for '${key}'.`); } - this.modules.set( - key, { - sourceFile, moduleName, imports, exports, providers, - }); + this.modules.set(key, { + sourceFile, + moduleName, + imports, + exports, + providers, + }); } listLazyRoutes(entryModuleKey?: string|undefined): LazyRoute[] { @@ -63,7 +66,7 @@ export class NgModuleRouteAnalyzer { const scanRecursively = entryModuleKey !== undefined; while (pendingModuleKeys.length > 0) { - const key = pendingModuleKeys.pop() !; + const key = pendingModuleKeys.pop()!; if (scannedModuleKeys.has(key)) { continue; @@ -71,7 +74,7 @@ export class NgModuleRouteAnalyzer { scannedModuleKeys.add(key); } - const data = this.modules.get(key) !; + const data = this.modules.get(key)!; const entryPoints = scanForRouteEntryPoints( data.sourceFile, data.moduleName, data, this.entryPointManager, this.evaluator); diff --git a/packages/compiler-cli/src/ngtsc/routing/src/lazy.ts b/packages/compiler-cli/src/ngtsc/routing/src/lazy.ts index 3e1eb580c3..39b4ba334c 100644 --- a/packages/compiler-cli/src/ngtsc/routing/src/lazy.ts +++ b/packages/compiler-cli/src/ngtsc/routing/src/lazy.ts @@ -12,7 +12,7 @@ import {Reference} from '../../imports'; import {ForeignFunctionResolver, PartialEvaluator, ResolvedValue} from '../../partial_evaluator'; import {NgModuleRawRouteData} from './analyzer'; -import {RouterEntryPoint, RouterEntryPointManager, entryPointKeyFor} from './route'; +import {entryPointKeyFor, RouterEntryPoint, RouterEntryPointManager} from './route'; const ROUTES_MARKER = '__ngRoutesMarker__'; @@ -23,7 +23,7 @@ export interface LazyRouteEntry { } export function scanForCandidateTransitiveModules( - expr: ts.Expression | null, evaluator: PartialEvaluator): string[] { + expr: ts.Expression|null, evaluator: PartialEvaluator): string[] { if (expr === null) { return []; } @@ -38,7 +38,7 @@ export function scanForCandidateTransitiveModules( } } else if (entry instanceof Map) { if (entry.has('ngModule')) { - recursivelyAddModules(entry.get('ngModule') !); + recursivelyAddModules(entry.get('ngModule')!); } } else if ((entry instanceof Reference) && hasIdentifier(entry.node)) { const filePath = entry.node.getSourceFile().fileName; @@ -70,7 +70,9 @@ export function scanForRouteEntryPoints( const resolvedTo = entryPointManager.resolveLoadChildrenIdentifier(loadChildren, ngModule); if (resolvedTo !== null) { routes.push({ - loadChildren, from, resolvedTo, + loadChildren, + from, + resolvedTo, }); } } @@ -159,29 +161,27 @@ function scanForLazyRoutes(routes: ResolvedValue[]): string[] { const routerModuleFFR: ForeignFunctionResolver = function routerModuleFFR( ref: Reference, - args: ReadonlyArray): ts.Expression | - null { - if (!isMethodNodeReference(ref) || !ts.isClassDeclaration(ref.node.parent)) { - return null; - } else if ( - ref.bestGuessOwningModule === null || - ref.bestGuessOwningModule.specifier !== '@angular/router') { - return null; - } else if ( - ref.node.parent.name === undefined || ref.node.parent.name.text !== 'RouterModule') { - return null; - } else if ( - !ts.isIdentifier(ref.node.name) || - (ref.node.name.text !== 'forRoot' && ref.node.name.text !== 'forChild')) { - return null; - } + args: ReadonlyArray): ts.Expression|null { + if (!isMethodNodeReference(ref) || !ts.isClassDeclaration(ref.node.parent)) { + return null; + } else if ( + ref.bestGuessOwningModule === null || + ref.bestGuessOwningModule.specifier !== '@angular/router') { + return null; + } else if (ref.node.parent.name === undefined || ref.node.parent.name.text !== 'RouterModule') { + return null; + } else if ( + !ts.isIdentifier(ref.node.name) || + (ref.node.name.text !== 'forRoot' && ref.node.name.text !== 'forChild')) { + return null; + } - const routes = args[0]; - return ts.createObjectLiteral([ - ts.createPropertyAssignment(ROUTES_MARKER, ts.createTrue()), - ts.createPropertyAssignment('routes', routes), - ]); - }; + const routes = args[0]; + return ts.createObjectLiteral([ + ts.createPropertyAssignment(ROUTES_MARKER, ts.createTrue()), + ts.createPropertyAssignment('routes', routes), + ]); +}; function hasIdentifier(node: ts.Node): node is ts.Node&{name: ts.Identifier} { const node_ = node as ts.NamedDeclaration; diff --git a/packages/compiler-cli/src/ngtsc/routing/src/route.ts b/packages/compiler-cli/src/ngtsc/routing/src/route.ts index 2764b09de3..d6f11b9a6e 100644 --- a/packages/compiler-cli/src/ngtsc/routing/src/route.ts +++ b/packages/compiler-cli/src/ngtsc/routing/src/route.ts @@ -22,10 +22,14 @@ export abstract class RouterEntryPoint { class RouterEntryPointImpl implements RouterEntryPoint { constructor(readonly filePath: string, readonly moduleName: string) {} - get name(): string { return this.moduleName; } + get name(): string { + return this.moduleName; + } // For debugging purposes. - toString(): string { return `RouterEntryPoint(name: ${this.name}, filePath: ${this.filePath})`; } + toString(): string { + return `RouterEntryPoint(name: ${this.name}, filePath: ${this.filePath})`; + } } export class RouterEntryPointManager { @@ -51,7 +55,7 @@ export class RouterEntryPointManager { if (!this.map.has(key)) { this.map.set(key, new RouterEntryPointImpl(sf.fileName, moduleName)); } - return this.map.get(key) !; + return this.map.get(key)!; } } diff --git a/packages/compiler-cli/src/ngtsc/scope/src/dependency.ts b/packages/compiler-cli/src/ngtsc/scope/src/dependency.ts index ab441af285..94479f97b9 100644 --- a/packages/compiler-cli/src/ngtsc/scope/src/dependency.ts +++ b/packages/compiler-cli/src/ngtsc/scope/src/dependency.ts @@ -47,12 +47,12 @@ export class MetadataDtsModuleScopeResolver implements DtsModuleScopeResolver { const clazz = ref.node; const sourceFile = clazz.getSourceFile(); if (!sourceFile.isDeclarationFile) { - throw new Error( - `Debug error: DtsModuleScopeResolver.read(${ref.debugName} from ${sourceFile.fileName}), but not a .d.ts file`); + throw new Error(`Debug error: DtsModuleScopeResolver.read(${ref.debugName} from ${ + sourceFile.fileName}), but not a .d.ts file`); } if (this.cache.has(clazz)) { - return this.cache.get(clazz) !; + return this.cache.get(clazz)!; } // Build up the export scope - those directives and pipes made visible by this module. diff --git a/packages/compiler-cli/src/ngtsc/scope/src/local.ts b/packages/compiler-cli/src/ngtsc/scope/src/local.ts index ad505ed1b6..5cc992b4e9 100644 --- a/packages/compiler-cli/src/ngtsc/scope/src/local.ts +++ b/packages/compiler-cli/src/ngtsc/scope/src/local.ts @@ -143,7 +143,7 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop getScopeForComponent(clazz: ClassDeclaration): LocalModuleScope|null|'error' { const scope = !this.declarationToModule.has(clazz) ? null : - this.getScopeOfModule(this.declarationToModule.get(clazz) !.ngModule); + this.getScopeOfModule(this.declarationToModule.get(clazz)!.ngModule); return scope; } @@ -159,7 +159,7 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop return null; } - return Array.from(this.duplicateDeclarations.get(node) !.values()); + return Array.from(this.duplicateDeclarations.get(node)!.values()); } /** @@ -172,7 +172,7 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop */ getScopeOfModule(clazz: ClassDeclaration): LocalModuleScope|'error'|null { const scope = this.moduleToRef.has(clazz) ? - this.getScopeOfModuleReference(this.moduleToRef.get(clazz) !) : + this.getScopeOfModuleReference(this.moduleToRef.get(clazz)!) : null; // If the NgModule class is marked as tainted, consider it an error. if (this.taintedModules.has(clazz)) { @@ -193,7 +193,7 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop this.getScopeOfModule(clazz); if (this.scopeErrors.has(clazz)) { - return this.scopeErrors.get(clazz) !; + return this.scopeErrors.get(clazz)!; } else { return null; } @@ -218,21 +218,22 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop rawDeclarations: ts.Expression|null): void { const declData: DeclarationData = { ngModule, - ref: decl, rawDeclarations, + ref: decl, + rawDeclarations, }; // First, check for duplicate declarations of the same directive/pipe. if (this.duplicateDeclarations.has(decl.node)) { // This directive/pipe has already been identified as being duplicated. Add this module to the // map of modules for which a duplicate declaration exists. - this.duplicateDeclarations.get(decl.node) !.set(ngModule, declData); + this.duplicateDeclarations.get(decl.node)!.set(ngModule, declData); } else if ( this.declarationToModule.has(decl.node) && - this.declarationToModule.get(decl.node) !.ngModule !== ngModule) { + this.declarationToModule.get(decl.node)!.ngModule !== ngModule) { // This directive/pipe is already registered as declared in another module. Mark it as a // duplicate instead. const duplicateDeclMap = new Map(); - const firstDeclData = this.declarationToModule.get(decl.node) !; + const firstDeclData = this.declarationToModule.get(decl.node)!; // Mark both modules as tainted, since their declarations are missing a component. this.taintedModules.add(firstDeclData.ngModule); @@ -341,11 +342,13 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop } else { this.taintedModules.add(ngModule.ref.node); - const errorNode = decl.getOriginForDiagnostics(ngModule.rawDeclarations !); + const errorNode = decl.getOriginForDiagnostics(ngModule.rawDeclarations!); diagnostics.push(makeDiagnostic( ErrorCode.NGMODULE_INVALID_DECLARATION, errorNode, `The class '${decl.node.name.text}' is listed in the declarations ` + - `of the NgModule '${ngModule.ref.node.name.text}', but is not a directive, a component, or a pipe. ` + + `of the NgModule '${ + ngModule.ref.node.name + .text}', but is not a directive, a component, or a pipe. ` + `Either remove it from the NgModule's declarations, or add an appropriate Angular decorator.`, [{node: decl.node.name, messageText: `'${decl.node.name.text}' is declared here.`}])); continue; @@ -378,11 +381,11 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop } } else if (compilationDirectives.has(decl.node)) { // decl is a directive or component in the compilation scope of this NgModule. - const directive = compilationDirectives.get(decl.node) !; + const directive = compilationDirectives.get(decl.node)!; exportDirectives.set(decl.node, directive); } else if (compilationPipes.has(decl.node)) { // decl is a pipe in the compilation scope of this NgModule. - const pipe = compilationPipes.get(decl.node) !; + const pipe = compilationPipes.get(decl.node)!; exportPipes.set(decl.node, pipe); } else { // decl is an unknown export. @@ -433,7 +436,9 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop /** * Check whether a component requires remote scoping. */ - getRequiresRemoteScope(node: ClassDeclaration): boolean { return this.remoteScoping.has(node); } + getRequiresRemoteScope(node: ClassDeclaration): boolean { + return this.remoteScoping.has(node); + } /** * Set a component as requiring remote scoping. @@ -466,7 +471,8 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop ErrorCode.NGMODULE_INVALID_EXPORT; diagnostics.push(makeDiagnostic( code, identifierOfNode(ref.node) || ref.node, - `Appears in the NgModule.${type}s of ${nodeNameForError(ownerForErrors)}, but could not be resolved to an NgModule`)); + `Appears in the NgModule.${type}s of ${ + nodeNameForError(ownerForErrors)}, but could not be resolved to an NgModule`)); return undefined; } return this.dependencyScopeReader.resolve(ref); @@ -496,16 +502,16 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop return; } const isReExport = !declared.has(exportRef.node); - const exportName = this.aliasingHost !.maybeAliasSymbolAs( + const exportName = this.aliasingHost!.maybeAliasSymbolAs( exportRef, sourceFile, ngModule.ref.node.name.text, isReExport); if (exportName === null) { return; } if (!reexportMap.has(exportName)) { if (exportRef.alias && exportRef.alias instanceof ExternalExpr) { - reexports !.push({ - fromModule: exportRef.alias.value.moduleName !, - symbolName: exportRef.alias.value.name !, + reexports!.push({ + fromModule: exportRef.alias.value.moduleName!, + symbolName: exportRef.alias.value.name!, asAlias: exportName, }); } else { @@ -514,7 +520,7 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop expr.value.name === null) { throw new Error('Expected ExternalExpr'); } - reexports !.push({ + reexports!.push({ fromModule: expr.value.moduleName, symbolName: expr.value.name, asAlias: exportName, @@ -523,7 +529,7 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop reexportMap.set(exportName, exportRef); } else { // Another re-export already used this name. Produce a diagnostic. - const prevRef = reexportMap.get(exportName) !; + const prevRef = reexportMap.get(exportName)!; diagnostics.push(reexportCollision(ngModuleRef.node, prevRef, exportRef)); } }; @@ -548,12 +554,13 @@ export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScop */ function invalidRef( clazz: ts.Declaration, decl: Reference, - type: 'import' | 'export'): ts.Diagnostic { + type: 'import'|'export'): ts.Diagnostic { const code = type === 'import' ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT; const resolveTarget = type === 'import' ? 'NgModule' : 'NgModule, Component, Directive, or Pipe'; let message = - `Appears in the NgModule.${type}s of ${nodeNameForError(clazz)}, but could not be resolved to an ${resolveTarget} class.` + + `Appears in the NgModule.${type}s of ${ + nodeNameForError(clazz)}, but could not be resolved to an ${resolveTarget} class.` + '\n\n'; const library = decl.ownedByModuleGuess !== null ? ` (${decl.ownedByModuleGuess})` : ''; const sf = decl.node.getSourceFile(); @@ -573,8 +580,8 @@ function invalidRef( } else { // This is a monorepo style local dependency. Unfortunately these are too different to really // offer much more advice than this. - message += - `This likely means that the dependency${library} which declares ${decl.debugName} has not been processed correctly by ngcc.`; + message += `This likely means that the dependency${library} which declares ${ + decl.debugName} has not been processed correctly by ngcc.`; } return makeDiagnostic(code, identifierOfNode(decl.node) || decl.node, message); @@ -585,7 +592,7 @@ function invalidRef( */ function invalidTransitiveNgModuleRef( clazz: ts.Declaration, decl: Reference, - type: 'import' | 'export'): ts.Diagnostic { + type: 'import'|'export'): ts.Diagnostic { const code = type === 'import' ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT; return makeDiagnostic( @@ -600,7 +607,8 @@ function invalidTransitiveNgModuleRef( function invalidReexport(clazz: ts.Declaration, decl: Reference): ts.Diagnostic { return makeDiagnostic( ErrorCode.NGMODULE_INVALID_REEXPORT, identifierOfNode(decl.node) || decl.node, - `Present in the NgModule.exports of ${nodeNameForError(clazz)} but neither declared nor imported`); + `Present in the NgModule.exports of ${ + nodeNameForError(clazz)} but neither declared nor imported`); } /** @@ -609,11 +617,13 @@ function invalidReexport(clazz: ts.Declaration, decl: Reference) function reexportCollision( module: ClassDeclaration, refA: Reference, refB: Reference): ts.Diagnostic { - const childMessageText = - `This directive/pipe is part of the exports of '${module.name.text}' and shares the same name as another exported directive/pipe.`; + const childMessageText = `This directive/pipe is part of the exports of '${ + module.name.text}' and shares the same name as another exported directive/pipe.`; return makeDiagnostic( - ErrorCode.NGMODULE_REEXPORT_NAME_COLLISION, module.name, ` - There was a name collision between two classes named '${refA.node.name.text}', which are both part of the exports of '${module.name.text}'. + ErrorCode.NGMODULE_REEXPORT_NAME_COLLISION, module.name, + ` + There was a name collision between two classes named '${ + refA.node.name.text}', which are both part of the exports of '${module.name.text}'. Angular generates re-exports of an NgModule's exported directives/pipes from the module's source file in certain cases, using the declared name of the class. If two classes of the same name are exported, this automatic naming does not work. diff --git a/packages/compiler-cli/src/ngtsc/scope/test/dependency_spec.ts b/packages/compiler-cli/src/ngtsc/scope/test/dependency_spec.ts index 5e5e36522a..512d5bb966 100644 --- a/packages/compiler-cli/src/ngtsc/scope/test/dependency_spec.ts +++ b/packages/compiler-cli/src/ngtsc/scope/test/dependency_spec.ts @@ -22,7 +22,7 @@ const MODULE_FROM_NODE_MODULES_PATH = /.*node_modules\/(\w+)\/index\.d\.ts$/; const testHost: UnifiedModulesHost = { fileNameToModuleName: function(imported: string): string { - const res = MODULE_FROM_NODE_MODULES_PATH.exec(imported) !; + const res = MODULE_FROM_NODE_MODULES_PATH.exec(imported)!; return 'root/' + res[1]; } }; @@ -44,7 +44,7 @@ export declare type PipeMeta = never; * destructured to retrieve references to specific declared classes. */ function makeTestEnv( - modules: {[module: string]: string}, aliasGenerator: AliasingHost | null = null): { + modules: {[module: string]: string}, aliasGenerator: AliasingHost|null = null): { refs: {[name: string]: Reference}, resolver: MetadataDtsModuleScopeResolver, } { @@ -64,11 +64,11 @@ function makeTestEnv( // Resolver for the refs object. const get = (target: {}, name: string): Reference => { for (const sf of program.getSourceFiles()) { - const symbol = checker.getSymbolAtLocation(sf) !; - const exportedSymbol = symbol.exports !.get(name as ts.__String); + const symbol = checker.getSymbolAtLocation(sf)!; + const exportedSymbol = symbol.exports!.get(name as ts.__String); if (exportedSymbol !== undefined) { const decl = exportedSymbol.valueDeclaration as ts.ClassDeclaration; - const specifier = MODULE_FROM_NODE_MODULES_PATH.exec(sf.fileName) ![1]; + const specifier = MODULE_FROM_NODE_MODULES_PATH.exec(sf.fileName)![1]; return new Reference(decl, {specifier, resolutionContext: sf.fileName}); } } @@ -97,7 +97,7 @@ runInEachFileSystem(() => { ` }); const {Dir, Module} = refs; - const scope = resolver.resolve(Module) !; + const scope = resolver.resolve(Module)!; expect(scopeToRefs(scope)).toEqual([Dir]); }); @@ -118,7 +118,7 @@ runInEachFileSystem(() => { ` }); const {Dir, ModuleB} = refs; - const scope = resolver.resolve(ModuleB) !; + const scope = resolver.resolve(ModuleB)!; expect(scopeToRefs(scope)).toEqual([Dir]); }); @@ -142,7 +142,7 @@ runInEachFileSystem(() => { ` }); const {Dir, ModuleB} = refs; - const scope = resolver.resolve(ModuleB) !; + const scope = resolver.resolve(ModuleB)!; expect(scopeToRefs(scope)).toEqual([Dir]); // Explicitly verify that the directive has the correct owning module. @@ -186,7 +186,7 @@ runInEachFileSystem(() => { }, new UnifiedModulesAliasingHost(testHost)); const {ShallowModule} = refs; - const scope = resolver.resolve(ShallowModule) !; + const scope = resolver.resolve(ShallowModule)!; const [DeepDir, MiddleDir, ShallowDir] = scopeToRefs(scope); expect(getAlias(DeepDir)).toEqual({ moduleName: 'root/shallow', @@ -236,7 +236,7 @@ runInEachFileSystem(() => { }, new UnifiedModulesAliasingHost(testHost)); const {ShallowModule} = refs; - const scope = resolver.resolve(ShallowModule) !; + const scope = resolver.resolve(ShallowModule)!; const [DeepDir, MiddleDir, ShallowDir] = scopeToRefs(scope); expect(getAlias(DeepDir)).toEqual({ moduleName: 'root/shallow', @@ -269,7 +269,7 @@ runInEachFileSystem(() => { }, new UnifiedModulesAliasingHost(testHost)); const {DeepExportModule} = refs; - const scope = resolver.resolve(DeepExportModule) !; + const scope = resolver.resolve(DeepExportModule)!; const [DeepDir] = scopeToRefs(scope); expect(getAlias(DeepDir)).toBeNull(); }); @@ -278,7 +278,7 @@ runInEachFileSystem(() => { function scopeToRefs(scope: ExportScope): Reference[] { const directives = scope.exported.directives.map(dir => dir.ref); const pipes = scope.exported.pipes.map(pipe => pipe.ref); - return [...directives, ...pipes].sort((a, b) => a.debugName !.localeCompare(b.debugName !)); + return [...directives, ...pipes].sort((a, b) => a.debugName!.localeCompare(b.debugName!)); } function getAlias(ref: Reference): ExternalReference|null { diff --git a/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts b/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts index 05d06dda5e..a496754060 100644 --- a/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts +++ b/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts @@ -34,8 +34,8 @@ function registerFakeRefs(registry: MetadataRegistry): describe('LocalModuleScopeRegistry', () => { const refEmitter = new ReferenceEmitter([]); - let scopeRegistry !: LocalModuleScopeRegistry; - let metaRegistry !: MetadataRegistry; + let scopeRegistry!: LocalModuleScopeRegistry; + let metaRegistry!: MetadataRegistry; beforeEach(() => { const localRegistry = new LocalMetadataRegistry(); @@ -230,7 +230,7 @@ describe('LocalModuleScopeRegistry', () => { }); function fakeDirective(ref: Reference): DirectiveMeta { - const name = ref.debugName !; + const name = ref.debugName!; return { ref, name, @@ -248,16 +248,18 @@ function fakeDirective(ref: Reference): DirectiveMeta { } function fakePipe(ref: Reference): PipeMeta { - const name = ref.debugName !; + const name = ref.debugName!; return {ref, name}; } class MockDtsModuleScopeResolver implements DtsModuleScopeResolver { - resolve(ref: Reference): null { return null; } + resolve(ref: Reference): null { + return null; + } } function scopeToRefs(scopeData: ScopeData): Reference[] { const directives = scopeData.directives.map(dir => dir.ref); const pipes = scopeData.pipes.map(pipe => pipe.ref); - return [...directives, ...pipes].sort((a, b) => a.debugName !.localeCompare(b.debugName !)); + return [...directives, ...pipes].sort((a, b) => a.debugName!.localeCompare(b.debugName!)); } diff --git a/packages/compiler-cli/src/ngtsc/shims/src/factory_generator.ts b/packages/compiler-cli/src/ngtsc/shims/src/factory_generator.ts index 426687636c..4bca52c413 100644 --- a/packages/compiler-cli/src/ngtsc/shims/src/factory_generator.ts +++ b/packages/compiler-cli/src/ngtsc/shims/src/factory_generator.ts @@ -7,7 +7,7 @@ */ import * as ts from 'typescript'; -import {AbsoluteFsPath, absoluteFrom, basename} from '../../file_system'; +import {absoluteFrom, AbsoluteFsPath, basename} from '../../file_system'; import {ImportRewriter} from '../../imports'; import {isNonDeclarationTsPath} from '../../util/src/typescript'; @@ -24,15 +24,21 @@ const STRIP_NG_FACTORY = /(.*)NgFactory$/; export class FactoryGenerator implements ShimGenerator { private constructor(private map: Map) {} - get factoryFileMap(): Map { return this.map; } + get factoryFileMap(): Map { + return this.map; + } - get factoryFileNames(): AbsoluteFsPath[] { return Array.from(this.map.keys()); } + get factoryFileNames(): AbsoluteFsPath[] { + return Array.from(this.map.keys()); + } - recognize(fileName: AbsoluteFsPath): boolean { return this.map.has(fileName); } + recognize(fileName: AbsoluteFsPath): boolean { + return this.map.has(fileName); + } generate(genFilePath: AbsoluteFsPath, readFile: (fileName: string) => ts.SourceFile | null): ts.SourceFile|null { - const originalPath = this.map.get(genFilePath) !; + const originalPath = this.map.get(genFilePath)!; const original = readFile(originalPath); if (original === null) { return null; @@ -53,7 +59,7 @@ export class FactoryGenerator implements ShimGenerator { decl => isExported(decl) && decl.decorators !== undefined && decl.name !== undefined) // Grab the symbol name. - .map(decl => decl.name !.text); + .map(decl => decl.name!.text); let sourceText = ''; @@ -71,8 +77,8 @@ export class FactoryGenerator implements ShimGenerator { // This will encompass a lot of symbols which don't need factories, but that's okay // because it won't miss any that do. const varLines = symbolNames.map( - name => - `export const ${name}NgFactory: i0.ɵNgModuleFactory = new i0.ɵNgModuleFactory(${name});`); + name => `export const ${ + name}NgFactory: i0.ɵNgModuleFactory = new i0.ɵNgModuleFactory(${name});`); sourceText += [ // This might be incorrect if the current package being compiled is Angular core, but it's // okay to leave in at type checking time. TypeScript can handle this reference via its path @@ -136,7 +142,7 @@ function transformFactorySourceFile( return file; } - const {moduleSymbolNames, sourceFilePath} = factoryMap.get(file.fileName) !; + const {moduleSymbolNames, sourceFilePath} = factoryMap.get(file.fileName)!; file = ts.getMutableClone(file); diff --git a/packages/compiler-cli/src/ngtsc/shims/src/factory_tracker.ts b/packages/compiler-cli/src/ngtsc/shims/src/factory_tracker.ts index a9b58b37e4..a4ccb13302 100644 --- a/packages/compiler-cli/src/ngtsc/shims/src/factory_tracker.ts +++ b/packages/compiler-cli/src/ngtsc/shims/src/factory_tracker.ts @@ -32,7 +32,7 @@ export class FactoryTracker { track(sf: ts.SourceFile, factorySymbolName: string): void { if (this.sourceToFactorySymbols.has(sf.fileName)) { - this.sourceToFactorySymbols.get(sf.fileName) !.add(factorySymbolName); + this.sourceToFactorySymbols.get(sf.fileName)!.add(factorySymbolName); } } } diff --git a/packages/compiler-cli/src/ngtsc/shims/src/summary_generator.ts b/packages/compiler-cli/src/ngtsc/shims/src/summary_generator.ts index f3eb5c10c7..ab6caddcdf 100644 --- a/packages/compiler-cli/src/ngtsc/shims/src/summary_generator.ts +++ b/packages/compiler-cli/src/ngtsc/shims/src/summary_generator.ts @@ -8,7 +8,7 @@ import * as ts from 'typescript'; -import {AbsoluteFsPath, absoluteFrom} from '../../file_system'; +import {absoluteFrom, AbsoluteFsPath} from '../../file_system'; import {isNonDeclarationTsPath} from '../../util/src/typescript'; import {ShimGenerator} from './api'; @@ -17,13 +17,17 @@ import {generatedModuleName} from './util'; export class SummaryGenerator implements ShimGenerator { private constructor(private map: Map) {} - getSummaryFileNames(): AbsoluteFsPath[] { return Array.from(this.map.keys()); } + getSummaryFileNames(): AbsoluteFsPath[] { + return Array.from(this.map.keys()); + } - recognize(fileName: AbsoluteFsPath): boolean { return this.map.has(fileName); } + recognize(fileName: AbsoluteFsPath): boolean { + return this.map.has(fileName); + } generate(genFilePath: AbsoluteFsPath, readFile: (fileName: string) => ts.SourceFile | null): ts.SourceFile|null { - const originalPath = this.map.get(genFilePath) !; + const originalPath = this.map.get(genFilePath)!; const original = readFile(originalPath); if (original === null) { return null; diff --git a/packages/compiler-cli/src/ngtsc/shims/src/typecheck_shim.ts b/packages/compiler-cli/src/ngtsc/shims/src/typecheck_shim.ts index 8f9d5247db..57ebf91b54 100644 --- a/packages/compiler-cli/src/ngtsc/shims/src/typecheck_shim.ts +++ b/packages/compiler-cli/src/ngtsc/shims/src/typecheck_shim.ts @@ -22,7 +22,9 @@ import {ShimGenerator} from './api'; export class TypeCheckShimGenerator implements ShimGenerator { constructor(private typeCheckFile: AbsoluteFsPath) {} - recognize(fileName: AbsoluteFsPath): boolean { return fileName === this.typeCheckFile; } + recognize(fileName: AbsoluteFsPath): boolean { + return fileName === this.typeCheckFile; + } generate(genFileName: AbsoluteFsPath, readFile: (fileName: string) => ts.SourceFile | null): ts.SourceFile|null { diff --git a/packages/compiler-cli/src/ngtsc/switch/src/switch.ts b/packages/compiler-cli/src/ngtsc/switch/src/switch.ts index 017458bcab..ea1619c9e3 100644 --- a/packages/compiler-cli/src/ngtsc/switch/src/switch.ts +++ b/packages/compiler-cli/src/ngtsc/switch/src/switch.ts @@ -107,8 +107,8 @@ function flipIvySwitchesInVariableStatement( // reported as a thrown error and not a diagnostic as transformers cannot output diagnostics. let newIdentifier = findPostSwitchIdentifier(statements, postSwitchName); if (newIdentifier === null) { - throw new Error( - `Unable to find identifier ${postSwitchName} in ${stmt.getSourceFile().fileName} for the Ivy switch.`); + throw new Error(`Unable to find identifier ${postSwitchName} in ${ + stmt.getSourceFile().fileName} for the Ivy switch.`); } // Copy the identifier with updateIdentifier(). This copies the internal information which diff --git a/packages/compiler-cli/src/ngtsc/testing/src/utils.ts b/packages/compiler-cli/src/ngtsc/testing/src/utils.ts index a71b7d21c3..b50751f088 100644 --- a/packages/compiler-cli/src/ngtsc/testing/src/utils.ts +++ b/packages/compiler-cli/src/ngtsc/testing/src/utils.ts @@ -10,7 +10,7 @@ import * as ts from 'typescript'; -import {AbsoluteFsPath, NgtscCompilerHost, dirname, getFileSystem, getSourceFileOrError} from '../../file_system'; +import {AbsoluteFsPath, dirname, getFileSystem, getSourceFileOrError, NgtscCompilerHost} from '../../file_system'; export function makeProgram( files: {name: AbsoluteFsPath, contents: string, isRoot?: boolean}[], @@ -25,7 +25,8 @@ export function makeProgram( const compilerOptions = { noLib: true, experimentalDecorators: true, - moduleResolution: ts.ModuleResolutionKind.NodeJs, ...options + moduleResolution: ts.ModuleResolutionKind.NodeJs, + ...options }; const compilerHost = new NgtscCompilerHost(fs, compilerOptions); const rootNames = files.filter(file => file.isRoot !== false) @@ -38,7 +39,7 @@ export function makeProgram( let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); if (diagnostic.file) { const {line, character} = - diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start !); + diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); message = `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`; } return `Error: ${message}`; diff --git a/packages/compiler-cli/src/ngtsc/transform/src/alias.ts b/packages/compiler-cli/src/ngtsc/transform/src/alias.ts index f7698f29e6..5cba3e6d50 100644 --- a/packages/compiler-cli/src/ngtsc/transform/src/alias.ts +++ b/packages/compiler-cli/src/ngtsc/transform/src/alias.ts @@ -17,7 +17,7 @@ export function aliasTransformFactory(exportStatements: Map { + exportStatements.get(file.fileName)!.forEach(([moduleName, symbolName], aliasName) => { const stmt = ts.createExportDeclaration( /* decorators */ undefined, /* modifiers */ undefined, diff --git a/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts b/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts index e103aadd31..250360d70e 100644 --- a/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts +++ b/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts @@ -94,9 +94,13 @@ export class TraitCompiler { } } - analyzeSync(sf: ts.SourceFile): void { this.analyze(sf, false); } + analyzeSync(sf: ts.SourceFile): void { + this.analyze(sf, false); + } - analyzeAsync(sf: ts.SourceFile): Promise|undefined { return this.analyze(sf, true); } + analyzeAsync(sf: ts.SourceFile): Promise|undefined { + return this.analyze(sf, true); + } private analyze(sf: ts.SourceFile, preanalyze: false): void; private analyze(sf: ts.SourceFile, preanalyze: true): Promise|undefined; @@ -138,7 +142,7 @@ export class TraitCompiler { recordFor(clazz: ClassDeclaration): ClassRecord|null { if (this.classes.has(clazz)) { - return this.classes.get(clazz) !; + return this.classes.get(clazz)!; } else { return null; } @@ -149,8 +153,8 @@ export class TraitCompiler { return null; } const records: ClassRecord[] = []; - for (const clazz of this.fileToClasses.get(sf) !) { - records.push(this.classes.get(clazz) !); + for (const clazz of this.fileToClasses.get(sf)!) { + records.push(this.classes.get(clazz)!); } return records; } @@ -173,7 +177,7 @@ export class TraitCompiler { }; for (const priorTrait of priorRecord.traits) { - const handler = this.handlersByName.get(priorTrait.handler.name) !; + const handler = this.handlersByName.get(priorTrait.handler.name)!; let trait: Trait = Trait.pending(handler, priorTrait.detected); if (priorTrait.state === TraitState.ANALYZED || priorTrait.state === TraitState.RESOLVED) { @@ -195,7 +199,7 @@ export class TraitCompiler { if (!this.fileToClasses.has(sf)) { this.fileToClasses.set(sf, new Set()); } - this.fileToClasses.get(sf) !.add(record.node); + this.fileToClasses.get(sf)!.add(record.node); } private scanClassForTraits(clazz: ClassDeclaration): @@ -242,7 +246,7 @@ export class TraitCompiler { if (!this.fileToClasses.has(sf)) { this.fileToClasses.set(sf, new Set()); } - this.fileToClasses.get(sf) !.add(clazz); + this.fileToClasses.get(sf)!.add(clazz); } else { // This is at least the second handler to match this class. This is a slower path that some // classes will go through, which validates that the set of decorators applied to the class @@ -317,7 +321,7 @@ export class TraitCompiler { } } if (preanalysis !== null) { - preanalyzeQueue !.push(preanalysis.then(analyze)); + preanalyzeQueue!.push(preanalysis.then(analyze)); } else { analyze(); } @@ -328,8 +332,8 @@ export class TraitCompiler { clazz: ClassDeclaration, trait: Trait, flags?: HandlerFlags): void { if (trait.state !== TraitState.PENDING) { - throw new Error( - `Attempt to analyze trait of ${clazz.name.text} in state ${TraitState[trait.state]} (expected DETECTED)`); + throw new Error(`Attempt to analyze trait of ${clazz.name.text} in state ${ + TraitState[trait.state]} (expected DETECTED)`); } // Attempt analysis. This could fail with a `FatalDiagnosticError`; catch it if it does. @@ -363,7 +367,7 @@ export class TraitCompiler { resolve(): void { const classes = Array.from(this.classes.keys()); for (const clazz of classes) { - const record = this.classes.get(clazz) !; + const record = this.classes.get(clazz)!; for (let trait of record.traits) { const handler = trait.handler; switch (trait.state) { @@ -371,8 +375,8 @@ export class TraitCompiler { case TraitState.ERRORED: continue; case TraitState.PENDING: - throw new Error( - `Resolving a trait that hasn't been analyzed: ${clazz.name.text} / ${Object.getPrototypeOf(trait.handler).constructor.name}`); + throw new Error(`Resolving a trait that hasn't been analyzed: ${clazz.name.text} / ${ + Object.getPrototypeOf(trait.handler).constructor.name}`); case TraitState.RESOLVED: throw new Error(`Resolving an already resolved trait`); } @@ -410,7 +414,7 @@ export class TraitCompiler { if (!this.reexportMap.has(fileName)) { this.reexportMap.set(fileName, new Map()); } - const fileReexports = this.reexportMap.get(fileName) !; + const fileReexports = this.reexportMap.get(fileName)!; for (const reexport of result.reexports) { fileReexports.set(reexport.asAlias, [reexport.fromModule, reexport.symbolName]); } @@ -421,7 +425,7 @@ export class TraitCompiler { typeCheck(ctx: TypeCheckContext): void { for (const clazz of this.classes.keys()) { - const record = this.classes.get(clazz) !; + const record = this.classes.get(clazz)!; for (const trait of record.traits) { if (trait.state !== TraitState.RESOLVED) { continue; @@ -435,7 +439,7 @@ export class TraitCompiler { index(ctx: IndexingContext): void { for (const clazz of this.classes.keys()) { - const record = this.classes.get(clazz) !; + const record = this.classes.get(clazz)!; for (const trait of record.traits) { if (trait.state !== TraitState.RESOLVED) { // Skip traits that haven't been resolved successfully. @@ -457,7 +461,7 @@ export class TraitCompiler { return null; } - const record = this.classes.get(original) !; + const record = this.classes.get(original)!; let res: CompileResult[] = []; @@ -496,7 +500,7 @@ export class TraitCompiler { return []; } - const record = this.classes.get(original) !; + const record = this.classes.get(original)!; const decorators: ts.Decorator[] = []; for (const trait of record.traits) { @@ -515,7 +519,7 @@ export class TraitCompiler { get diagnostics(): ReadonlyArray { const diagnostics: ts.Diagnostic[] = []; for (const clazz of this.classes.keys()) { - const record = this.classes.get(clazz) !; + const record = this.classes.get(clazz)!; if (record.metaDiagnostics !== null) { diagnostics.push(...record.metaDiagnostics); } @@ -528,5 +532,7 @@ export class TraitCompiler { return diagnostics; } - get exportStatements(): Map> { return this.reexportMap; } + get exportStatements(): Map> { + return this.reexportMap; + } } diff --git a/packages/compiler-cli/src/ngtsc/transform/src/declaration.ts b/packages/compiler-cli/src/ngtsc/transform/src/declaration.ts index 6e8c9abaed..36cee9b39a 100644 --- a/packages/compiler-cli/src/ngtsc/transform/src/declaration.ts +++ b/packages/compiler-cli/src/ngtsc/transform/src/declaration.ts @@ -28,14 +28,14 @@ export class DtsTransformRegistry { if (!this.ivyDeclarationTransforms.has(sf)) { this.ivyDeclarationTransforms.set(sf, new IvyDeclarationDtsTransform()); } - return this.ivyDeclarationTransforms.get(sf) !; + return this.ivyDeclarationTransforms.get(sf)!; } getReturnTypeTransform(sf: ts.SourceFile): ReturnTypeTransform { if (!this.returnTypeTransforms.has(sf)) { this.returnTypeTransforms.set(sf, new ReturnTypeTransform()); } - return this.returnTypeTransforms.get(sf) !; + return this.returnTypeTransforms.get(sf)!; } /** @@ -55,11 +55,11 @@ export class DtsTransformRegistry { let transforms: DtsTransform[]|null = null; if (this.ivyDeclarationTransforms.has(originalSf)) { transforms = []; - transforms.push(this.ivyDeclarationTransforms.get(originalSf) !); + transforms.push(this.ivyDeclarationTransforms.get(originalSf)!); } if (this.returnTypeTransforms.has(originalSf)) { transforms = transforms || []; - transforms.push(this.returnTypeTransforms.get(originalSf) !); + transforms.push(this.returnTypeTransforms.get(originalSf)!); } return transforms; } @@ -200,7 +200,7 @@ export class IvyDeclarationDtsTransform implements DtsTransform { if (!this.declarationFields.has(original)) { return clazz; } - const fields = this.declarationFields.get(original) !; + const fields = this.declarationFields.get(original)!; const newMembers = fields.map(decl => { const modifiers = [ts.createModifier(ts.SyntaxKind.StaticKeyword)]; @@ -247,7 +247,7 @@ export class ReturnTypeTransform implements DtsTransform { if (!this.typeReplacements.has(original)) { return element; } - const returnType = this.typeReplacements.get(original) !; + const returnType = this.typeReplacements.get(original)!; const tsReturnType = translateType(returnType, imports); const methodSignature = ts.updateMethodSignature( @@ -273,7 +273,7 @@ export class ReturnTypeTransform implements DtsTransform { if (!this.typeReplacements.has(original)) { return element; } - const returnType = this.typeReplacements.get(original) !; + const returnType = this.typeReplacements.get(original)!; const tsReturnType = translateType(returnType, imports); return ts.updateFunctionDeclaration( diff --git a/packages/compiler-cli/src/ngtsc/transform/src/trait.ts b/packages/compiler-cli/src/ngtsc/transform/src/trait.ts index 1bdd897354..e6b5fb83d3 100644 --- a/packages/compiler-cli/src/ngtsc/transform/src/trait.ts +++ b/packages/compiler-cli/src/ngtsc/transform/src/trait.ts @@ -50,8 +50,8 @@ export enum TraitState { * This not only simplifies the implementation, but ensures traits are monomorphic objects as * they're all just "views" in the type system of the same object (which never changes shape). */ -export type Trait = PendingTrait| SkippedTrait| AnalyzedTrait| - ResolvedTrait| ErroredTrait; +export type Trait = PendingTrait|SkippedTrait|AnalyzedTrait| + ResolvedTrait|ErroredTrait; /** * The value side of `Trait` exposes a helper to create a `Trait` in a pending state (by delegating @@ -59,7 +59,7 @@ export type Trait = PendingTrait| SkippedTrait| Analy */ export const Trait = { pending: (handler: DecoratorHandler, detected: DetectResult): - PendingTrait => TraitImpl.pending(handler, detected), + PendingTrait => TraitImpl.pending(handler, detected), }; /** @@ -137,7 +137,9 @@ export interface ErroredTrait extends TraitBase { * * This is a terminal state. */ -export interface SkippedTrait extends TraitBase { state: TraitState.SKIPPED; } +export interface SkippedTrait extends TraitBase { + state: TraitState.SKIPPED; +} /** * The part of the `Trait` interface for any trait which has been successfully analyzed. @@ -251,8 +253,8 @@ class TraitImpl { */ private assertTransitionLegal(allowedState: TraitState, transitionTo: TraitState): void { if (!(this.state & allowedState)) { - throw new Error( - `Assertion failure: cannot transition from ${TraitState[this.state]} to ${TraitState[transitionTo]}.`); + throw new Error(`Assertion failure: cannot transition from ${TraitState[this.state]} to ${ + TraitState[transitionTo]}.`); } } diff --git a/packages/compiler-cli/src/ngtsc/transform/src/transform.ts b/packages/compiler-cli/src/ngtsc/transform/src/transform.ts index 00ada93a58..58704a1369 100644 --- a/packages/compiler-cli/src/ngtsc/transform/src/transform.ts +++ b/packages/compiler-cli/src/ngtsc/transform/src/transform.ts @@ -12,7 +12,7 @@ import * as ts from 'typescript'; import {DefaultImportRecorder, ImportRewriter} from '../../imports'; import {Decorator, ReflectionHost} from '../../reflection'; import {ImportManager, translateExpression, translateStatement} from '../../translator'; -import {VisitListEntryResult, Visitor, visit} from '../../util/src/visitor'; +import {visit, VisitListEntryResult, Visitor} from '../../util/src/visitor'; import {TraitCompiler} from './compilation'; import {addImports} from './utils'; @@ -285,7 +285,7 @@ function setFileOverviewComment(sf: ts.SourceFile, fileoverview: FileOverviewMet } function maybeFilterDecorator( - decorators: ts.NodeArray| undefined, + decorators: ts.NodeArray|undefined, toRemove: ts.Decorator[]): ts.NodeArray|undefined { if (decorators === undefined) { return undefined; diff --git a/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts b/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts index 8608e4364f..e90f61659d 100644 --- a/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts +++ b/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts @@ -24,11 +24,15 @@ runInEachFileSystem(() => { name = 'FakeDecoratorHandler'; precedence = HandlerPrecedence.PRIMARY; - detect(): undefined { throw new Error('detect should not have been called'); } + detect(): undefined { + throw new Error('detect should not have been called'); + } analyze(): AnalysisOutput { throw new Error('analyze should not have been called'); } - compile(): CompileResult { throw new Error('compile should not have been called'); } + compile(): CompileResult { + throw new Error('compile should not have been called'); + } } const {program} = makeProgram([{ @@ -40,7 +44,7 @@ runInEachFileSystem(() => { const compiler = new TraitCompiler( [new FakeDecoratorHandler()], reflectionHost, NOOP_PERF_RECORDER, NOOP_INCREMENTAL_BUILD, true, new DtsTransformRegistry()); - const sourceFile = program.getSourceFile('lib.d.ts') !; + const sourceFile = program.getSourceFile('lib.d.ts')!; const analysis = compiler.analyzeSync(sourceFile); expect(sourceFile.isDeclarationFile).toBe(true); diff --git a/packages/compiler-cli/src/ngtsc/translator/src/translator.ts b/packages/compiler-cli/src/ngtsc/translator/src/translator.ts index a55348229d..aed4303eea 100644 --- a/packages/compiler-cli/src/ngtsc/translator/src/translator.ts +++ b/packages/compiler-cli/src/ngtsc/translator/src/translator.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {ArrayType, AssertNotNull, BinaryOperator, BinaryOperatorExpr, BuiltinType, BuiltinTypeName, CastExpr, ClassStmt, CommaExpr, CommentStmt, ConditionalExpr, DeclareFunctionStmt, DeclareVarStmt, Expression, ExpressionStatement, ExpressionType, ExpressionVisitor, ExternalExpr, FunctionExpr, IfStmt, InstantiateExpr, InvokeFunctionExpr, InvokeMethodExpr, JSDocCommentStmt, LiteralArrayExpr, LiteralExpr, LiteralMapExpr, MapType, NotExpr, ReadKeyExpr, ReadPropExpr, ReadVarExpr, ReturnStatement, Statement, StatementVisitor, StmtModifier, ThrowStmt, TryCatchStmt, Type, TypeVisitor, TypeofExpr, WrappedNodeExpr, WriteKeyExpr, WritePropExpr, WriteVarExpr} from '@angular/compiler'; +import {ArrayType, AssertNotNull, BinaryOperator, BinaryOperatorExpr, BuiltinType, BuiltinTypeName, CastExpr, ClassStmt, CommaExpr, CommentStmt, ConditionalExpr, DeclareFunctionStmt, DeclareVarStmt, Expression, ExpressionStatement, ExpressionType, ExpressionVisitor, ExternalExpr, FunctionExpr, IfStmt, InstantiateExpr, InvokeFunctionExpr, InvokeMethodExpr, JSDocCommentStmt, LiteralArrayExpr, LiteralExpr, LiteralMapExpr, MapType, NotExpr, ReadKeyExpr, ReadPropExpr, ReadVarExpr, ReturnStatement, Statement, StatementVisitor, StmtModifier, ThrowStmt, TryCatchStmt, Type, TypeofExpr, TypeVisitor, WrappedNodeExpr, WriteKeyExpr, WritePropExpr, WriteVarExpr} from '@angular/compiler'; import {LocalizedString} from '@angular/compiler/src/output/output_ast'; import * as ts from 'typescript'; @@ -15,9 +15,13 @@ import {DefaultImportRecorder, ImportRewriter, NOOP_DEFAULT_IMPORT_RECORDER, Noo export class Context { constructor(readonly isStatement: boolean) {} - get withExpressionMode(): Context { return this.isStatement ? new Context(false) : this; } + get withExpressionMode(): Context { + return this.isStatement ? new Context(false) : this; + } - get withStatementMode(): Context { return !this.isStatement ? new Context(true) : this; } + get withStatementMode(): Context { + return !this.isStatement ? new Context(true) : this; + } } const BINARY_OPERATORS = new Map([ @@ -83,7 +87,7 @@ export class ImportManager { if (!this.specifierToIdentifier.has(moduleName)) { this.specifierToIdentifier.set(moduleName, `${this.prefix}${this.nextIndex++}`); } - const moduleImport = this.specifierToIdentifier.get(moduleName) !; + const moduleImport = this.specifierToIdentifier.get(moduleName)!; return {moduleImport, symbol}; } @@ -130,19 +134,21 @@ class ExpressionTranslatorVisitor implements ExpressionVisitor, StatementVisitor ts.NodeFlags.Const : ts.NodeFlags.None; return ts.createVariableStatement( - undefined, ts.createVariableDeclarationList( - [ts.createVariableDeclaration( - stmt.name, undefined, stmt.value && - stmt.value.visitExpression(this, context.withExpressionMode))], - nodeFlags)); + undefined, + ts.createVariableDeclarationList( + [ts.createVariableDeclaration( + stmt.name, undefined, + stmt.value && stmt.value.visitExpression(this, context.withExpressionMode))], + nodeFlags)); } visitDeclareFunctionStmt(stmt: DeclareFunctionStmt, context: Context): ts.FunctionDeclaration { return ts.createFunctionDeclaration( undefined, undefined, undefined, stmt.name, undefined, stmt.params.map(param => ts.createParameter(undefined, undefined, undefined, param.name)), - undefined, ts.createBlock(stmt.statements.map( - child => child.visitStatement(this, context.withStatementMode)))); + undefined, + ts.createBlock( + stmt.statements.map(child => child.visitStatement(this, context.withStatementMode)))); } visitExpressionStmt(stmt: ExpressionStatement, context: Context): ts.ExpressionStatement { @@ -194,7 +200,7 @@ class ExpressionTranslatorVisitor implements ExpressionVisitor, StatementVisitor } visitReadVarExpr(ast: ReadVarExpr, context: Context): ts.Identifier { - const identifier = ts.createIdentifier(ast.name !); + const identifier = ts.createIdentifier(ast.name!); this.setSourceMapRange(identifier, ast); return identifier; } @@ -322,7 +328,7 @@ class ExpressionTranslatorVisitor implements ExpressionVisitor, StatementVisitor return ts.createConditional( cond, ast.trueCase.visitExpression(this, context), - ast.falseCase !.visitExpression(this, context)); + ast.falseCase!.visitExpression(this, context)); } visitNotExpr(ast: NotExpr, context: Context): ts.PrefixUnaryExpression { @@ -352,7 +358,7 @@ class ExpressionTranslatorVisitor implements ExpressionVisitor, StatementVisitor throw new Error(`Unknown binary operator: ${BinaryOperator[ast.operator]}`); } return ts.createBinary( - ast.lhs.visitExpression(this, context), BINARY_OPERATORS.get(ast.operator) !, + ast.lhs.visitExpression(this, context), BINARY_OPERATORS.get(ast.operator)!, ast.rhs.visitExpression(this, context)); } @@ -537,13 +543,17 @@ export class TypeTranslatorVisitor implements ExpressionVisitor, TypeVisitor { throw new Error('Method not implemented.'); } - visitNotExpr(ast: NotExpr, context: Context) { throw new Error('Method not implemented.'); } + visitNotExpr(ast: NotExpr, context: Context) { + throw new Error('Method not implemented.'); + } visitAssertNotNullExpr(ast: AssertNotNull, context: Context) { throw new Error('Method not implemented.'); } - visitCastExpr(ast: CastExpr, context: Context) { throw new Error('Method not implemented.'); } + visitCastExpr(ast: CastExpr, context: Context) { + throw new Error('Method not implemented.'); + } visitFunctionExpr(ast: FunctionExpr, context: Context) { throw new Error('Method not implemented.'); @@ -580,7 +590,9 @@ export class TypeTranslatorVisitor implements ExpressionVisitor, TypeVisitor { return ts.createTypeLiteralNode(entries); } - visitCommaExpr(ast: CommaExpr, context: Context) { throw new Error('Method not implemented.'); } + visitCommaExpr(ast: CommaExpr, context: Context) { + throw new Error('Method not implemented.'); + } visitWrappedNodeExpr(ast: WrappedNodeExpr, context: Context): ts.TypeNode { const node: ts.Node = ast.node; diff --git a/packages/compiler-cli/src/ngtsc/tsc_plugin.ts b/packages/compiler-cli/src/ngtsc/tsc_plugin.ts index d533b8a3ee..660d48d132 100644 --- a/packages/compiler-cli/src/ngtsc/tsc_plugin.ts +++ b/packages/compiler-cli/src/ngtsc/tsc_plugin.ts @@ -71,12 +71,14 @@ export class NgTscPlugin implements TscPlugin { return this._compiler; } - constructor(private ngOptions: {}) { setFileSystem(new NodeJSFileSystem()); } + constructor(private ngOptions: {}) { + setFileSystem(new NodeJSFileSystem()); + } wrapHost( host: ts.CompilerHost&UnifiedModulesHost, inputFiles: readonly string[], options: ts.CompilerOptions): PluginCompilerHost { - this.options = {...this.ngOptions, ...options } as NgCompilerOptions; + this.options = {...this.ngOptions, ...options} as NgCompilerOptions; this.host = NgCompilerHost.wrap(host, inputFiles, this.options); return this.host; } @@ -100,9 +102,15 @@ export class NgTscPlugin implements TscPlugin { return this.compiler.getDiagnostics(file); } - getOptionDiagnostics(): ts.Diagnostic[] { return this.compiler.getOptionDiagnostics(); } + getOptionDiagnostics(): ts.Diagnostic[] { + return this.compiler.getOptionDiagnostics(); + } - getNextProgram(): ts.Program { return this.compiler.getNextProgram(); } + getNextProgram(): ts.Program { + return this.compiler.getNextProgram(); + } - createTransformers(): ts.CustomTransformers { return this.compiler.prepareEmit().transformers; } + createTransformers(): ts.CustomTransformers { + return this.compiler.prepareEmit().transformers; + } } diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/api.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/api.ts index 3134a3db8a..f36f7983f0 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/api.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/api.ts @@ -25,7 +25,7 @@ export interface TypeCheckableDirectiveMeta extends DirectiveMeta { hasNgTemplateContextGuard: boolean; } -export type TemplateId = string & {__brand: 'TemplateId'}; +export type TemplateId = string&{__brand: 'TemplateId'}; /** * Metadata required in addition to a component class in order to generate a type check block (TCB) @@ -233,7 +233,7 @@ export interface TypeCheckingConfig { export type TemplateSourceMapping = - DirectTemplateSourceMapping | IndirectTemplateSourceMapping | ExternalTemplateSourceMapping; + DirectTemplateSourceMapping|IndirectTemplateSourceMapping|ExternalTemplateSourceMapping; /** * A mapping to an inline template in a TS file. diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts index 1538b964a2..58b866f0f9 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts @@ -14,7 +14,7 @@ import {NoopImportRewriter, Reference, ReferenceEmitter} from '../../imports'; import {ClassDeclaration, ReflectionHost} from '../../reflection'; import {ImportManager} from '../../translator'; -import {TemplateSourceMapping, TypeCheckBlockMetadata, TypeCheckableDirectiveMeta, TypeCheckingConfig, TypeCtorMetadata} from './api'; +import {TemplateSourceMapping, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata, TypeCheckingConfig, TypeCtorMetadata} from './api'; import {shouldReportDiagnostic, translateDiagnostic} from './diagnostics'; import {DomSchemaChecker, RegistryDomSchemaChecker} from './dom'; import {Environment} from './environment'; @@ -125,7 +125,7 @@ export class TypeCheckContext { if (!this.opMap.has(sf)) { this.opMap.set(sf, []); } - const ops = this.opMap.get(sf) !; + const ops = this.opMap.get(sf)!; // Push a `TypeCtorOp` into the operation queue for the source file. ops.push(new TypeCtorOp(ref, ctorMeta)); @@ -152,7 +152,7 @@ export class TypeCheckContext { // Each Op has a splitPoint index into the text where it needs to be inserted. Split the // original source text into chunks at these split points, where code will be inserted between // the chunks. - const ops = this.opMap.get(sf) !.sort(orderOps); + const ops = this.opMap.get(sf)!.sort(orderOps); const textParts = splitStringAtPoints(sf.text, ops.map(op => op.splitPoint)); // Use a `ts.Printer` to generate source code. @@ -238,7 +238,7 @@ export class TypeCheckContext { if (!this.opMap.has(sf)) { this.opMap.set(sf, []); } - const ops = this.opMap.get(sf) !; + const ops = this.opMap.get(sf)!; ops.push(new TcbOp( ref, tcbMeta, this.config, this.reflector, this.domSchemaChecker, this.oobRecorder)); } @@ -278,7 +278,9 @@ class TcbOp implements Op { /** * Type check blocks are inserted immediately after the end of the component class. */ - get splitPoint(): number { return this.ref.node.end + 1; } + get splitPoint(): number { + return this.ref.node.end + 1; + } execute(im: ImportManager, sf: ts.SourceFile, refEmitter: ReferenceEmitter, printer: ts.Printer): string { @@ -301,7 +303,9 @@ class TypeCtorOp implements Op { /** * Type constructor operations are inserted immediately before the end of the directive class. */ - get splitPoint(): number { return this.ref.node.end - 1; } + get splitPoint(): number { + return this.ref.node.end - 1; + } execute(im: ImportManager, sf: ts.SourceFile, refEmitter: ReferenceEmitter, printer: ts.Printer): string { diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/diagnostics.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/diagnostics.ts index b65fa8d818..f5d847938e 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/diagnostics.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/diagnostics.ts @@ -70,7 +70,7 @@ export function ignoreDiagnostics(node: ts.Node): void { * Adds a synthetic comment to the expression that represents the parse span of the provided node. * This comment can later be retrieved as trivia of a node to recover original source locations. */ -export function addParseSpanInfo(node: ts.Node, span: AbsoluteSourceSpan | ParseSourceSpan): void { +export function addParseSpanInfo(node: ts.Node, span: AbsoluteSourceSpan|ParseSourceSpan): void { let commentText: string; if (span instanceof AbsoluteSourceSpan) { commentText = `${span.start},${span.end}`; @@ -145,7 +145,7 @@ export function translateDiagnostic( */ export function makeTemplateDiagnostic( mapping: TemplateSourceMapping, span: ParseSourceSpan, category: ts.DiagnosticCategory, - code: number, messageText: string | ts.DiagnosticMessageChain, relatedMessage?: { + code: number, messageText: string|ts.DiagnosticMessageChain, relatedMessage?: { text: string, span: ParseSourceSpan, }): TemplateDiagnostic { @@ -172,7 +172,8 @@ export function makeTemplateDiagnostic( file: mapping.node.getSourceFile(), componentFile: mapping.node.getSourceFile(), start: span.start.offset, - length: span.end.offset - span.start.offset, relatedInformation, + length: span.end.offset - span.start.offset, + relatedInformation, }; } else if (mapping.type === 'indirect' || mapping.type === 'external') { // For indirect mappings (template was declared inline, but ngtsc couldn't map it directly diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/dom.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/dom.ts index 480577cbdc..2e2bfe8631 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/dom.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/dom.ts @@ -12,7 +12,7 @@ import * as ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../diagnostics'; import {TemplateId} from './api'; -import {TemplateSourceResolver, makeTemplateDiagnostic} from './diagnostics'; +import {makeTemplateDiagnostic, TemplateSourceResolver} from './diagnostics'; const REGISTRY = new DomElementSchemaRegistry(); const REMOVE_XHTML_REGEX = /^:xhtml:/; @@ -66,7 +66,9 @@ export interface DomSchemaChecker { export class RegistryDomSchemaChecker implements DomSchemaChecker { private _diagnostics: ts.Diagnostic[] = []; - get diagnostics(): ReadonlyArray { return this._diagnostics; } + get diagnostics(): ReadonlyArray { + return this._diagnostics; + } constructor(private resolver: TemplateSourceResolver) {} @@ -83,8 +85,8 @@ export class RegistryDomSchemaChecker implements DomSchemaChecker { errorMsg += `1. If '${name}' is an Angular component, then verify that it is part of this module.\n`; if (name.indexOf('-') > -1) { - errorMsg += - `2. If '${name}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`; + errorMsg += `2. If '${ + name}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`; } else { errorMsg += `2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`; @@ -107,12 +109,16 @@ export class RegistryDomSchemaChecker implements DomSchemaChecker { `Can't bind to '${name}' since it isn't a known property of '${element.name}'.`; if (element.name.startsWith('ng-')) { errorMsg += - `\n1. If '${name}' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.` + + `\n1. If '${ + name}' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.` + `\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`; } else if (element.name.indexOf('-') > -1) { errorMsg += - `\n1. If '${element.name}' is an Angular component and it has '${name}' input, then verify that it is part of this module.` + - `\n2. If '${element.name}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.` + + `\n1. If '${element.name}' is an Angular component and it has '${ + name}' input, then verify that it is part of this module.` + + `\n2. If '${ + element + .name}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.` + `\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`; } diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/environment.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/environment.ts index 5f48a9c04b..300616c47f 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/environment.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/environment.ts @@ -59,7 +59,7 @@ export class Environment { const dirRef = dir.ref as Reference>; const node = dirRef.node; if (this.typeCtors.has(node)) { - return this.typeCtors.get(node) !; + return this.typeCtors.get(node)!; } if (requiresInlineTypeCtor(node, this.reflector)) { @@ -101,7 +101,7 @@ export class Environment { */ pipeInst(ref: Reference>): ts.Expression { if (this.pipeInsts.has(ref.node)) { - return this.pipeInsts.get(ref.node) !; + return this.pipeInsts.get(ref.node)!; } const pipeType = this.referenceType(ref); @@ -142,7 +142,8 @@ export class Environment { /* dotDotDotToken */ undefined, /* name */ 'cb', /* questionToken */ undefined, - /* type */ ts.createFunctionTypeNode( + /* type */ + ts.createFunctionTypeNode( /* typeParameters */ undefined, /* parameters */[ts.createParameter( /* decorators */ undefined, diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts index fd1fa179c7..0d7901332c 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {AST, ASTWithSource, AstVisitor, Binary, BindingPipe, Chain, Conditional, EmptyExpr, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, NonNullAssert, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeMethodCall, SafePropertyRead} from '@angular/compiler'; +import {AST, AstVisitor, ASTWithSource, Binary, BindingPipe, Chain, Conditional, EmptyExpr, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, NonNullAssert, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeMethodCall, SafePropertyRead} from '@angular/compiler'; import * as ts from 'typescript'; import {TypeCheckingConfig} from './api'; @@ -103,7 +103,7 @@ class AstTranslator implements AstVisitor { } visitFunctionCall(ast: FunctionCall): ts.Expression { - const receiver = wrapForDiagnostics(this.translate(ast.target !)); + const receiver = wrapForDiagnostics(this.translate(ast.target!)); const args = ast.args.map(expr => this.translate(expr)); const node = ts.createCall(receiver, undefined, args); addParseSpanInfo(node, ast.sourceSpan); @@ -192,7 +192,9 @@ class AstTranslator implements AstVisitor { return node; } - visitPipe(ast: BindingPipe): never { throw new Error('Method not implemented.'); } + visitPipe(ast: BindingPipe): never { + throw new Error('Method not implemented.'); + } visitPrefixNot(ast: PrefixNot): ts.Expression { const expression = wrapForDiagnostics(this.translate(ast.expression)); @@ -221,7 +223,9 @@ class AstTranslator implements AstVisitor { return node; } - visitQuote(ast: Quote): never { throw new Error('Method not implemented.'); } + visitQuote(ast: Quote): never { + throw new Error('Method not implemented.'); + } visitSafeMethodCall(ast: SafeMethodCall): ts.Expression { // See the comments in SafePropertyRead above for an explanation of the cases here. @@ -296,28 +300,64 @@ class VeSafeLhsInferenceBugDetector implements AstVisitor { return ast.receiver.visit(VeSafeLhsInferenceBugDetector.SINGLETON); } - visitBinary(ast: Binary): boolean { return ast.left.visit(this) || ast.right.visit(this); } - visitChain(ast: Chain): boolean { return false; } + visitBinary(ast: Binary): boolean { + return ast.left.visit(this) || ast.right.visit(this); + } + visitChain(ast: Chain): boolean { + return false; + } visitConditional(ast: Conditional): boolean { return ast.condition.visit(this) || ast.trueExp.visit(this) || ast.falseExp.visit(this); } - visitFunctionCall(ast: FunctionCall): boolean { return true; } - visitImplicitReceiver(ast: ImplicitReceiver): boolean { return false; } + visitFunctionCall(ast: FunctionCall): boolean { + return true; + } + visitImplicitReceiver(ast: ImplicitReceiver): boolean { + return false; + } visitInterpolation(ast: Interpolation): boolean { return ast.expressions.some(exp => exp.visit(this)); } - visitKeyedRead(ast: KeyedRead): boolean { return false; } - visitKeyedWrite(ast: KeyedWrite): boolean { return false; } - visitLiteralArray(ast: LiteralArray): boolean { return true; } - visitLiteralMap(ast: LiteralMap): boolean { return true; } - visitLiteralPrimitive(ast: LiteralPrimitive): boolean { return false; } - visitMethodCall(ast: MethodCall): boolean { return true; } - visitPipe(ast: BindingPipe): boolean { return true; } - visitPrefixNot(ast: PrefixNot): boolean { return ast.expression.visit(this); } - visitNonNullAssert(ast: PrefixNot): boolean { return ast.expression.visit(this); } - visitPropertyRead(ast: PropertyRead): boolean { return false; } - visitPropertyWrite(ast: PropertyWrite): boolean { return false; } - visitQuote(ast: Quote): boolean { return false; } - visitSafeMethodCall(ast: SafeMethodCall): boolean { return true; } - visitSafePropertyRead(ast: SafePropertyRead): boolean { return false; } + visitKeyedRead(ast: KeyedRead): boolean { + return false; + } + visitKeyedWrite(ast: KeyedWrite): boolean { + return false; + } + visitLiteralArray(ast: LiteralArray): boolean { + return true; + } + visitLiteralMap(ast: LiteralMap): boolean { + return true; + } + visitLiteralPrimitive(ast: LiteralPrimitive): boolean { + return false; + } + visitMethodCall(ast: MethodCall): boolean { + return true; + } + visitPipe(ast: BindingPipe): boolean { + return true; + } + visitPrefixNot(ast: PrefixNot): boolean { + return ast.expression.visit(this); + } + visitNonNullAssert(ast: PrefixNot): boolean { + return ast.expression.visit(this); + } + visitPropertyRead(ast: PropertyRead): boolean { + return false; + } + visitPropertyWrite(ast: PropertyWrite): boolean { + return false; + } + visitQuote(ast: Quote): boolean { + return false; + } + visitSafeMethodCall(ast: SafeMethodCall): boolean { + return true; + } + visitSafePropertyRead(ast: SafePropertyRead): boolean { + return false; + } } diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/host.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/host.ts index 8bbc0edd4c..a1d68b541c 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/host.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/host.ts @@ -25,7 +25,7 @@ export class TypeCheckProgramHost implements ts.CompilerHost { this.sfMap = sfMap; if (delegate.getDirectories !== undefined) { - this.getDirectories = (path: string) => delegate.getDirectories !(path); + this.getDirectories = (path: string) => delegate.getDirectories!(path); } if (delegate.resolveModuleNames !== undefined) { @@ -69,7 +69,9 @@ export class TypeCheckProgramHost implements ts.CompilerHost { throw new Error(`TypeCheckProgramHost should never write files`); } - getCurrentDirectory(): string { return this.delegate.getCurrentDirectory(); } + getCurrentDirectory(): string { + return this.delegate.getCurrentDirectory(); + } getDirectories?: (path: string) => string[]; @@ -77,13 +79,19 @@ export class TypeCheckProgramHost implements ts.CompilerHost { return this.delegate.getCanonicalFileName(fileName); } - useCaseSensitiveFileNames(): boolean { return this.delegate.useCaseSensitiveFileNames(); } + useCaseSensitiveFileNames(): boolean { + return this.delegate.useCaseSensitiveFileNames(); + } - getNewLine(): string { return this.delegate.getNewLine(); } + getNewLine(): string { + return this.delegate.getNewLine(); + } fileExists(fileName: string): boolean { return this.sfMap.has(fileName) || this.delegate.fileExists(fileName); } - readFile(fileName: string): string|undefined { return this.delegate.readFile(fileName); } + readFile(fileName: string): string|undefined { + return this.delegate.readFile(fileName); + } } \ No newline at end of file diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts index 2f1a8b6e9c..18ee794e6d 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts @@ -12,7 +12,7 @@ import * as ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../diagnostics'; import {TemplateId} from './api'; -import {TemplateSourceResolver, makeTemplateDiagnostic} from './diagnostics'; +import {makeTemplateDiagnostic, TemplateSourceResolver} from './diagnostics'; @@ -68,7 +68,9 @@ export class OutOfBandDiagnosticRecorderImpl implements OutOfBandDiagnosticRecor constructor(private resolver: TemplateSourceResolver) {} - get diagnostics(): ReadonlyArray { return this._diagnostics; } + get diagnostics(): ReadonlyArray { + return this._diagnostics; + } missingReferenceTarget(templateId: TemplateId, ref: TmplAstReference): void { const mapping = this.resolver.getSourceMapping(templateId); @@ -97,8 +99,9 @@ export class OutOfBandDiagnosticRecorderImpl implements OutOfBandDiagnosticRecor illegalAssignmentToTemplateVar( templateId: TemplateId, assignment: PropertyWrite, target: TmplAstVariable): void { const mapping = this.resolver.getSourceMapping(templateId); - const errorMsg = - `Cannot use variable '${assignment.name}' as the left-hand side of an assignment expression. Template variables are read-only.`; + const errorMsg = `Cannot use variable '${ + assignment + .name}' as the left-hand side of an assignment expression. Template variables are read-only.`; const sourceSpan = this.resolver.toParseSourceSpan(templateId, assignment.sourceSpan); if (sourceSpan === null) { @@ -115,8 +118,8 @@ export class OutOfBandDiagnosticRecorderImpl implements OutOfBandDiagnosticRecor duplicateTemplateVar( templateId: TemplateId, variable: TmplAstVariable, firstDecl: TmplAstVariable): void { const mapping = this.resolver.getSourceMapping(templateId); - const errorMsg = - `Cannot redeclare variable '${variable.name}' as it was previously declared elsewhere for the same template.`; + const errorMsg = `Cannot redeclare variable '${ + variable.name}' as it was previously declared elsewhere for the same template.`; // The allocation of the error here is pretty useless for variables declared in microsyntax, // since the sourceSpan refers to the entire microsyntax property, not a span for the specific diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/source.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/source.ts index 22ea319fff..9f37c36c19 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/source.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/source.ts @@ -65,14 +65,14 @@ export class TemplateSourceManager implements TemplateSourceResolver { if (!this.templateSources.has(id)) { throw new Error(`Unexpected unknown template ID: ${id}`); } - return this.templateSources.get(id) !.mapping; + return this.templateSources.get(id)!.mapping; } toParseSourceSpan(id: TemplateId, span: AbsoluteSourceSpan): ParseSourceSpan|null { if (!this.templateSources.has(id)) { return null; } - const templateSource = this.templateSources.get(id) !; + const templateSource = this.templateSources.get(id)!; return templateSource.toParseSourceSpan(span.start, span.end); } } diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts index 667957411a..7911baacbd 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts @@ -6,17 +6,17 @@ * found in the LICENSE file at https://angular.io/license */ -import {AST, BindingPipe, BindingType, BoundTarget, DYNAMIC_TYPE, ImplicitReceiver, MethodCall, ParseSourceSpan, ParsedEventType, PropertyRead, PropertyWrite, SchemaMetadata, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstBoundText, TmplAstElement, TmplAstNode, TmplAstReference, TmplAstTemplate, TmplAstTextAttribute, TmplAstVariable} from '@angular/compiler'; +import {AST, BindingPipe, BindingType, BoundTarget, DYNAMIC_TYPE, ImplicitReceiver, MethodCall, ParsedEventType, ParseSourceSpan, PropertyRead, PropertyWrite, SchemaMetadata, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstBoundText, TmplAstElement, TmplAstNode, TmplAstReference, TmplAstTemplate, TmplAstTextAttribute, TmplAstVariable} from '@angular/compiler'; import * as ts from 'typescript'; import {Reference} from '../../imports'; import {ClassDeclaration} from '../../reflection'; -import {TemplateId, TypeCheckBlockMetadata, TypeCheckableDirectiveMeta} from './api'; +import {TemplateId, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata} from './api'; import {addParseSpanInfo, addTemplateId, ignoreDiagnostics, wrapForDiagnostics} from './diagnostics'; import {DomSchemaChecker} from './dom'; import {Environment} from './environment'; -import {NULL_AS_ANY, astToTypescript} from './expression'; +import {astToTypescript, NULL_AS_ANY} from './expression'; import {OutOfBandDiagnosticRecorder} from './oob'; import {ExpressionSemanticVisitor} from './template_semantics'; import {checkIfClassIsExported, checkIfGenericTypesAreUnbound, tsCallMethod, tsCastToAny, tsCreateElement, tsCreateVariable, tsDeclareVariable} from './ts_util'; @@ -109,7 +109,9 @@ abstract class TcbOp { * `TcbOp` can be returned in cases where additional code generation is necessary to deal with * circular references. */ - circularFallback(): TcbOp|ts.Expression { return INFER_TYPE_FOR_CIRCULAR_OP_EXPR; } + circularFallback(): TcbOp|ts.Expression { + return INFER_TYPE_FOR_CIRCULAR_OP_EXPR; + } } /** @@ -170,7 +172,9 @@ class TcbVariableOp extends TcbOp { * Executing this operation returns a reference to the template's context variable. */ class TcbTemplateContextOp extends TcbOp { - constructor(private tcb: Context, private scope: Scope) { super(); } + constructor(private tcb: Context, private scope: Scope) { + super(); + } execute(): ts.Identifier { // Allocate a template ctx variable and declare it with an 'any' type. The type of this variable @@ -219,7 +223,7 @@ class TcbTemplateBodyOp extends TcbOp { // For each template guard function on the directive, look for a binding to that input. const boundInput = this.template.inputs.find(i => i.name === guard.inputName) || this.template.templateAttrs.find( - (i: TmplAstTextAttribute | TmplAstBoundAttribute): i is TmplAstBoundAttribute => + (i: TmplAstTextAttribute|TmplAstBoundAttribute): i is TmplAstBoundAttribute => i instanceof TmplAstBoundAttribute && i.name === guard.inputName); if (boundInput !== undefined) { // If there is such a binding, generate an expression for it. @@ -266,7 +270,7 @@ class TcbTemplateBodyOp extends TcbOp { guard = directiveGuards.reduce( (expr, dirGuard) => ts.createBinary(expr, ts.SyntaxKind.AmpersandAmpersandToken, dirGuard), - directiveGuards.pop() !); + directiveGuards.pop()!); } // Create a new Scope for the template. This constructs the list of operations for the template @@ -514,7 +518,7 @@ class TcbDirectiveOutputsOp extends TcbOp { if (output.type !== ParsedEventType.Regular || !fieldByEventName.has(output.name)) { continue; } - const field = fieldByEventName.get(output.name) !; + const field = fieldByEventName.get(output.name)!; if (this.tcb.env.config.checkTypeOfOutputEvents) { // For strict checking of directive events, generate a call to the `subscribe` method @@ -644,13 +648,15 @@ export class Context { * Currently this uses a monotonically increasing counter, but in the future the variable name * might change depending on the type of data being stored. */ - allocateId(): ts.Identifier { return ts.createIdentifier(`_t${this.nextId++}`); } + allocateId(): ts.Identifier { + return ts.createIdentifier(`_t${this.nextId++}`); + } getPipeByName(name: string): ts.Expression|null { if (!this.pipes.has(name)) { return null; } - return this.env.pipeInst(this.pipes.get(name) !); + return this.env.pipeInst(this.pipes.get(name)!); } } @@ -745,7 +751,7 @@ class Scope { if (!varMap.has(v.name)) { varMap.set(v.name, v); } else { - const firstDecl = varMap.get(v.name) !; + const firstDecl = varMap.get(v.name)!; tcb.oobRecorder.duplicateTemplateVar(tcb.id, v, firstDecl); } @@ -796,7 +802,9 @@ class Scope { /** * Add a statement to this scope. */ - addStatement(stmt: ts.Statement): void { this.statements.push(stmt); } + addStatement(stmt: ts.Statement): void { + this.statements.push(stmt); + } /** * Get the statements. @@ -840,26 +848,26 @@ class Scope { if (ref instanceof TmplAstVariable && this.varMap.has(ref)) { // Resolving a context variable for this template. // Execute the `TcbVariableOp` associated with the `TmplAstVariable`. - return this.resolveOp(this.varMap.get(ref) !); + return this.resolveOp(this.varMap.get(ref)!); } else if ( ref instanceof TmplAstTemplate && directive === undefined && this.templateCtxOpMap.has(ref)) { // Resolving the context of the given sub-template. // Execute the `TcbTemplateContextOp` for the template. - return this.resolveOp(this.templateCtxOpMap.get(ref) !); + return this.resolveOp(this.templateCtxOpMap.get(ref)!); } else if ( (ref instanceof TmplAstElement || ref instanceof TmplAstTemplate) && directive !== undefined && this.directiveOpMap.has(ref)) { // Resolving a directive on an element or sub-template. - const dirMap = this.directiveOpMap.get(ref) !; + const dirMap = this.directiveOpMap.get(ref)!; if (dirMap.has(directive)) { - return this.resolveOp(dirMap.get(directive) !); + return this.resolveOp(dirMap.get(directive)!); } else { return null; } } else if (ref instanceof TmplAstElement && this.elementOpMap.has(ref)) { // Resolving the DOM node of an element in this template. - return this.resolveOp(this.elementOpMap.get(ref) !); + return this.resolveOp(this.elementOpMap.get(ref)!); } else { return null; } @@ -1261,14 +1269,13 @@ function tcbCallTypeCtor( type TcbDirectiveInput = { type: 'binding'; field: string; expression: ts.Expression; sourceSpan: ParseSourceSpan; -} | -{ +}|{ type: 'unset'; field: string; }; function tcbGetDirectiveInputs( - el: TmplAstElement | TmplAstTemplate, dir: TypeCheckableDirectiveMeta, tcb: Context, + el: TmplAstElement|TmplAstTemplate, dir: TypeCheckableDirectiveMeta, tcb: Context, scope: Scope): TcbDirectiveInput[] { // Only the first binding to a property is written. // TODO(alxhub): produce an error for duplicate bindings to the same property, independently of @@ -1306,7 +1313,7 @@ function tcbGetDirectiveInputs( * Add a binding expression to the map for each input/template attribute of the directive that has * a matching binding. */ - function processAttribute(attr: TmplAstBoundAttribute | TmplAstTextAttribute): void { + function processAttribute(attr: TmplAstBoundAttribute|TmplAstTextAttribute): void { // Skip non-property bindings. if (attr instanceof TmplAstBoundAttribute && attr.type !== BindingType.Property) { return; @@ -1321,7 +1328,7 @@ function tcbGetDirectiveInputs( if (!propMatch.has(attr.name)) { return; } - const field = propMatch.get(attr.name) !; + const field = propMatch.get(attr.name)!; // Skip the attribute if a previous binding also wrote to it. if (directiveInputs.has(field)) { @@ -1369,7 +1376,7 @@ const enum EventParamType { */ function tcbCreateEventHandler( event: TmplAstBoundEvent, tcb: Context, scope: Scope, - eventType: EventParamType | ts.TypeNode): ts.Expression { + eventType: EventParamType|ts.TypeNode): ts.Expression { const handler = tcbEventHandlerExpression(event.handler, tcb, scope); let eventParamType: ts.TypeNode|undefined; diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_file.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_file.ts index 5df3ab2fb8..1b5f93f247 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_file.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_file.ts @@ -78,7 +78,9 @@ export class TypeCheckFile extends Environment { this.fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); } - getPreludeStatements(): ts.Statement[] { return []; } + getPreludeStatements(): ts.Statement[] { + return []; + } } export function typeCheckFilePath(rootDirs: AbsoluteFsPath[]): AbsoluteFsPath { diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.ts index 55c559f655..de5621bd2b 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.ts @@ -15,8 +15,7 @@ import {TypeParameterEmitter} from './type_parameter_emitter'; export function generateTypeCtorDeclarationFn( node: ClassDeclaration, meta: TypeCtorMetadata, nodeTypeRef: ts.EntityName, - typeParams: ts.TypeParameterDeclaration[] | undefined, - reflector: ReflectionHost): ts.Statement { + typeParams: ts.TypeParameterDeclaration[]|undefined, reflector: ReflectionHost): ts.Statement { if (requiresInlineTypeCtor(node, reflector)) { throw new Error(`${node.name.text} requires an inline type constructor`); } @@ -32,7 +31,8 @@ export function generateTypeCtorDeclarationFn( const fnType = ts.createFunctionTypeNode( /* typeParameters */ typeParameters, /* parameters */[initParam], - /* type */ rawType, ); + /* type */ rawType, + ); const decl = ts.createVariableDeclaration( /* name */ meta.fnName, @@ -121,7 +121,8 @@ export function generateInlineTypeCtor( /* typeParameters */ typeParametersWithDefaultTypes(node.typeParameters), /* parameters */[initParam], /* type */ rawType, - /* body */ body, ); + /* body */ body, + ); } function constructTypeCtorParameter( @@ -149,7 +150,8 @@ function constructTypeCtorParameter( /* modifiers */ undefined, /* name */ key, /* questionToken */ undefined, - /* type */ ts.createTypeQueryNode( + /* type */ + ts.createTypeQueryNode( ts.createQualifiedName(rawType.typeName, `ngAcceptInputType_${key}`)), /* initializer */ undefined)); } @@ -243,9 +245,8 @@ function checkIfGenericTypeBoundsAreContextFree( * * This correctly infers `T` as `any`, and therefore `_t3` as `NgFor`. */ -function typeParametersWithDefaultTypes( - params: ReadonlyArray| undefined): ts.TypeParameterDeclaration[]| - undefined { +function typeParametersWithDefaultTypes(params: ReadonlyArray| + undefined): ts.TypeParameterDeclaration[]|undefined { if (params === undefined) { return undefined; } diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/type_emitter.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/type_emitter.ts index 877235ef4b..a1befba593 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/type_emitter.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/type_emitter.ts @@ -12,7 +12,7 @@ import {Reference} from '../../imports'; * A resolved type reference can either be a `Reference`, the original `ts.TypeReferenceNode` itself * or null to indicate the no reference could be resolved. */ -export type ResolvedTypeReference = Reference | ts.TypeReferenceNode | null; +export type ResolvedTypeReference = Reference|ts.TypeReferenceNode|null; /** * A type reference resolver function is responsible for finding the declaration of the type @@ -111,7 +111,9 @@ export class TypeEmitter { visitTypeReferenceNode: type => this.emitTypeReference(type), visitArrayTypeNode: type => ts.updateArrayTypeNode(type, this.emitType(type.elementType)), visitKeywordType: type => type, - visitOtherType: () => { throw new Error('Unable to emit a complex type'); }, + visitOtherType: () => { + throw new Error('Unable to emit a complex type'); + }, }); } @@ -137,8 +139,8 @@ export class TypeEmitter { const emittedType = this.emitReference(reference); if (!ts.isTypeReferenceNode(emittedType)) { - throw new Error( - `Expected TypeReferenceNode for emitted reference, got ${ts.SyntaxKind[emittedType.kind]}`); + throw new Error(`Expected TypeReferenceNode for emitted reference, got ${ + ts.SyntaxKind[emittedType.kind]}`); } typeName = emittedType.typeName; diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/type_parameter_emitter.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/type_parameter_emitter.ts index 20d6bf1b18..bf57f72803 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/type_parameter_emitter.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/type_parameter_emitter.ts @@ -10,7 +10,7 @@ import * as ts from 'typescript'; import {OwningModule, Reference} from '../../imports'; import {ReflectionHost} from '../../reflection'; -import {ResolvedTypeReference, TypeEmitter, canEmitType} from './type_emitter'; +import {canEmitType, ResolvedTypeReference, TypeEmitter} from './type_emitter'; /** @@ -92,6 +92,6 @@ export class TypeParameterEmitter { private isLocalTypeParameter(decl: ts.Declaration): boolean { // Checking for local type parameters only occurs during resolution of type parameters, so it is // guaranteed that type parameters are present. - return this.typeParameters !.some(param => param === decl); + return this.typeParameters!.some(param => param === decl); } } diff --git a/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts b/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts index 1c281971de..c691989bb9 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts @@ -8,10 +8,10 @@ import * as ts from 'typescript'; -import {TestFile, runInEachFileSystem} from '../../file_system/testing'; +import {runInEachFileSystem, TestFile} from '../../file_system/testing'; import {TypeCheckingConfig} from '../src/api'; -import {TestDeclaration, ngForDeclaration, ngForDts, typecheck} from './test_utils'; +import {ngForDeclaration, ngForDts, TestDeclaration, typecheck} from './test_utils'; runInEachFileSystem(() => { describe('template diagnostics', () => { @@ -377,8 +377,8 @@ function diagnose( return diagnostics.map(diag => { const text = typeof diag.messageText === 'string' ? diag.messageText : diag.messageText.messageText; - const fileName = diag.file !.fileName; - const {line, character} = ts.getLineAndCharacterOfPosition(diag.file !, diag.start !); + const fileName = diag.file!.fileName; + const {line, character} = ts.getLineAndCharacterOfPosition(diag.file!, diag.start!); return `${fileName}(${line + 1}, ${character + 1}): ${text}`; }); } diff --git a/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts b/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts index 1f1a35a058..81279b37bb 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {TestDeclaration, tcb} from './test_utils'; +import {tcb, TestDeclaration} from './test_utils'; describe('type check blocks diagnostics', () => { describe('parse spans', () => { diff --git a/packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts b/packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts index da668db467..89d7d5c0b2 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts @@ -6,16 +6,16 @@ * found in the LICENSE file at https://angular.io/license */ -import {CssSelector, ParseSourceFile, ParseSourceSpan, R3TargetBinder, SchemaMetadata, SelectorMatcher, TmplAstElement, TmplAstReference, Type, parseTemplate} from '@angular/compiler'; +import {CssSelector, ParseSourceFile, ParseSourceSpan, parseTemplate, R3TargetBinder, SchemaMetadata, SelectorMatcher, TmplAstElement, TmplAstReference, Type} from '@angular/compiler'; import * as ts from 'typescript'; -import {AbsoluteFsPath, LogicalFileSystem, absoluteFrom} from '../../file_system'; +import {absoluteFrom, AbsoluteFsPath, LogicalFileSystem} from '../../file_system'; import {TestFile} from '../../file_system/testing'; import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, Reference, ReferenceEmitter} from '../../imports'; -import {ClassDeclaration, TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection'; +import {ClassDeclaration, isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {makeProgram} from '../../testing'; import {getRootDirs} from '../../util/src/typescript'; -import {TemplateId, TemplateSourceMapping, TypeCheckBlockMetadata, TypeCheckableDirectiveMeta, TypeCheckingConfig} from '../src/api'; +import {TemplateId, TemplateSourceMapping, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata, TypeCheckingConfig} from '../src/api'; import {TypeCheckContext} from '../src/context'; import {DomSchemaChecker} from '../src/dom'; import {Environment} from '../src/environment'; @@ -168,23 +168,20 @@ export const ALL_ENABLED_CONFIG: TypeCheckingConfig = { }; // Remove 'ref' from TypeCheckableDirectiveMeta and add a 'selector' instead. -export type TestDirective = - Partial>>& - { - selector: string, - name: string, file?: AbsoluteFsPath, - type: 'directive', coercedInputFields?: string[], - }; +export type TestDirective = Partial>>&{ + selector: string, + name: string, + file?: AbsoluteFsPath, type: 'directive', + coercedInputFields?: string[], +}; export type TestPipe = { name: string, - file?: AbsoluteFsPath, - pipeName: string, - type: 'pipe', + file?: AbsoluteFsPath, pipeName: string, type: 'pipe', }; -export type TestDeclaration = TestDirective | TestPipe; +export type TestDeclaration = TestDirective|TestPipe; export function tcb( template: string, declarations: TestDeclaration[] = [], config?: TypeCheckingConfig, @@ -252,7 +249,7 @@ export function typecheck( ]; const {program, host, options} = makeProgram(files, {strictNullChecks: true, noImplicitAny: true, ...opts}, undefined, false); - const sf = program.getSourceFile(absoluteFrom('/main.ts')) !; + const sf = program.getSourceFile(absoluteFrom('/main.ts'))!; const checker = program.getTypeChecker(); const logicalFs = new LogicalFileSystem(getRootDirs(host, options)); const reflectionHost = new TypeScriptReflectionHost(checker); @@ -277,7 +274,7 @@ export function typecheck( const {matcher, pipes} = prepareDeclarations(declarations, decl => { let declFile = sf; if (decl.file !== undefined) { - declFile = program.getSourceFile(decl.file) !; + declFile = program.getSourceFile(decl.file)!; if (declFile === undefined) { throw new Error(`Unable to locate ${decl.file} for ${decl.type} ${decl.name}`); } @@ -356,7 +353,9 @@ class FakeEnvironment /* implements Environment */ { return ts.createParen(ts.createAsExpression(ts.createNull(), this.referenceType(ref))); } - declareOutputHelper(): ts.Expression { return ts.createIdentifier('_outputHelper'); } + declareOutputHelper(): ts.Expression { + return ts.createIdentifier('_outputHelper'); + } reference(ref: Reference>): ts.Expression { return ref.node.name; @@ -379,7 +378,9 @@ class FakeEnvironment /* implements Environment */ { return ts.createTypeReferenceNode(qName, typeArgs.length > 0 ? typeArgs : undefined); } - getPreludeStatements(): ts.Statement[] { return []; } + getPreludeStatements(): ts.Statement[] { + return []; + } static newFake(config: TypeCheckingConfig): Environment { return new FakeEnvironment(config) as Environment; @@ -387,7 +388,9 @@ class FakeEnvironment /* implements Environment */ { } export class NoopSchemaChecker implements DomSchemaChecker { - get diagnostics(): ReadonlyArray { return []; } + get diagnostics(): ReadonlyArray { + return []; + } checkElement(id: string, element: TmplAstElement, schemas: SchemaMetadata[]): void {} checkProperty( @@ -396,7 +399,9 @@ export class NoopSchemaChecker implements DomSchemaChecker { } export class NoopOobRecorder implements OutOfBandDiagnosticRecorder { - get diagnostics(): ReadonlyArray { return []; } + get diagnostics(): ReadonlyArray { + return []; + } missingReferenceTarget(): void {} missingPipe(): void {} illegalAssignmentToTemplateVar(): void {} diff --git a/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts b/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts index 05d9d4cbe4..f69af3763b 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts @@ -8,12 +8,13 @@ import {TypeCheckingConfig} from '../src/api'; -import {ALL_ENABLED_CONFIG, TestDeclaration, TestDirective, tcb} from './test_utils'; +import {ALL_ENABLED_CONFIG, tcb, TestDeclaration, TestDirective} from './test_utils'; describe('type check blocks', () => { - it('should generate a basic block for a binding', - () => { expect(tcb('{{hello}} {{world}}')).toContain('"" + (ctx).hello + (ctx).world;'); }); + it('should generate a basic block for a binding', () => { + expect(tcb('{{hello}} {{world}}')).toContain('"" + (ctx).hello + (ctx).world;'); + }); it('should generate literal map expressions', () => { const TEMPLATE = '{{ method({foo: a, bar: b}) }}'; @@ -264,7 +265,6 @@ describe('type check blocks', () => { }); describe('outputs', () => { - it('should emit subscribe calls for directive outputs', () => { const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', @@ -305,7 +305,6 @@ describe('type check blocks', () => { expect(block).toContain( '_t3.addEventListener("event", function ($event): any { (_t2 = 3); });'); }); - }); describe('config', () => { @@ -385,7 +384,6 @@ describe('type check blocks', () => { }); describe('config.checkTypeOfBindings', () => { - it('should check types of bindings when enabled', () => { const TEMPLATE = `
`; const block = tcb(TEMPLATE, DIRECTIVES); diff --git a/packages/compiler-cli/src/ngtsc/typecheck/test/type_constructor_spec.ts b/packages/compiler-cli/src/ngtsc/typecheck/test/type_constructor_spec.ts index 0dbcd2f9bd..9f9e1e141c 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/test/type_constructor_spec.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/test/type_constructor_spec.ts @@ -6,14 +6,16 @@ * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; -import {LogicalFileSystem, absoluteFrom, getSourceFileOrError} from '../../file_system'; -import {TestFile, runInEachFileSystem} from '../../file_system/testing'; + +import {absoluteFrom, getSourceFileOrError, LogicalFileSystem} from '../../file_system'; +import {runInEachFileSystem, TestFile} from '../../file_system/testing'; import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, Reference, ReferenceEmitter} from '../../imports'; -import {TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection'; +import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {getRootDirs} from '../../util/src/typescript'; import {TypeCheckContext} from '../src/context'; import {TypeCheckFile} from '../src/type_check_file'; + import {ALL_ENABLED_CONFIG} from './test_utils'; runInEachFileSystem(() => { @@ -42,7 +44,7 @@ runInEachFileSystem(() => { it('should not produce an empty SourceFile when there is nothing to typecheck', () => { const file = new TypeCheckFile( _('/_typecheck_.ts'), ALL_ENABLED_CONFIG, new ReferenceEmitter([]), - /* reflector */ null !); + /* reflector */ null!); const sf = file.render(); expect(sf.statements.length).toBe(1); }); @@ -126,7 +128,7 @@ TestClass.ngTypeCtor({value: 'test'}); const res = ctx.calculateTemplateDiagnostics(program, host, options); const TestClassWithCtor = getDeclaration(res.program, _('/main.ts'), 'TestClass', isNamedClassDeclaration); - const typeCtor = TestClassWithCtor.members.find(isTypeCtor) !; + const typeCtor = TestClassWithCtor.members.find(isTypeCtor)!; expect(typeCtor.getText()).not.toContain('queryField'); }); }); @@ -168,7 +170,7 @@ TestClass.ngTypeCtor({value: 'test'}); const res = ctx.calculateTemplateDiagnostics(program, host, options); const TestClassWithCtor = getDeclaration(res.program, _('/main.ts'), 'TestClass', isNamedClassDeclaration); - const typeCtor = TestClassWithCtor.members.find(isTypeCtor) !; + const typeCtor = TestClassWithCtor.members.find(isTypeCtor)!; const ctorText = typeCtor.getText().replace(/[ \r\n]+/g, ' '); expect(ctorText).toContain( 'init: Pick | { bar: typeof TestClass.ngAcceptInputType_bar; }'); diff --git a/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts b/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts index 099573ebb2..5d80d09a01 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts @@ -8,16 +8,16 @@ import * as ts from 'typescript'; import {absoluteFrom} from '../../file_system'; -import {TestFile, runInEachFileSystem} from '../../file_system/testing'; -import {TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection'; +import {runInEachFileSystem, TestFile} from '../../file_system/testing'; +import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {TypeParameterEmitter} from '../src/type_parameter_emitter'; + import {angularCoreDts} from './test_utils'; runInEachFileSystem(() => { describe('type parameter emitter', () => { - function createEmitter(source: string, additionalFiles: TestFile[] = []) { const files: TestFile[] = [ angularCoreDts(), {name: absoluteFrom('/main.ts'), contents: source}, ...additionalFiles @@ -34,7 +34,7 @@ runInEachFileSystem(() => { function emit(emitter: TypeParameterEmitter) { const emitted = emitter.emit(ref => { - const typeName = ts.createQualifiedName(ts.createIdentifier('test'), ref.debugName !); + const typeName = ts.createQualifiedName(ts.createIdentifier('test'), ref.debugName!); return ts.createTypeReferenceNode(typeName, /* typeArguments */ undefined); }); @@ -209,6 +209,5 @@ runInEachFileSystem(() => { expect(emitter.canEmit()).toBe(true); expect(emit(emitter)).toEqual(''); }); - }); }); diff --git a/packages/compiler-cli/src/ngtsc/util/src/ts_source_map_bug_29300.ts b/packages/compiler-cli/src/ngtsc/util/src/ts_source_map_bug_29300.ts index ede59091e1..83148904e7 100644 --- a/packages/compiler-cli/src/ngtsc/util/src/ts_source_map_bug_29300.ts +++ b/packages/compiler-cli/src/ngtsc/util/src/ts_source_map_bug_29300.ts @@ -29,16 +29,38 @@ export function tsSourceMapBug29300Fixed() { const sourceFile = ts.createSourceFile('test.ts', 'a;', ts.ScriptTarget.ES2015, true, ts.ScriptKind.TS); const host = { - getSourceFile(): ts.SourceFile | undefined{return sourceFile;}, - fileExists(): boolean{return true;}, - readFile(): string | undefined{return '';}, - writeFile(fileName: string, data: string) { writtenFiles[fileName] = data; }, - getDefaultLibFileName(): string{return '';}, - getCurrentDirectory(): string{return '';}, - getDirectories(): string[]{return [];}, - getCanonicalFileName(): string{return '';}, - useCaseSensitiveFileNames(): boolean{return true;}, - getNewLine(): string{return '\n';}, + getSourceFile(): ts.SourceFile | + undefined { + return sourceFile; + }, + fileExists(): boolean { + return true; + }, + readFile(): string | + undefined { + return ''; + }, + writeFile(fileName: string, data: string) { + writtenFiles[fileName] = data; + }, + getDefaultLibFileName(): string { + return ''; + }, + getCurrentDirectory(): string { + return ''; + }, + getDirectories(): string[] { + return []; + }, + getCanonicalFileName(): string { + return ''; + }, + useCaseSensitiveFileNames(): boolean { + return true; + }, + getNewLine(): string { + return '\n'; + }, }; const transform = (context: ts.TransformationContext) => { diff --git a/packages/compiler-cli/src/ngtsc/util/src/typescript.ts b/packages/compiler-cli/src/ngtsc/util/src/typescript.ts index 68e71b5673..dc38c2a96c 100644 --- a/packages/compiler-cli/src/ngtsc/util/src/typescript.ts +++ b/packages/compiler-cli/src/ngtsc/util/src/typescript.ts @@ -28,7 +28,7 @@ export function isFromDtsFile(node: ts.Node): boolean { return sf !== undefined && sf.isDeclarationFile; } -export function nodeNameForError(node: ts.Node & {name?: ts.Node}): string { +export function nodeNameForError(node: ts.Node&{name?: ts.Node}): string { if (node.name !== undefined && ts.isIdentifier(node.name)) { return node.name.text; } else { @@ -58,7 +58,7 @@ export function getTokenAtPosition(sf: ts.SourceFile, pos: number): ts.Node { return (ts as any).getTokenAtPosition(sf, pos); } -export function identifierOfNode(decl: ts.Node & {name?: ts.Node}): ts.Identifier|null { +export function identifierOfNode(decl: ts.Node&{name?: ts.Node}): ts.Identifier|null { if (decl.name !== undefined && ts.isIdentifier(decl.name)) { return decl.name; } else { @@ -123,7 +123,7 @@ export function nodeDebugInfo(node: ts.Node): string { export function resolveModuleName( moduleName: string, containingFile: string, compilerOptions: ts.CompilerOptions, compilerHost: ts.CompilerHost, - moduleResolutionCache: ts.ModuleResolutionCache | null): ts.ResolvedModule|undefined { + moduleResolutionCache: ts.ModuleResolutionCache|null): ts.ResolvedModule|undefined { if (compilerHost.resolveModuleNames) { // FIXME: Additional parameters are required in TS3.6, but ignored in 3.5. // Remove the any cast once google3 is fully on TS3.6. diff --git a/packages/compiler-cli/src/ngtsc/util/src/visitor.ts b/packages/compiler-cli/src/ngtsc/util/src/visitor.ts index 2c96f9304c..fe2ac3377c 100644 --- a/packages/compiler-cli/src/ngtsc/util/src/visitor.ts +++ b/packages/compiler-cli/src/ngtsc/util/src/visitor.ts @@ -68,7 +68,9 @@ export abstract class Visitor { /** * Visit types of nodes which don't have their own explicit visitor. */ - visitOtherNode(node: T): T { return node; } + visitOtherNode(node: T): T { + return node; + } /** * @internal @@ -81,8 +83,9 @@ export abstract class Visitor { node = ts.visitEachChild(node, child => this._visit(child, context), context) as T; if (ts.isClassDeclaration(node)) { - visitedNode = this._visitListEntryNode( - node, (node: ts.ClassDeclaration) => this.visitClassDeclaration(node)) as typeof node; + visitedNode = + this._visitListEntryNode( + node, (node: ts.ClassDeclaration) => this.visitClassDeclaration(node)) as typeof node; } else { visitedNode = this.visitOtherNode(node); } @@ -111,12 +114,12 @@ export abstract class Visitor { const newStatements: ts.Statement[] = []; clone.statements.forEach(stmt => { if (this._before.has(stmt)) { - newStatements.push(...(this._before.get(stmt) !as ts.Statement[])); + newStatements.push(...(this._before.get(stmt)! as ts.Statement[])); this._before.delete(stmt); } newStatements.push(stmt); if (this._after.has(stmt)) { - newStatements.push(...(this._after.get(stmt) !as ts.Statement[])); + newStatements.push(...(this._after.get(stmt)! as ts.Statement[])); this._after.delete(stmt); } }); @@ -126,6 +129,6 @@ export abstract class Visitor { } function hasStatements(node: ts.Node): node is ts.Node&{statements: ts.NodeArray} { - const block = node as{statements?: any}; + const block = node as {statements?: any}; return block.statements !== undefined && Array.isArray(block.statements); } diff --git a/packages/compiler-cli/src/ngtsc/util/test/visitor_spec.ts b/packages/compiler-cli/src/ngtsc/util/test/visitor_spec.ts index 7ecbc89aa2..c875cc8ddb 100644 --- a/packages/compiler-cli/src/ngtsc/util/test/visitor_spec.ts +++ b/packages/compiler-cli/src/ngtsc/util/test/visitor_spec.ts @@ -6,22 +6,22 @@ * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; + import {absoluteFrom, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {makeProgram} from '../../testing'; -import {VisitListEntryResult, Visitor, visit} from '../src/visitor'; +import {visit, VisitListEntryResult, Visitor} from '../src/visitor'; class TestAstVisitor extends Visitor { visitClassDeclaration(node: ts.ClassDeclaration): VisitListEntryResult { - const name = node.name !.text; - const statics = - node.members.filter(member => (member.modifiers as ReadonlyArray|| [ - ]).some(mod => mod.kind === ts.SyntaxKind.StaticKeyword)); - const idStatic = statics - .find( - el => ts.isPropertyDeclaration(el) && ts.isIdentifier(el.name) && - el.name.text === 'id') as ts.PropertyDeclaration | + const name = node.name!.text; + const statics = node.members.filter( + member => (member.modifiers as ReadonlyArray|| + []).some(mod => mod.kind === ts.SyntaxKind.StaticKeyword)); + const idStatic = statics.find( + el => ts.isPropertyDeclaration(el) && ts.isIdentifier(el.name) && + el.name.text === 'id') as ts.PropertyDeclaration | undefined; if (idStatic !== undefined) { return { diff --git a/packages/compiler-cli/src/perform_compile.ts b/packages/compiler-cli/src/perform_compile.ts index b746e6ced5..5456d2f0e4 100644 --- a/packages/compiler-cli/src/perform_compile.ts +++ b/packages/compiler-cli/src/perform_compile.ts @@ -6,10 +6,10 @@ * found in the LICENSE file at https://angular.io/license */ -import {Position, isSyntaxError} from '@angular/compiler'; +import {isSyntaxError, Position} from '@angular/compiler'; import * as ts from 'typescript'; -import {AbsoluteFsPath, absoluteFrom, getFileSystem, relative, resolve} from '../src/ngtsc/file_system'; +import {absoluteFrom, AbsoluteFsPath, getFileSystem, relative, resolve} from '../src/ngtsc/file_system'; import {replaceTsWithNgInErrors} from './ngtsc/diagnostics'; import * as api from './transformers/api'; @@ -35,7 +35,7 @@ function displayFileName(fileName: string, host: ts.FormatDiagnosticsHost): stri export function formatDiagnosticPosition( position: Position, host: ts.FormatDiagnosticsHost = defaultFormatHost): string { - return `${displayFileName(position.fileName, host)}(${position.line + 1},${position.column+1})`; + return `${displayFileName(position.fileName, host)}(${position.line + 1},${position.column + 1})`; } export function flattenDiagnosticMessageChain( @@ -73,11 +73,10 @@ export function formatDiagnostic( const newLine = host.getNewLine(); const span = diagnostic.span; if (span) { - result += `${formatDiagnosticPosition({ - fileName: span.start.file.url, - line: span.start.line, - column: span.start.col - }, host)}: `; + result += `${ + formatDiagnosticPosition( + {fileName: span.start.file.url, line: span.start.line, column: span.start.col}, + host)}: `; } else if (diagnostic.position) { result += `${formatDiagnosticPosition(diagnostic.position, host)}: `; } @@ -156,8 +155,10 @@ export function readConfiguration( // other options like 'compilerOptions' are merged by TS const baseConfig = existingConfig || config; if (existingConfig) { - baseConfig.angularCompilerOptions = {...config.angularCompilerOptions, - ...baseConfig.angularCompilerOptions}; + baseConfig.angularCompilerOptions = { + ...config.angularCompilerOptions, + ...baseConfig.angularCompilerOptions + }; } if (config.extends) { @@ -223,7 +224,7 @@ export interface PerformCompilationResult { emitResult?: ts.EmitResult; } -export function exitCodeFromResult(diags: Diagnostics | undefined): number { +export function exitCodeFromResult(diags: Diagnostics|undefined): number { if (!diags || filterErrorsAndWarnings(diags).length === 0) { // If we have a result and didn't get any errors, we succeeded. return 0; @@ -233,21 +234,29 @@ export function exitCodeFromResult(diags: Diagnostics | undefined): number { return diags.some(d => d.source === 'angular' && d.code === api.UNKNOWN_ERROR_CODE) ? 2 : 1; } -export function performCompilation( - {rootNames, options, host, oldProgram, emitCallback, mergeEmitResultsCallback, - gatherDiagnostics = defaultGatherDiagnostics, customTransformers, - emitFlags = api.EmitFlags.Default, modifiedResourceFiles = null}: { - rootNames: string[], - options: api.CompilerOptions, - host?: api.CompilerHost, - oldProgram?: api.Program, - emitCallback?: api.TsEmitCallback, - mergeEmitResultsCallback?: api.TsMergeEmitResultsCallback, - gatherDiagnostics?: (program: api.Program) => Diagnostics, - customTransformers?: api.CustomTransformers, - emitFlags?: api.EmitFlags, - modifiedResourceFiles?: Set| null, - }): PerformCompilationResult { +export function performCompilation({ + rootNames, + options, + host, + oldProgram, + emitCallback, + mergeEmitResultsCallback, + gatherDiagnostics = defaultGatherDiagnostics, + customTransformers, + emitFlags = api.EmitFlags.Default, + modifiedResourceFiles = null +}: { + rootNames: string[], + options: api.CompilerOptions, + host?: api.CompilerHost, + oldProgram?: api.Program, + emitCallback?: api.TsEmitCallback, + mergeEmitResultsCallback?: api.TsMergeEmitResultsCallback, + gatherDiagnostics?: (program: api.Program) => Diagnostics, + customTransformers?: api.CustomTransformers, + emitFlags?: api.EmitFlags, + modifiedResourceFiles?: Set| null, +}): PerformCompilationResult { let program: api.Program|undefined; let emitResult: ts.EmitResult|undefined; let allDiagnostics: Array = []; @@ -262,7 +271,7 @@ export function performCompilation( program = ng.createProgram({rootNames, host, options, oldProgram}); const beforeDiags = Date.now(); - allDiagnostics.push(...gatherDiagnostics(program !)); + allDiagnostics.push(...gatherDiagnostics(program!)); if (options.diagnostics) { const afterDiags = Date.now(); allDiagnostics.push( @@ -271,7 +280,7 @@ export function performCompilation( if (!hasErrors(allDiagnostics)) { emitResult = - program !.emit({emitCallback, mergeEmitResultsCallback, customTransformers, emitFlags}); + program!.emit({emitCallback, mergeEmitResultsCallback, customTransformers, emitFlags}); allDiagnostics.push(...emitResult.diagnostics); return {diagnostics: allDiagnostics, program, emitResult}; } @@ -297,7 +306,7 @@ export function performCompilation( export function defaultGatherDiagnostics(program: api.Program): Diagnostics { const allDiagnostics: Array = []; - function checkDiagnostics(diags: Diagnostics | undefined) { + function checkDiagnostics(diags: Diagnostics|undefined) { if (diags) { allDiagnostics.push(...diags); return !hasErrors(diags); diff --git a/packages/compiler-cli/src/perform_watch.ts b/packages/compiler-cli/src/perform_watch.ts index 2d406686ac..36aa3e6a66 100644 --- a/packages/compiler-cli/src/perform_watch.ts +++ b/packages/compiler-cli/src/perform_watch.ts @@ -10,7 +10,7 @@ import * as chokidar from 'chokidar'; import * as path from 'path'; import * as ts from 'typescript'; -import {Diagnostics, ParsedConfiguration, PerformCompilationResult, exitCodeFromResult, performCompilation, readConfiguration} from './perform_compile'; +import {Diagnostics, exitCodeFromResult, ParsedConfiguration, performCompilation, PerformCompilationResult, readConfiguration} from './perform_compile'; import * as api from './transformers/api'; import {createCompilerHost} from './transformers/entry_points'; import {createMessageDiagnostic} from './transformers/util'; @@ -50,8 +50,9 @@ export interface PerformWatchHost { export function createPerformWatchHost( configFileName: string, reportDiagnostics: (diagnostics: Diagnostics) => void, - existingOptions?: ts.CompilerOptions, createEmitCallback?: (options: api.CompilerOptions) => - api.TsEmitCallback | undefined): PerformWatchHost { + existingOptions?: ts.CompilerOptions, + createEmitCallback?: (options: api.CompilerOptions) => + api.TsEmitCallback | undefined): PerformWatchHost { return { reportDiagnostics: reportDiagnostics, createCompilerHost: options => createCompilerHost({options}), @@ -130,7 +131,7 @@ export function performWatchCompilation(host: PerformWatchHost): // Note: ! is ok as options are filled after the first compilation // Note: ! is ok as resolvedReadyPromise is filled by the previous call const fileWatcher = - host.onFileChange(cachedOptions !.options, watchedFileChanged, resolveReadyPromise !); + host.onFileChange(cachedOptions!.options, watchedFileChanged, resolveReadyPromise!); return {close, ready: cb => readyPromise.then(cb), firstCompileResult}; @@ -177,7 +178,7 @@ export function performWatchCompilation(host: PerformWatchHost): if (ce.exists == null) { ce.exists = originalFileExists.call(this, fileName); } - return ce.exists !; + return ce.exists!; }; const originalGetSourceFile = cachedCompilerHost.getSourceFile; cachedCompilerHost.getSourceFile = function( @@ -186,7 +187,7 @@ export function performWatchCompilation(host: PerformWatchHost): if (!ce.sf) { ce.sf = originalGetSourceFile.call(this, fileName, languageVersion); } - return ce.sf !; + return ce.sf!; }; const originalReadFile = cachedCompilerHost.readFile; cachedCompilerHost.readFile = function(fileName: string) { @@ -194,7 +195,7 @@ export function performWatchCompilation(host: PerformWatchHost): if (ce.content == null) { ce.content = originalReadFile.call(this, fileName); } - return ce.content !; + return ce.content!; }; // Provide access to the file paths that triggered this rebuild cachedCompilerHost.getModifiedResourceFiles = function() { diff --git a/packages/compiler-cli/src/transformers/api.ts b/packages/compiler-cli/src/transformers/api.ts index 17da6f47d3..bde02a1a28 100644 --- a/packages/compiler-cli/src/transformers/api.ts +++ b/packages/compiler-cli/src/transformers/api.ts @@ -190,8 +190,12 @@ export interface TsEmitArguments { customTransformers?: ts.CustomTransformers; } -export interface TsEmitCallback { (args: TsEmitArguments): ts.EmitResult; } -export interface TsMergeEmitResultsCallback { (results: ts.EmitResult[]): ts.EmitResult; } +export interface TsEmitCallback { + (args: TsEmitArguments): ts.EmitResult; +} +export interface TsMergeEmitResultsCallback { + (results: ts.EmitResult[]): ts.EmitResult; +} export interface LibrarySummary { fileName: string; @@ -283,14 +287,14 @@ export interface Program { * * Angular structural information is required to emit files. */ - emit({emitFlags, cancellationToken, customTransformers, emitCallback, - mergeEmitResultsCallback}?: { - emitFlags?: EmitFlags, - cancellationToken?: ts.CancellationToken, - customTransformers?: CustomTransformers, - emitCallback?: TsEmitCallback, - mergeEmitResultsCallback?: TsMergeEmitResultsCallback - }): ts.EmitResult; + emit({emitFlags, cancellationToken, customTransformers, emitCallback, mergeEmitResultsCallback}?: + { + emitFlags?: EmitFlags, + cancellationToken?: ts.CancellationToken, + customTransformers?: CustomTransformers, + emitCallback?: TsEmitCallback, + mergeEmitResultsCallback?: TsMergeEmitResultsCallback + }): ts.EmitResult; /** * Returns the .d.ts / .ngsummary.json / .ngfactory.d.ts files of libraries that have been emitted diff --git a/packages/compiler-cli/src/transformers/compiler_host.ts b/packages/compiler-cli/src/transformers/compiler_host.ts index 353b1884d8..5efb487d2d 100644 --- a/packages/compiler-cli/src/transformers/compiler_host.ts +++ b/packages/compiler-cli/src/transformers/compiler_host.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {AotCompilerHost, EmitterVisitorContext, GeneratedFile, ParseSourceSpan, TypeScriptEmitter, collectExternalReferences, syntaxError} from '@angular/compiler'; +import {AotCompilerHost, collectExternalReferences, EmitterVisitorContext, GeneratedFile, ParseSourceSpan, syntaxError, TypeScriptEmitter} from '@angular/compiler'; import * as path from 'path'; import * as ts from 'typescript'; @@ -15,7 +15,7 @@ import {ModuleMetadata} from '../metadata/index'; import {join} from '../ngtsc/file_system'; import {CompilerHost, CompilerOptions, LibrarySummary} from './api'; -import {MetadataReaderHost, createMetadataReaderCache, readMetadata} from './metadata_reader'; +import {createMetadataReaderCache, MetadataReaderHost, readMetadata} from './metadata_reader'; import {DTS, GENERATED_FILES, isInRootDir, relativeToRootDirs} from './util'; const NODE_MODULES_PACKAGE_NAME = /node_modules\/((\w|-|\.)+|(@(\w|-|\.)+\/(\w|-|\.)+))/; @@ -24,8 +24,8 @@ const CSS_PREPROCESSOR_EXT = /(\.scss|\.sass|\.less|\.styl)$/; let wrapHostForTest: ((host: ts.CompilerHost) => ts.CompilerHost)|null = null; -export function setWrapHostForTest(wrapFn: ((host: ts.CompilerHost) => ts.CompilerHost) | null): - void { +export function setWrapHostForTest(wrapFn: ((host: ts.CompilerHost) => ts.CompilerHost)| + null): void { wrapHostForTest = wrapFn; } @@ -53,11 +53,11 @@ export interface CodeGenerator { findGeneratedFileNames(fileName: string): string[]; } -function assert(condition: T | null | undefined) { +function assert(condition: T|null|undefined) { if (!condition) { // TODO(chuckjaz): do the right thing } - return condition !; + return condition!; } /** @@ -67,7 +67,7 @@ function assert(condition: T | null | undefined) { * - TypeCheckHost for mapping ts errors to ng errors (via translateDiagnostics) */ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHost, AotCompilerHost, - TypeCheckHost { + TypeCheckHost { private metadataReaderCache = createMetadataReaderCache(); private fileNameToModuleNameCache = new Map(); private flatModuleIndexCache = new Map(); @@ -83,13 +83,13 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos private metadataReaderHost: MetadataReaderHost; // TODO(issue/24571): remove '!'. - getCancellationToken !: () => ts.CancellationToken; + getCancellationToken!: () => ts.CancellationToken; // TODO(issue/24571): remove '!'. - getDefaultLibLocation !: () => string; + getDefaultLibLocation!: () => string; // TODO(issue/24571): remove '!'. - trace !: (s: string) => void; + trace!: (s: string) => void; // TODO(issue/24571): remove '!'. - getDirectories !: (path: string) => string[]; + getDirectories!: (path: string) => string[]; resolveTypeReferenceDirectives?: (names: string[], containingFile: string) => ts.ResolvedTypeReferenceDirective[]; directoryExists?: (directoryName: string) => boolean; @@ -100,21 +100,21 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos private codeGenerator: CodeGenerator, private librarySummaries = new Map()) { this.moduleResolutionCache = ts.createModuleResolutionCache( - this.context.getCurrentDirectory !(), this.context.getCanonicalFileName.bind(this.context)); - const basePath = this.options.basePath !; + this.context.getCurrentDirectory!(), this.context.getCanonicalFileName.bind(this.context)); + const basePath = this.options.basePath!; this.rootDirs = - (this.options.rootDirs || [this.options.basePath !]).map(p => path.resolve(basePath, p)); + (this.options.rootDirs || [this.options.basePath!]).map(p => path.resolve(basePath, p)); if (context.getDirectories) { - this.getDirectories = path => context.getDirectories !(path); + this.getDirectories = path => context.getDirectories!(path); } if (context.directoryExists) { - this.directoryExists = directoryName => context.directoryExists !(directoryName); + this.directoryExists = directoryName => context.directoryExists!(directoryName); } if (context.getCancellationToken) { - this.getCancellationToken = () => context.getCancellationToken !(); + this.getCancellationToken = () => context.getCancellationToken!(); } if (context.getDefaultLibLocation) { - this.getDefaultLibLocation = () => context.getDefaultLibLocation !(); + this.getDefaultLibLocation = () => context.getDefaultLibLocation!(); } if (context.resolveTypeReferenceDirectives) { // Backward compatibility with TypeScript 2.9 and older since return @@ -123,11 +123,11 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos type ts3ResolveTypeReferenceDirectives = (names: string[], containingFile: string) => ts.ResolvedTypeReferenceDirective[]; this.resolveTypeReferenceDirectives = (names: string[], containingFile: string) => - (context.resolveTypeReferenceDirectives as ts3ResolveTypeReferenceDirectives) !( - names, containingFile); + (context.resolveTypeReferenceDirectives as ts3ResolveTypeReferenceDirectives)! + (names, containingFile); } if (context.trace) { - this.trace = s => context.trace !(s); + this.trace = s => context.trace!(s); } if (context.fileNameToModuleName) { this.fileNameToModuleName = context.fileNameToModuleName.bind(context); @@ -265,8 +265,8 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos } } } else { - throw new Error( - `Trying to import a source file from a node_modules package: import ${originalImportedFile} from ${containingFile}`); + throw new Error(`Trying to import a source file from a node_modules package: import ${ + originalImportedFile} from ${containingFile}`); } this.fileNameToModuleNameCache.set(cacheKey, moduleName); @@ -325,7 +325,7 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos // Note: we need the explicit check via `has` as we also cache results // that were null / undefined. if (this.originalSourceFiles.has(filePath)) { - return this.originalSourceFiles.get(filePath) !; + return this.originalSourceFiles.get(filePath)!; } if (!languageVersion) { languageVersion = this.options.target || ts.ScriptTarget.Latest; @@ -353,8 +353,8 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos newRefs.forEach(r => refsAreEqual = refsAreEqual && oldRefs.has(r)); } if (!refsAreEqual) { - throw new Error( - `Illegal State: external references changed in ${genFile.genFileUrl}.\nOld: ${Array.from(oldRefs)}.\nNew: ${Array.from(newRefs)}`); + throw new Error(`Illegal State: external references changed in ${genFile.genFileUrl}.\nOld: ${ + Array.from(oldRefs)}.\nNew: ${Array.from(newRefs)}`); } return this.addGeneratedFile(genFile, newRefs); } @@ -381,7 +381,8 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos } this.generatedSourceFiles.set(genFile.genFileUrl, { sourceFile: sf, - emitCtx: context, externalReferences, + emitCtx: context, + externalReferences, }); return sf; } @@ -468,7 +469,7 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos } // TODO(tbosch): TypeScript's typings for getSourceFile are incorrect, // as it can very well return undefined. - return sf !; + return sf!; } private getGeneratedFile(fileName: string): ts.SourceFile|null { @@ -638,7 +639,7 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos } function genFileExternalReferences(genFile: GeneratedFile): Set { - return new Set(collectExternalReferences(genFile.stmts !).map(er => er.moduleName !)); + return new Set(collectExternalReferences(genFile.stmts!).map(er => er.moduleName!)); } function addReferencesToSourceFile(sf: ts.SourceFile, genFileNames: string[]) { diff --git a/packages/compiler-cli/src/transformers/inline_resources.ts b/packages/compiler-cli/src/transformers/inline_resources.ts index 25e4d6108f..015fad0353 100644 --- a/packages/compiler-cli/src/transformers/inline_resources.ts +++ b/packages/compiler-cli/src/transformers/inline_resources.ts @@ -8,7 +8,7 @@ import * as ts from 'typescript'; -import {MetadataObject, MetadataValue, isClassMetadata, isMetadataImportedSymbolReferenceExpression, isMetadataSymbolicCallExpression} from '../metadata/index'; +import {isClassMetadata, isMetadataImportedSymbolReferenceExpression, isMetadataSymbolicCallExpression, MetadataObject, MetadataValue} from '../metadata/index'; import {MetadataTransformer, ValueTransform} from './metadata_cache'; @@ -17,27 +17,29 @@ const PRECONDITIONS_TEXT = /** A subset of members from AotCompilerHost */ export type ResourcesHost = { - resourceNameToFileName(resourceName: string, containingFileName: string): string | null; + resourceNameToFileName(resourceName: string, containingFileName: string): string|null; loadResource(path: string): Promise| string; }; export type StaticResourceLoader = { - get(url: string | MetadataValue): string; + get(url: string|MetadataValue): string; }; function getResourceLoader(host: ResourcesHost, containingFileName: string): StaticResourceLoader { return { - get(url: string | MetadataValue): string{ + get(url: string|MetadataValue): string { if (typeof url !== 'string') { throw new Error('templateUrl and stylesUrl must be string literals. ' + PRECONDITIONS_TEXT); - } const fileName = host.resourceNameToFileName(url, containingFileName); + } + const fileName = host.resourceNameToFileName(url, containingFileName); if (fileName) { const content = host.loadResource(fileName); if (typeof content !== 'string') { throw new Error('Cannot handle async resource. ' + PRECONDITIONS_TEXT); } return content; - } throw new Error(`Failed to resolve ${url} from ${containingFileName}. ${PRECONDITIONS_TEXT}`); + } + throw new Error(`Failed to resolve ${url} from ${containingFileName}. ${PRECONDITIONS_TEXT}`); } }; } @@ -249,8 +251,7 @@ function isComponentSymbol(identifier: ts.Node, typeChecker: ts.TypeChecker) { const name = (declaration.propertyName || declaration.name).text; // We know that parent pointers are set because we created the SourceFile ourselves. // The number of parent references here match the recursion depth at this point. - const moduleId = - (declaration.parent !.parent !.parent !.moduleSpecifier as ts.StringLiteral).text; + const moduleId = (declaration.parent!.parent!.parent!.moduleSpecifier as ts.StringLiteral).text; return moduleId === '@angular/core' && name === 'Component'; } diff --git a/packages/compiler-cli/src/transformers/lower_expressions.ts b/packages/compiler-cli/src/transformers/lower_expressions.ts index 3f2bc92c78..7ded3d5198 100644 --- a/packages/compiler-cli/src/transformers/lower_expressions.ts +++ b/packages/compiler-cli/src/transformers/lower_expressions.ts @@ -9,7 +9,8 @@ import {createLoweredSymbol, isLoweredSymbol} from '@angular/compiler'; import * as ts from 'typescript'; -import {CollectorOptions, MetadataCollector, MetadataValue, ModuleMetadata, isMetadataGlobalReferenceExpression} from '../metadata/index'; +import {CollectorOptions, isMetadataGlobalReferenceExpression, MetadataCollector, MetadataValue, ModuleMetadata} from '../metadata/index'; + import {MetadataCache, MetadataTransformer, ValueTransform} from './metadata_cache'; export interface LoweringRequest { @@ -21,7 +22,10 @@ export interface LoweringRequest { export type RequestLocationMap = Map; -const enum DeclarationOrder { BeforeStmt, AfterStmt } +const enum DeclarationOrder { + BeforeStmt, + AfterStmt +} interface Declaration { name: string; @@ -201,14 +205,16 @@ export function getExpressionLoweringTransformFactory( }; } -export interface RequestsMap { getRequests(sourceFile: ts.SourceFile): RequestLocationMap; } +export interface RequestsMap { + getRequests(sourceFile: ts.SourceFile): RequestLocationMap; +} interface MetadataAndLoweringRequests { metadata: ModuleMetadata|undefined; requests: RequestLocationMap; } -function isEligibleForLowering(node: ts.Node | undefined): boolean { +function isEligibleForLowering(node: ts.Node|undefined): boolean { if (node) { switch (node.kind) { case ts.SyntaxKind.SourceFile: @@ -232,10 +238,11 @@ function isEligibleForLowering(node: ts.Node | undefined): boolean { // example) might also require lowering even if the top-level declaration is already // properly exported. const varNode = node as ts.VariableDeclaration; - return isExported || (varNode.initializer !== undefined && - (ts.isObjectLiteralExpression(varNode.initializer) || - ts.isArrayLiteralExpression(varNode.initializer) || - ts.isCallExpression(varNode.initializer))); + return isExported || + (varNode.initializer !== undefined && + (ts.isObjectLiteralExpression(varNode.initializer) || + ts.isArrayLiteralExpression(varNode.initializer) || + ts.isCallExpression(varNode.initializer))); } return isEligibleForLowering(node.parent); } @@ -264,7 +271,7 @@ function isLiteralFieldNamed(node: ts.Node, names: Set): boolean { export class LowerMetadataTransform implements RequestsMap, MetadataTransformer { // TODO(issue/24571): remove '!'. - private cache !: MetadataCache; + private cache!: MetadataCache; private requests = new Map(); private lowerableFieldNames: Set; @@ -288,7 +295,9 @@ export class LowerMetadataTransform implements RequestsMap, MetadataTransformer } // MetadataTransformer - connect(cache: MetadataCache): void { this.cache = cache; } + connect(cache: MetadataCache): void { + this.cache = cache; + } start(sourceFile: ts.SourceFile): ValueTransform|undefined { let identNumber = 0; @@ -329,7 +338,7 @@ export class LowerMetadataTransform implements RequestsMap, MetadataTransformer const hasLowerableParentCache = new Map(); - const shouldBeLowered = (node: ts.Node | undefined): boolean => { + const shouldBeLowered = (node: ts.Node|undefined): boolean => { if (node === undefined) { return false; } @@ -346,7 +355,7 @@ export class LowerMetadataTransform implements RequestsMap, MetadataTransformer return lowerable; }; - const hasLowerableParent = (node: ts.Node | undefined): boolean => { + const hasLowerableParent = (node: ts.Node|undefined): boolean => { if (node === undefined) { return false; } @@ -354,10 +363,10 @@ export class LowerMetadataTransform implements RequestsMap, MetadataTransformer hasLowerableParentCache.set( node, shouldBeLowered(node.parent) || hasLowerableParent(node.parent)); } - return hasLowerableParentCache.get(node) !; + return hasLowerableParentCache.get(node)!; }; - const isLowerable = (node: ts.Node | undefined): boolean => { + const isLowerable = (node: ts.Node|undefined): boolean => { if (node === undefined) { return false; } @@ -383,7 +392,7 @@ function createExportTableFor(sourceFile: ts.SourceFile): Set { case ts.SyntaxKind.InterfaceDeclaration: if ((ts.getCombinedModifierFlags(node as ts.Declaration) & ts.ModifierFlags.Export) != 0) { const classDeclaration = - node as(ts.ClassDeclaration | ts.FunctionDeclaration | ts.InterfaceDeclaration); + node as (ts.ClassDeclaration | ts.FunctionDeclaration | ts.InterfaceDeclaration); const name = classDeclaration.name; if (name) exportTable.add(name.text); } @@ -406,7 +415,9 @@ function createExportTableFor(sourceFile: ts.SourceFile): Set { const exportDeclaration = node as ts.ExportDeclaration; const {moduleSpecifier, exportClause} = exportDeclaration; if (!moduleSpecifier && exportClause && ts.isNamedExports(exportClause)) { - exportClause.elements.forEach(spec => { exportTable.add(spec.name.text); }); + exportClause.elements.forEach(spec => { + exportTable.add(spec.name.text); + }); } } }); diff --git a/packages/compiler-cli/src/transformers/node_emitter.ts b/packages/compiler-cli/src/transformers/node_emitter.ts index 9171982655..a557669d45 100644 --- a/packages/compiler-cli/src/transformers/node_emitter.ts +++ b/packages/compiler-cli/src/transformers/node_emitter.ts @@ -12,7 +12,9 @@ import * as ts from 'typescript'; import {error} from './util'; -export interface Node { sourceSpan: ParseSourceSpan|null; } +export interface Node { + sourceSpan: ParseSourceSpan|null; +} const METHOD_THIS_NAME = 'this'; const CATCH_ERROR_NAME = 'error'; @@ -110,15 +112,16 @@ export function updateSourceFile( // Validate that all the classes have been generated classNames.size == 0 || - error( - `${classNames.size == 1 ? 'Class' : 'Classes'} "${Array.from(classNames.keys()).join(', ')}" not generated`); + error(`${classNames.size == 1 ? 'Class' : 'Classes'} "${ + Array.from(classNames.keys()).join(', ')}" not generated`); // Add imports to the module required by the new methods const imports = converter.getImports(); if (imports && imports.length) { // Find where the new imports should go const index = firstAfter( - newStatements, statement => statement.kind === ts.SyntaxKind.ImportDeclaration || + newStatements, + statement => statement.kind === ts.SyntaxKind.ImportDeclaration || statement.kind === ts.SyntaxKind.ImportEqualsDeclaration); newStatements = [...newStatements.slice(0, index), ...imports, ...prefix, ...newStatements.slice(index)]; @@ -152,7 +155,9 @@ function firstAfter(a: T[], predicate: (value: T) => boolean) { // A recorded node is a subtype of the node that is marked as being recorded. This is used // to ensure that NodeEmitterVisitor.record has been called on all nodes returned by the // NodeEmitterVisitor -export type RecordedNode = (T & { __recorded: any;}) | null; +export type RecordedNode = (T&{ + __recorded: any; +})|null; function escapeLiteral(value: string): string { return value.replace(/(\"|\\)/g, '\\$1').replace(/(\n)|(\r)/g, function(v, n, r) { @@ -220,8 +225,9 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { .map( ([exportedFilePath, reexports]) => ts.createExportDeclaration( /* decorators */ undefined, - /* modifiers */ undefined, ts.createNamedExports(reexports.map( - ({name, as}) => ts.createExportSpecifier(name, as))), + /* modifiers */ undefined, + ts.createNamedExports( + reexports.map(({name, as}) => ts.createExportSpecifier(name, as))), /* moduleSpecifier */ createLiteral(exportedFilePath))); } @@ -231,13 +237,16 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { ([namespace, prefix]) => ts.createImportDeclaration( /* decorators */ undefined, /* modifiers */ undefined, - /* importClause */ ts.createImportClause( + /* importClause */ + ts.createImportClause( /* name */(undefined as any), ts.createNamespaceImport(ts.createIdentifier(prefix))), /* moduleSpecifier */ createLiteral(namespace))); } - getNodeMap() { return this._nodeMap; } + getNodeMap() { + return this._nodeMap; + } updateSourceMap(statements: ts.Statement[]) { let lastRangeStartNode: ts.Node|undefined = undefined; @@ -324,7 +333,7 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { reexports = []; this._reexports.set(moduleName, reexports); } - reexports.push({name: name !, as: stmt.name}); + reexports.push({name: name!, as: stmt.name}); return null; } } @@ -340,9 +349,10 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { const tsVarStmt = this.record(stmt, ts.createVariableStatement(/* modifiers */[], varDeclList)); const exportStmt = this.record( - stmt, ts.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, - ts.createNamedExports([ts.createExportSpecifier(stmt.name, stmt.name)]))); + stmt, + ts.createExportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, + ts.createNamedExports([ts.createExportSpecifier(stmt.name, stmt.name)]))); return [tsVarStmt, exportStmt]; } return this.record(stmt, ts.createVariableStatement(this.getModifiers(stmt), varDeclList)); @@ -350,14 +360,15 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { visitDeclareFunctionStmt(stmt: DeclareFunctionStmt) { return this.record( - stmt, ts.createFunctionDeclaration( - /* decorators */ undefined, this.getModifiers(stmt), - /* asteriskToken */ undefined, stmt.name, /* typeParameters */ undefined, - stmt.params.map( - p => ts.createParameter( - /* decorators */ undefined, /* modifiers */ undefined, - /* dotDotDotToken */ undefined, p.name)), - /* type */ undefined, this._visitStatements(stmt.statements))); + stmt, + ts.createFunctionDeclaration( + /* decorators */ undefined, this.getModifiers(stmt), + /* asteriskToken */ undefined, stmt.name, /* typeParameters */ undefined, + stmt.params.map( + p => ts.createParameter( + /* decorators */ undefined, /* modifiers */ undefined, + /* dotDotDotToken */ undefined, p.name)), + /* type */ undefined, this._visitStatements(stmt.statements))); } visitExpressionStmt(stmt: ExpressionStatement) { @@ -401,7 +412,8 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { (stmt.constructorMethod && [ts.createConstructor( /* decorators */ undefined, /* modifiers */ undefined, - /* parameters */ stmt.constructorMethod.params.map( + /* parameters */ + stmt.constructorMethod.params.map( p => ts.createParameter( /* decorators */ undefined, /* modifiers */ undefined, @@ -415,7 +427,7 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { method => ts.createMethod( /* decorators */ undefined, /* modifiers */ translateModifiers(method.modifiers), - /* astriskToken */ undefined, method.name !/* guarded by filter */, + /* astriskToken */ undefined, method.name!/* guarded by filter */, /* questionToken */ undefined, /* typeParameters */ undefined, method.params.map( p => ts.createParameter( @@ -423,13 +435,14 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { /* dotDotDotToken */ undefined, p.name)), /* type */ undefined, this._visitStatements(method.body))); return this.record( - stmt, ts.createClassDeclaration( - /* decorators */ undefined, modifiers, stmt.name, /* typeParameters*/ undefined, - stmt.parent && [ts.createHeritageClause( - ts.SyntaxKind.ExtendsKeyword, - [stmt.parent.visitExpression(this, null)])] || - [], - [...fields, ...getters, ...constructor, ...methods])); + stmt, + ts.createClassDeclaration( + /* decorators */ undefined, modifiers, stmt.name, /* typeParameters*/ undefined, + stmt.parent && + [ts.createHeritageClause( + ts.SyntaxKind.ExtendsKeyword, [stmt.parent.visitExpression(this, null)])] || + [], + [...fields, ...getters, ...constructor, ...methods])); } visitIfStmt(stmt: IfStmt) { @@ -443,19 +456,21 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { visitTryCatchStmt(stmt: TryCatchStmt): RecordedNode { return this.record( - stmt, ts.createTry( - this._visitStatements(stmt.bodyStmts), - ts.createCatchClause( - CATCH_ERROR_NAME, this._visitStatementsPrefix( - [ts.createVariableStatement( - /* modifiers */ undefined, - [ts.createVariableDeclaration( - CATCH_STACK_NAME, /* type */ undefined, - ts.createPropertyAccess( - ts.createIdentifier(CATCH_ERROR_NAME), - ts.createIdentifier(CATCH_STACK_NAME)))])], - stmt.catchStmts)), - /* finallyBlock */ undefined)); + stmt, + ts.createTry( + this._visitStatements(stmt.bodyStmts), + ts.createCatchClause( + CATCH_ERROR_NAME, + this._visitStatementsPrefix( + [ts.createVariableStatement( + /* modifiers */ undefined, + [ts.createVariableDeclaration( + CATCH_STACK_NAME, /* type */ undefined, + ts.createPropertyAccess( + ts.createIdentifier(CATCH_ERROR_NAME), + ts.createIdentifier(CATCH_STACK_NAME)))])], + stmt.catchStmts)), + /* finallyBlock */ undefined)); } visitThrowStmt(stmt: ThrowStmt) { @@ -481,7 +496,9 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { } // ExpressionVisitor - visitWrappedNodeExpr(expr: WrappedNodeExpr) { return this.record(expr, expr.node); } + visitWrappedNodeExpr(expr: WrappedNodeExpr) { + return this.record(expr, expr.node); + } visitTypeofExpr(expr: TypeofExpr) { const typeOf = ts.createTypeOf(expr.expr.visitExpression(this, null)); @@ -508,8 +525,9 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { visitWriteVarExpr(expr: WriteVarExpr): RecordedNode { return this.record( - expr, ts.createAssignment( - ts.createIdentifier(expr.name), expr.value.visitExpression(this, null))); + expr, + ts.createAssignment( + ts.createIdentifier(expr.name), expr.value.visitExpression(this, null))); } visitWriteKeyExpr(expr: WriteKeyExpr): RecordedNode { @@ -523,9 +541,10 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { visitWritePropExpr(expr: WritePropExpr): RecordedNode { return this.record( - expr, ts.createAssignment( - ts.createPropertyAccess(expr.receiver.visitExpression(this, null), expr.name), - expr.value.visitExpression(this, null))); + expr, + ts.createAssignment( + ts.createPropertyAccess(expr.receiver.visitExpression(this, null), expr.name), + expr.value.visitExpression(this, null))); } visitInvokeMethodExpr(expr: InvokeMethodExpr): RecordedNode { @@ -539,19 +558,23 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { visitInvokeFunctionExpr(expr: InvokeFunctionExpr): RecordedNode { return this.record( - expr, ts.createCall( - expr.fn.visitExpression(this, null), /* typeArguments */ undefined, - expr.args.map(arg => arg.visitExpression(this, null)))); + expr, + ts.createCall( + expr.fn.visitExpression(this, null), /* typeArguments */ undefined, + expr.args.map(arg => arg.visitExpression(this, null)))); } visitInstantiateExpr(expr: InstantiateExpr): RecordedNode { return this.record( - expr, ts.createNew( - expr.classExpr.visitExpression(this, null), /* typeArguments */ undefined, - expr.args.map(arg => arg.visitExpression(this, null)))); + expr, + ts.createNew( + expr.classExpr.visitExpression(this, null), /* typeArguments */ undefined, + expr.args.map(arg => arg.visitExpression(this, null)))); } - visitLiteralExpr(expr: LiteralExpr) { return this.record(expr, createLiteral(expr.value)); } + visitLiteralExpr(expr: LiteralExpr) { + return this.record(expr, createLiteral(expr.value)); + } visitLocalizedString(expr: LocalizedString, context: any) { throw new Error('localized strings are not supported in pre-ivy mode.'); @@ -567,13 +590,14 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { expr, ts.createParen(ts.createConditional( expr.condition.visitExpression(this, null), expr.trueCase.visitExpression(this, null), - expr.falseCase !.visitExpression(this, null)))); + expr.falseCase!.visitExpression(this, null)))); } visitNotExpr(expr: NotExpr): RecordedNode { return this.record( - expr, ts.createPrefix( - ts.SyntaxKind.ExclamationToken, expr.condition.visitExpression(this, null))); + expr, + ts.createPrefix( + ts.SyntaxKind.ExclamationToken, expr.condition.visitExpression(this, null))); } visitAssertNotNullExpr(expr: AssertNotNull): RecordedNode { @@ -586,15 +610,16 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { visitFunctionExpr(expr: FunctionExpr) { return this.record( - expr, ts.createFunctionExpression( - /* modifiers */ undefined, /* astriskToken */ undefined, - /* name */ expr.name || undefined, - /* typeParameters */ undefined, - expr.params.map( - p => ts.createParameter( - /* decorators */ undefined, /* modifiers */ undefined, - /* dotDotDotToken */ undefined, p.name)), - /* type */ undefined, this._visitStatements(expr.statements))); + expr, + ts.createFunctionExpression( + /* modifiers */ undefined, /* astriskToken */ undefined, + /* name */ expr.name || undefined, + /* typeParameters */ undefined, + expr.params.map( + p => ts.createParameter( + /* decorators */ undefined, /* modifiers */ undefined, + /* dotDotDotToken */ undefined, p.name)), + /* type */ undefined, this._visitStatements(expr.statements))); } visitBinaryOperatorExpr(expr: BinaryOperatorExpr): @@ -676,21 +701,23 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { visitLiteralMapExpr(expr: LiteralMapExpr): RecordedNode { return this.record( - expr, ts.createObjectLiteral(expr.entries.map( - entry => ts.createPropertyAssignment( - entry.quoted || !_VALID_IDENTIFIER_RE.test(entry.key) ? - ts.createLiteral(entry.key) : - entry.key, - entry.value.visitExpression(this, null))))); + expr, + ts.createObjectLiteral(expr.entries.map( + entry => ts.createPropertyAssignment( + entry.quoted || !_VALID_IDENTIFIER_RE.test(entry.key) ? + ts.createLiteral(entry.key) : + entry.key, + entry.value.visitExpression(this, null))))); } visitCommaExpr(expr: CommaExpr): RecordedNode { return this.record( - expr, expr.parts.map(e => e.visitExpression(this, null)) - .reduce( - (left, right) => - left ? ts.createBinary(left, ts.SyntaxKind.CommaToken, right) : right, - null)); + expr, + expr.parts.map(e => e.visitExpression(this, null)) + .reduce( + (left, right) => + left ? ts.createBinary(left, ts.SyntaxKind.CommaToken, right) : right, + null)); } private _visitStatements(statements: Statement[]): ts.Block { @@ -705,7 +732,7 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { private _visitIdentifier(value: ExternalReference): ts.Expression { // name can only be null during JIT which never executes this code. - const moduleName = value.moduleName, name = value.name !; + const moduleName = value.moduleName, name = value.name!; let prefixIdent: ts.Identifier|null = null; if (moduleName) { let prefix = this._importsWithPrefixes.get(moduleName); @@ -730,7 +757,7 @@ export class NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor { } -function getMethodName(methodRef: {name: string | null; builtin: BuiltinMethod | null}): string { +function getMethodName(methodRef: {name: string|null; builtin: BuiltinMethod | null}): string { if (methodRef.name) { return methodRef.name; } else { @@ -760,6 +787,6 @@ function modifierFromModifier(modifier: StmtModifier): ts.Modifier { return error(`unknown statement modifier`); } -function translateModifiers(modifiers: StmtModifier[] | null): ts.Modifier[]|undefined { - return modifiers == null ? undefined : modifiers !.map(modifierFromModifier); +function translateModifiers(modifiers: StmtModifier[]|null): ts.Modifier[]|undefined { + return modifiers == null ? undefined : modifiers!.map(modifierFromModifier); } diff --git a/packages/compiler-cli/src/transformers/program.ts b/packages/compiler-cli/src/transformers/program.ts index eb631c4c2d..89d483b6ff 100644 --- a/packages/compiler-cli/src/transformers/program.ts +++ b/packages/compiler-cli/src/transformers/program.ts @@ -7,26 +7,26 @@ * found in the LICENSE file at https://angular.io/license */ -import {AotCompiler, AotCompilerHost, AotCompilerOptions, EmitterVisitorContext, FormattedMessageChain, GeneratedFile, MessageBundle, NgAnalyzedFile, NgAnalyzedFileWithInjectables, NgAnalyzedModules, ParseSourceSpan, PartialModule, Position, Serializer, StaticSymbol, TypeScriptEmitter, Xliff, Xliff2, Xmb, core, createAotCompiler, getParseErrors, isFormattedError, isSyntaxError} from '@angular/compiler'; +import {AotCompiler, AotCompilerHost, AotCompilerOptions, core, createAotCompiler, EmitterVisitorContext, FormattedMessageChain, GeneratedFile, getParseErrors, isFormattedError, isSyntaxError, MessageBundle, NgAnalyzedFile, NgAnalyzedFileWithInjectables, NgAnalyzedModules, ParseSourceSpan, PartialModule, Position, Serializer, StaticSymbol, TypeScriptEmitter, Xliff, Xliff2, Xmb} from '@angular/compiler'; import * as fs from 'fs'; import * as path from 'path'; import * as ts from 'typescript'; -import {TypeCheckHost, translateDiagnostics} from '../diagnostics/translate_diagnostics'; -import {MetadataCollector, ModuleMetadata, createBundleIndexHost} from '../metadata'; +import {translateDiagnostics, TypeCheckHost} from '../diagnostics/translate_diagnostics'; +import {createBundleIndexHost, MetadataCollector, ModuleMetadata} from '../metadata'; import {NgtscProgram} from '../ngtsc/program'; import {verifySupportedTypeScriptVersion} from '../typescript_support'; import {CompilerHost, CompilerOptions, CustomTransformers, DEFAULT_ERROR_CODE, Diagnostic, DiagnosticMessageChain, EmitFlags, LazyRoute, LibrarySummary, Program, SOURCE, TsEmitArguments, TsEmitCallback, TsMergeEmitResultsCallback} from './api'; -import {CodeGenerator, TsCompilerAotCompilerTypeCheckHostAdapter, getOriginalReferences} from './compiler_host'; -import {InlineResourcesMetadataTransformer, getInlineResourcesTransformFactory} from './inline_resources'; -import {LowerMetadataTransform, getExpressionLoweringTransformFactory} from './lower_expressions'; +import {CodeGenerator, getOriginalReferences, TsCompilerAotCompilerTypeCheckHostAdapter} from './compiler_host'; +import {getInlineResourcesTransformFactory, InlineResourcesMetadataTransformer} from './inline_resources'; +import {getExpressionLoweringTransformFactory, LowerMetadataTransform} from './lower_expressions'; import {MetadataCache, MetadataTransformer} from './metadata_cache'; import {getAngularEmitterTransformFactory} from './node_emitter_transform'; import {PartialModuleMetadataTransformer} from './r3_metadata_transform'; -import {StripDecoratorsMetadataTransformer, getDecoratorStripTransformerFactory} from './r3_strip_decorators'; +import {getDecoratorStripTransformerFactory, StripDecoratorsMetadataTransformer} from './r3_strip_decorators'; import {getAngularClassTransformerFactory} from './r3_transform'; -import {DTS, GENERATED_FILES, StructureIsReused, TS, createMessageDiagnostic, isInRootDir, ngToTsDiagnostic, tsStructureIsReused, userError} from './util'; +import {createMessageDiagnostic, DTS, GENERATED_FILES, isInRootDir, ngToTsDiagnostic, StructureIsReused, TS, tsStructureIsReused, userError} from './util'; /** @@ -60,18 +60,23 @@ const emptyModules: NgAnalyzedModules = { files: [] }; -const defaultEmitCallback: TsEmitCallback = - ({program, targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, - customTransformers}) => - program.emit( - targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); +const defaultEmitCallback: TsEmitCallback = ({ + program, + targetSourceFile, + writeFile, + cancellationToken, + emitOnlyDtsFiles, + customTransformers +}) => + program.emit( + targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); class AngularCompilerProgram implements Program { private rootNames: string[]; private metadataCache: MetadataCache; // Metadata cache used exclusively for the flat module index // TODO(issue/24571): remove '!'. - private flatModuleMetadataCache !: MetadataCache; + private flatModuleMetadataCache!: MetadataCache; private loweringMetadataTransform: LowerMetadataTransform; private oldProgramLibrarySummaries: Map|undefined; private oldProgramEmittedGeneratedFiles: Map|undefined; @@ -84,18 +89,18 @@ class AngularCompilerProgram implements Program { // Lazily initialized fields // TODO(issue/24571): remove '!'. - private _compiler !: AotCompiler; + private _compiler!: AotCompiler; // TODO(issue/24571): remove '!'. - private _hostAdapter !: TsCompilerAotCompilerTypeCheckHostAdapter; + private _hostAdapter!: TsCompilerAotCompilerTypeCheckHostAdapter; // TODO(issue/24571): remove '!'. - private _tsProgram !: ts.Program; + private _tsProgram!: ts.Program; private _analyzedModules: NgAnalyzedModules|undefined; private _analyzedInjectables: NgAnalyzedFileWithInjectables[]|undefined; private _structuralDiagnostics: Diagnostic[]|undefined; private _programWithStubs: ts.Program|undefined; private _optionsDiagnostics: Diagnostic[] = []; // TODO(issue/24571): remove '!'. - private _reifiedDecorators !: Set; + private _reifiedDecorators!: Set; constructor( rootNames: ReadonlyArray, private options: CompilerOptions, @@ -124,7 +129,7 @@ class AngularCompilerProgram implements Program { code: DEFAULT_ERROR_CODE }))); } else { - this.rootNames.push(indexName !); + this.rootNames.push(indexName!); this.host = bundleHost; } } @@ -175,7 +180,9 @@ class AngularCompilerProgram implements Program { return result; } - getTsProgram(): ts.Program { return this.tsProgram; } + getTsProgram(): ts.Program { + return this.tsProgram; + } getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken) { return this.tsProgram.getOptionsDiagnostics(cancellationToken); @@ -256,17 +263,19 @@ class AngularCompilerProgram implements Program { return this._emitRender2(parameters); } - private _emitRender3( - { - emitFlags = EmitFlags.Default, cancellationToken, customTransformers, - emitCallback = defaultEmitCallback, mergeEmitResultsCallback = mergeEmitResults, - }: { - emitFlags?: EmitFlags, - cancellationToken?: ts.CancellationToken, - customTransformers?: CustomTransformers, - emitCallback?: TsEmitCallback, - mergeEmitResultsCallback?: TsMergeEmitResultsCallback, - } = {}): ts.EmitResult { + private _emitRender3({ + emitFlags = EmitFlags.Default, + cancellationToken, + customTransformers, + emitCallback = defaultEmitCallback, + mergeEmitResultsCallback = mergeEmitResults, + }: { + emitFlags?: EmitFlags, + cancellationToken?: ts.CancellationToken, + customTransformers?: CustomTransformers, + emitCallback?: TsEmitCallback, + mergeEmitResultsCallback?: TsMergeEmitResultsCallback, + } = {}): ts.EmitResult { const emitStart = Date.now(); if ((emitFlags & (EmitFlags.JS | EmitFlags.DTS | EmitFlags.Metadata | EmitFlags.Codegen)) === 0) { @@ -276,7 +285,7 @@ class AngularCompilerProgram implements Program { // analyzedModules and analyzedInjectables are created together. If one exists, so does the // other. const modules = - this.compiler.emitAllPartialModules(this.analyzedModules, this._analyzedInjectables !); + this.compiler.emitAllPartialModules(this.analyzedModules, this._analyzedInjectables!); const writeTsFile: ts.WriteFileCallback = (outFileName, outData, writeByteOrderMark, onError?, sourceFiles?) => { @@ -306,7 +315,8 @@ class AngularCompilerProgram implements Program { program: this.tsProgram, host: this.host, options: this.options, - writeFile: writeTsFile, emitOnlyDtsFiles, + writeFile: writeTsFile, + emitOnlyDtsFiles, customTransformers: tsCustomTransformers }); } finally { @@ -319,17 +329,19 @@ class AngularCompilerProgram implements Program { } } - private _emitRender2( - { - emitFlags = EmitFlags.Default, cancellationToken, customTransformers, - emitCallback = defaultEmitCallback, mergeEmitResultsCallback = mergeEmitResults, - }: { - emitFlags?: EmitFlags, - cancellationToken?: ts.CancellationToken, - customTransformers?: CustomTransformers, - emitCallback?: TsEmitCallback, - mergeEmitResultsCallback?: TsMergeEmitResultsCallback, - } = {}): ts.EmitResult { + private _emitRender2({ + emitFlags = EmitFlags.Default, + cancellationToken, + customTransformers, + emitCallback = defaultEmitCallback, + mergeEmitResultsCallback = mergeEmitResults, + }: { + emitFlags?: EmitFlags, + cancellationToken?: ts.CancellationToken, + customTransformers?: CustomTransformers, + emitCallback?: TsEmitCallback, + mergeEmitResultsCallback?: TsMergeEmitResultsCallback, + } = {}): ts.EmitResult { const emitStart = Date.now(); if (emitFlags & EmitFlags.I18nBundle) { const locale = this.options.i18nOutLocale || null; @@ -413,7 +425,8 @@ class AngularCompilerProgram implements Program { program: this.tsProgram, host: this.host, options: this.options, - writeFile: writeTsFile, emitOnlyDtsFiles, + writeFile: writeTsFile, + emitOnlyDtsFiles, customTransformers: tsCustomTransformers, targetSourceFile: this.tsProgram.getSourceFile(fileName), }))); @@ -423,7 +436,8 @@ class AngularCompilerProgram implements Program { program: this.tsProgram, host: this.host, options: this.options, - writeFile: writeTsFile, emitOnlyDtsFiles, + writeFile: writeTsFile, + emitOnlyDtsFiles, customTransformers: tsCustomTransformers }); emittedUserTsCount = this.tsProgram.getSourceFiles().length - genTsFiles.length; @@ -466,7 +480,7 @@ class AngularCompilerProgram implements Program { if (emitFlags & EmitFlags.Codegen) { genJsonFiles.forEach(gf => { const outFileName = srcToOutPath(gf.genFileUrl); - this.writeFile(outFileName, gf.source !, false, undefined, gf); + this.writeFile(outFileName, gf.source!, false, undefined, gf); }); } let metadataJsonCount = 0; @@ -501,21 +515,21 @@ class AngularCompilerProgram implements Program { if (!this._compiler) { this._createCompiler(); } - return this._compiler !; + return this._compiler!; } private get hostAdapter(): TsCompilerAotCompilerTypeCheckHostAdapter { if (!this._hostAdapter) { this._createCompiler(); } - return this._hostAdapter !; + return this._hostAdapter!; } private get analyzedModules(): NgAnalyzedModules { if (!this._analyzedModules) { this.initSync(); } - return this._analyzedModules !; + return this._analyzedModules!; } private get structuralDiagnostics(): ReadonlyArray { @@ -531,7 +545,7 @@ class AngularCompilerProgram implements Program { if (!this._tsProgram) { this.initSync(); } - return this._tsProgram !; + return this._tsProgram!; } private get reifiedDecorators(): Set { @@ -617,7 +631,7 @@ class AngularCompilerProgram implements Program { private _createCompiler() { const codegen: CodeGenerator = { generateFile: (genFileName, baseFileName) => - this._compiler.emitBasicStub(genFileName, baseFileName), + this._compiler.emitBasicStub(genFileName, baseFileName), findGeneratedFileNames: (fileName) => this._compiler.findGeneratedFileNames(fileName), }; @@ -646,7 +660,7 @@ class AngularCompilerProgram implements Program { const codegen: CodeGenerator = { generateFile: (genFileName, baseFileName) => - this.compiler.emitBasicStub(genFileName, baseFileName), + this.compiler.emitBasicStub(genFileName, baseFileName), findGeneratedFileNames: (fileName) => this.compiler.findGeneratedFileNames(fileName), }; @@ -692,7 +706,7 @@ class AngularCompilerProgram implements Program { if (generate) { // Note: ! is ok as hostAdapter.shouldGenerateFile will always return a baseFileName // for .ngfactory.ts files. - const genFile = this.compiler.emitTypeCheckStub(sf.fileName, baseFileName !); + const genFile = this.compiler.emitTypeCheckStub(sf.fileName, baseFileName!); if (genFile) { this.hostAdapter.updateGeneratedFile(genFile); } @@ -782,11 +796,12 @@ class AngularCompilerProgram implements Program { private getSourceFilesForEmit(): ts.SourceFile[]|undefined { // TODO(tbosch): if one of the files contains a `const enum` // always emit all files -> return undefined! - let sourceFilesToEmit = this.tsProgram.getSourceFiles().filter( - sf => { return !sf.isDeclarationFile && !GENERATED_FILES.test(sf.fileName); }); + let sourceFilesToEmit = this.tsProgram.getSourceFiles().filter(sf => { + return !sf.isDeclarationFile && !GENERATED_FILES.test(sf.fileName); + }); if (this.oldProgramEmittedSourceFiles) { sourceFilesToEmit = sourceFilesToEmit.filter(sf => { - const oldFile = this.oldProgramEmittedSourceFiles !.get(sf.fileName); + const oldFile = this.oldProgramEmittedSourceFiles!.get(sf.fileName); return sf !== oldFile; }); } @@ -849,7 +864,8 @@ class AngularCompilerProgram implements Program { export function createProgram({rootNames, options, host, oldProgram}: { rootNames: ReadonlyArray, options: CompilerOptions, - host: CompilerHost, oldProgram?: Program + host: CompilerHost, + oldProgram?: Program }): Program { if (options.enableIvy !== false) { return new NgtscProgram(rootNames, options, host, oldProgram as NgtscProgram | undefined); @@ -887,7 +903,9 @@ function getAotCompilerOptions(options: CompilerOptions): AotCompilerOptions { return { locale: options.i18nInLocale, i18nFormat: options.i18nInFormat || options.i18nOutFormat, - i18nUseExternalIds: options.i18nUseExternalIds, translations, missingTranslation, + i18nUseExternalIds: options.i18nUseExternalIds, + translations, + missingTranslation, enableSummariesForJit: options.enableSummariesForJit, preserveWhitespaces: options.preserveWhitespaces, fullTemplateTypeCheck: options.fullTemplateTypeCheck, @@ -931,8 +949,8 @@ function normalizeSeparators(path: string): string { * POSIX normalized paths for output paths. */ export function createSrcToOutPathMapper( - outDir: string | undefined, sampleSrcFileName: string | undefined, - sampleOutFileName: string | undefined, host: { + outDir: string|undefined, sampleSrcFileName: string|undefined, + sampleOutFileName: string|undefined, host: { dirname: typeof path.dirname, resolve: typeof path.resolve, relative: typeof path.relative @@ -971,14 +989,14 @@ export function createSrcToOutPathMapper( } export function i18nExtract( - formatName: string | null, outFile: string | null, host: ts.CompilerHost, - options: CompilerOptions, bundle: MessageBundle): string[] { + formatName: string|null, outFile: string|null, host: ts.CompilerHost, options: CompilerOptions, + bundle: MessageBundle): string[] { formatName = formatName || 'xlf'; // Checks the format and returns the extension const ext = i18nGetExtension(formatName); const content = i18nSerialize(bundle, formatName, options); const dstFile = outFile || `messages.${ext}`; - const dstPath = path.resolve(options.outDir || options.basePath !, dstFile); + const dstPath = path.resolve(options.outDir || options.basePath!, dstFile); host.writeFile(dstPath, content, false, undefined, []); return [dstPath]; } @@ -1045,7 +1063,7 @@ function mergeEmitResults(emitResults: ts.EmitResult[]): ts.EmitResult { function diagnosticSourceOfSpan(span: ParseSourceSpan): ts.SourceFile { // For diagnostics, TypeScript only uses the fileName and text properties. // The redundant '()' are here is to avoid having clang-format breaking the line incorrectly. - return ({ fileName: span.start.file.url, text: span.start.file.content } as any); + return ({fileName: span.start.file.url, text: span.start.file.content} as any); } function diagnosticSourceOfFileName(fileName: string, program: ts.Program): ts.SourceFile { @@ -1055,7 +1073,7 @@ function diagnosticSourceOfFileName(fileName: string, program: ts.Program): ts.S // If we are reporting diagnostics for a source file that is not in the project then we need // to fake a source file so the diagnostic formatting routines can emit the file name. // The redundant '()' are here is to avoid having clang-format breaking the line incorrectly. - return ({ fileName, text: '' } as any); + return ({fileName, text: ''} as any); } diff --git a/packages/compiler-cli/src/transformers/r3_metadata_transform.ts b/packages/compiler-cli/src/transformers/r3_metadata_transform.ts index ace19fea11..d0aefbf553 100644 --- a/packages/compiler-cli/src/transformers/r3_metadata_transform.ts +++ b/packages/compiler-cli/src/transformers/r3_metadata_transform.ts @@ -9,7 +9,7 @@ import {ClassStmt, PartialModule, Statement, StmtModifier} from '@angular/compiler'; import * as ts from 'typescript'; -import {MetadataCollector, MetadataValue, ModuleMetadata, isClassMetadata} from '../metadata/index'; +import {isClassMetadata, MetadataCollector, MetadataValue, ModuleMetadata} from '../metadata/index'; import {MetadataTransformer, ValueTransform} from './metadata_cache'; diff --git a/packages/compiler-cli/src/transformers/r3_strip_decorators.ts b/packages/compiler-cli/src/transformers/r3_strip_decorators.ts index c5feabee50..1d2bba7cdb 100644 --- a/packages/compiler-cli/src/transformers/r3_strip_decorators.ts +++ b/packages/compiler-cli/src/transformers/r3_strip_decorators.ts @@ -9,7 +9,7 @@ import {StaticReflector, StaticSymbol} from '@angular/compiler'; import * as ts from 'typescript'; -import {MetadataValue, isClassMetadata, isMetadataImportedSymbolReferenceExpression, isMetadataSymbolicCallExpression} from '../metadata'; +import {isClassMetadata, isMetadataImportedSymbolReferenceExpression, isMetadataSymbolicCallExpression, MetadataValue} from '../metadata'; import {MetadataTransformer, ValueTransform} from './metadata_cache'; @@ -39,8 +39,14 @@ export function getDecoratorStripTransformerFactory( }); if (decorators.length !== node.decorators.length) { return ts.updateClassDeclaration( - node, decorators, node.modifiers, node.name, node.typeParameters, - node.heritageClauses || [], node.members, ); + node, + decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses || [], + node.members, + ); } return node; }; @@ -130,7 +136,7 @@ function resolveToStaticSymbol( if (!ts.isImportSpecifier(decl)) { return null; } - const moduleSpecifier = decl.parent !.parent !.parent !.moduleSpecifier; + const moduleSpecifier = decl.parent!.parent!.parent!.moduleSpecifier; if (!ts.isStringLiteral(moduleSpecifier)) { return null; } diff --git a/packages/compiler-cli/src/transformers/util.ts b/packages/compiler-cli/src/transformers/util.ts index 8d35326e27..9df0d76365 100644 --- a/packages/compiler-cli/src/transformers/util.ts +++ b/packages/compiler-cli/src/transformers/util.ts @@ -16,7 +16,11 @@ export const GENERATED_FILES = /(.*?)\.(ngfactory|shim\.ngstyle|ngstyle|ngsummar export const DTS = /\.d\.ts$/; export const TS = /^(?!.*\.d\.ts$).*\.ts$/; -export const enum StructureIsReused {Not = 0, SafeModules = 1, Completely = 2} +export const enum StructureIsReused { + Not = 0, + SafeModules = 1, + Completely = 2 +} // Note: This is an internal property in TypeScript. Use it only for assertions and tests. export function tsStructureIsReused(program: ts.Program): StructureIsReused { @@ -36,7 +40,8 @@ export function createMessageDiagnostic(messageText: string): ts.Diagnostic&Diag file: undefined, start: undefined, length: undefined, - category: ts.DiagnosticCategory.Message, messageText, + category: ts.DiagnosticCategory.Message, + messageText, code: DEFAULT_ERROR_CODE, source: SOURCE, }; @@ -76,7 +81,7 @@ export function ngToTsDiagnostic(ng: Diagnostic): ts.Diagnostic { // Note: We can't use a real ts.SourceFile, // but we can at least mirror the properties `fileName` and `text`, which // are mostly used for error reporting. - file = { fileName: ng.span.start.file.url, text: ng.span.start.file.content } as ts.SourceFile; + file = {fileName: ng.span.start.file.url, text: ng.span.start.file.content} as ts.SourceFile; start = ng.span.start.offset; length = ng.span.end.offset - start; } @@ -84,6 +89,8 @@ export function ngToTsDiagnostic(ng: Diagnostic): ts.Diagnostic { file, messageText: ng.messageText, category: ng.category, - code: ng.code, start, length, + code: ng.code, + start, + length, }; } diff --git a/packages/compiler-cli/src/typescript_support.ts b/packages/compiler-cli/src/typescript_support.ts index 3a3e3e6476..98945def78 100644 --- a/packages/compiler-cli/src/typescript_support.ts +++ b/packages/compiler-cli/src/typescript_support.ts @@ -49,8 +49,8 @@ export function restoreTypeScriptVersionForTesting(): void { */ export function checkVersion(version: string, minVersion: string, maxVersion: string) { if ((compareVersions(version, minVersion) < 0 || compareVersions(version, maxVersion) >= 0)) { - throw new Error( - `The Angular Compiler requires TypeScript >=${minVersion} and <${maxVersion} but ${version} was found instead.`); + throw new Error(`The Angular Compiler requires TypeScript >=${minVersion} and <${ + maxVersion} but ${version} was found instead.`); } } diff --git a/packages/compiler-cli/test/compliance/mock_compile.ts b/packages/compiler-cli/test/compliance/mock_compile.ts index e0c905ded7..bae4cc8632 100644 --- a/packages/compiler-cli/test/compliance/mock_compile.ts +++ b/packages/compiler-cli/test/compliance/mock_compile.ts @@ -7,8 +7,9 @@ */ import {AotCompilerOptions} from '@angular/compiler'; import {escapeRegExp} from '@angular/compiler/src/util'; -import {MockCompilerHost, MockData, MockDirectory, arrayToMockDir, toMockFileArray} from '@angular/compiler/test/aot/test_util'; +import {arrayToMockDir, MockCompilerHost, MockData, MockDirectory, toMockFileArray} from '@angular/compiler/test/aot/test_util'; import * as ts from 'typescript'; + import {NodeJSFileSystem, setFileSystem} from '../../src/ngtsc/file_system'; import {NgtscProgram} from '../../src/ngtsc/program'; @@ -22,10 +23,11 @@ const NUMBER = /\d+/; const ELLIPSIS = '…'; const TOKEN = new RegExp( - `\\s*((${IDENTIFIER.source})|(${BACKTICK_STRING.source})|(${OPERATOR.source})|(${STRING.source})|${NUMBER.source}|${ELLIPSIS})\\s*`, + `\\s*((${IDENTIFIER.source})|(${BACKTICK_STRING.source})|(${OPERATOR.source})|(${ + STRING.source})|${NUMBER.source}|${ELLIPSIS})\\s*`, 'y'); -type Piece = string | RegExp; +type Piece = string|RegExp; const SKIP = /(?:.|\n|\r)*/; @@ -116,15 +118,16 @@ export function expectEmit( const context = fullContext.length > contextLength ? `...${fullContext.substr(-contextLength)}` : fullContext; - fail( - `${description}: Failed to find "${expectedPiece}" after "${context}" in:\n'${source.substr(0,last)}[<---HERE expected "${expectedPiece}"]${source.substr(last)}'`); + fail(`${description}: Failed to find "${expectedPiece}" after "${context}" in:\n'${ + source.substr(0, last)}[<---HERE expected "${expectedPiece}"]${source.substr(last)}'`); return; } else { last = (m.index || 0) + m[0].length; } } fail( - `Test helper failure: Expected expression failed but the reporting logic could not find where it failed in: ${source}`); + `Test helper failure: Expected expression failed but the reporting logic could not find where it failed in: ${ + source}`); } else { if (assertIdentifiers) { // It might be possible to add the constraints in the original regexp (see `buildMatcher`) @@ -141,8 +144,8 @@ export function expectEmit( const name = matches[groups.get(id) as number]; const regexp = assertIdentifiers[id]; if (!regexp.test(name)) { - throw Error( - `${description}: The matching identifier "${id}" is "${name}" which doesn't match ${regexp}`); + throw Error(`${description}: The matching identifier "${id}" is "${ + name}" which doesn't match ${regexp}`); } } } @@ -160,7 +163,7 @@ const MATCHING_IDENT = /^\$.*\$$/; * - the `regexp` to be used to match the generated code, * - the `groups` which maps `$...$` identifier to their position in the regexp matches. */ -function buildMatcher(pieces: (string | RegExp)[]): {regexp: RegExp, groups: Map} { +function buildMatcher(pieces: (string|RegExp)[]): {regexp: RegExp, groups: Map} { const results: string[] = []; let first = true; let group = 0; @@ -196,7 +199,9 @@ function buildMatcher(pieces: (string | RegExp)[]): {regexp: RegExp, groups: Map export function compile( data: MockDirectory, angularFiles: MockData, options: AotCompilerOptions = {}, - errorCollector: (error: any, fileName?: string) => void = error => { throw error;}): { + errorCollector: (error: any, fileName?: string) => void = error => { + throw error; + }): { source: string, } { setFileSystem(new NodeJSFileSystem()); @@ -211,7 +216,8 @@ export function compile( target: ts.ScriptTarget.ES2015, module: ts.ModuleKind.ES2015, moduleResolution: ts.ModuleResolutionKind.NodeJs, - enableI18nLegacyMessageIdFormat: false, ...options, + enableI18nLegacyMessageIdFormat: false, + ...options, }, mockCompilerHost); program.emit(); diff --git a/packages/compiler-cli/test/compliance/mock_compiler_spec.ts b/packages/compiler-cli/test/compliance/mock_compiler_spec.ts index a1422aa4cc..fe6166022c 100644 --- a/packages/compiler-cli/test/compliance/mock_compiler_spec.ts +++ b/packages/compiler-cli/test/compliance/mock_compiler_spec.ts @@ -100,14 +100,14 @@ describe('mock_compiler', () => { it('should be able to properly handle string literals with escaped quote', () => { const files = { app: { - 'test.ts': String.raw `const identifier = "\"quoted\"";`, + 'test.ts': String.raw`const identifier = "\"quoted\"";`, } }; const result = compile(files, angularFiles); expect(() => { - expectEmit(result.source, String.raw `const $a$ = "\"quoted\"";`, 'Output does not match.'); + expectEmit(result.source, String.raw`const $a$ = "\"quoted\"";`, 'Output does not match.'); }).not.toThrow(); }); }); diff --git a/packages/compiler-cli/test/compliance/r3_compiler_compliance_spec.ts b/packages/compiler-cli/test/compliance/r3_compiler_compliance_spec.ts index 1df894c1c0..00f1155b58 100644 --- a/packages/compiler-cli/test/compliance/r3_compiler_compliance_spec.ts +++ b/packages/compiler-cli/test/compliance/r3_compiler_compliance_spec.ts @@ -16,7 +16,6 @@ import {compile, expectEmit} from './mock_compile'; * test in compiler_canonical_spec.ts should have a corresponding test here. */ describe('compiler compliance', () => { - const angularFiles = setup({ compileAngular: false, compileAnimations: false, @@ -49,7 +48,8 @@ describe('compiler compliance', () => { // The template should look like this (where IDENT is a wild card for an identifier): const template = ` … - consts: [["title", "Hello", ${AttributeMarker.Classes}, "my-app"], ["cx", "20", "cy", "30", "r", "50"]], + consts: [["title", "Hello", ${ + AttributeMarker.Classes}, "my-app"], ["cx", "20", "cy", "30", "r", "50"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div", 0); @@ -536,7 +536,6 @@ describe('compiler compliance', () => { const result = compile(files, angularFiles); expectEmit(result.source, template, 'Incorrect template'); }); - }); describe('components & directives', () => { @@ -867,7 +866,6 @@ describe('compiler compliance', () => { }); describe('value composition', () => { - it('should support array literals', () => { const files = { app: { @@ -1143,7 +1141,6 @@ describe('compiler compliance', () => { }); describe('content projection', () => { - it('should support content projection in root template', () => { const files = { app: { @@ -1319,7 +1316,8 @@ describe('compiler compliance', () => { } const $_c4$ = [[["span", "title", "tofirst"]], "*"]; … - consts: [["id", "second", ${AttributeMarker.Template}, "ngIf"], ["id", "third", ${AttributeMarker.Template}, "ngIf"], ["id", "second"], ["id", "third"]], + consts: [["id", "second", ${AttributeMarker.Template}, "ngIf"], ["id", "third", ${ + AttributeMarker.Template}, "ngIf"], ["id", "second"], ["id", "third"]], template: function Cmp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵprojectionDef($_c4$); @@ -1534,7 +1532,8 @@ describe('compiler compliance', () => { decls: 1, vars: 1, consts: [ - ["ngProjectAs", ".someclass", ${AttributeMarker.ProjectAs}, ["", 8, "someclass"], ${AttributeMarker.Template}, "ngIf"], + ["ngProjectAs", ".someclass", ${AttributeMarker.ProjectAs}, ["", 8, "someclass"], ${ + AttributeMarker.Template}, "ngIf"], ["ngProjectAs", ".someclass", ${AttributeMarker.ProjectAs}, ["", 8, "someclass"]] ], template: function MyApp_Template(rf, ctx) { @@ -1552,7 +1551,6 @@ describe('compiler compliance', () => { const result = compile(files, angularFiles); expectEmit(result.source, SimpleComponentDefinition, 'Incorrect MyApp definition'); }); - }); describe('queries', () => { @@ -2044,9 +2042,7 @@ describe('compiler compliance', () => { }); describe('pipes', () => { - it('should render pipes', () => { - const files = { app: { 'spec.ts': ` @@ -2217,7 +2213,6 @@ describe('compiler compliance', () => { it('should generate the proper instruction when injecting ChangeDetectorRef into a pipe', () => { - const files = { app: { 'spec.ts': ` @@ -2282,7 +2277,6 @@ describe('compiler compliance', () => { expectEmit(source, MyOtherPipeDefinition, 'Invalid alternate pipe definition'); expectEmit(source, MyOtherPipeFactory, 'Invalid alternate pipe factory function'); }); - }); it('local reference', () => { @@ -2477,7 +2471,8 @@ describe('compiler compliance', () => { } // ... - consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], ["foo", ""], [${AttributeMarker.Template}, "ngIf"]], + consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], ["foo", ""], [${ + AttributeMarker.Template}, "ngIf"]], template:function MyComponent_Template(rf, ctx){ if (rf & 1) { $i0$.ɵɵtemplate(0, MyComponent_div_0_Template, 4, 1, "div", 0); @@ -3280,7 +3275,6 @@ describe('compiler compliance', () => { const result = compile(files, angularFiles); expectEmit(result.source, MyAppDeclaration, 'Invalid component definition'); }); - }); describe('inherited base classes', () => { @@ -3849,7 +3843,7 @@ describe('compiler compliance', () => { } }; const result = compile(files, angularFiles); - expect(result.source.match(/ɵdir/g) !.length).toBe(1); + expect(result.source.match(/ɵdir/g)!.length).toBe(1); }); }); }); diff --git a/packages/compiler-cli/test/compliance/r3_view_compiler_binding_spec.ts b/packages/compiler-cli/test/compliance/r3_view_compiler_binding_spec.ts index 98cdd94271..1a962dc5ee 100644 --- a/packages/compiler-cli/test/compliance/r3_view_compiler_binding_spec.ts +++ b/packages/compiler-cli/test/compliance/r3_view_compiler_binding_spec.ts @@ -405,7 +405,6 @@ describe('compiler compliance: bindings', () => { expectEmit(result.source, template, 'Incorrect template'); }); - }); describe('attribute bindings', () => { @@ -640,13 +639,13 @@ describe('compiler compliance: bindings', () => { }; const template = ` - consts: [["target", "_blank", "aria-label", "link", ${AttributeMarker.Bindings}, "title", "id", "customEvent"]], + consts: [["target", "_blank", "aria-label", "link", ${ + AttributeMarker.Bindings}, "title", "id", "customEvent"]], … `; const result = compile(files, angularFiles); expectEmit(result.source, template, 'Incorrect attribute array'); }); - }); describe('host bindings', () => { @@ -850,12 +849,15 @@ describe('compiler compliance: bindings', () => { HostAttributeComp.ɵcmp = $r3$.ɵɵdefineComponent({ type: HostAttributeComp, selectors: [["my-host-attribute-component"]], - hostAttrs: ["title", "hello there from component", ${AttributeMarker.Styles}, "opacity", "1"], + hostAttrs: ["title", "hello there from component", ${ + AttributeMarker.Styles}, "opacity", "1"], … HostAttributeDir.ɵdir = $r3$.ɵɵdefineDirective({ type: HostAttributeDir, selectors: [["", "hostAttributeDir", ""]], - hostAttrs: ["title", "hello there from directive", ${AttributeMarker.Classes}, "one", "two", ${AttributeMarker.Styles}, "width", "200px", "height", "500px"], + hostAttrs: ["title", "hello there from directive", ${ + AttributeMarker.Classes}, "one", "two", ${ + AttributeMarker.Styles}, "width", "200px", "height", "500px"], hostVars: 4, hostBindings: function HostAttributeDir_HostBindings(rf, ctx) { … @@ -1216,7 +1218,6 @@ describe('compiler compliance: bindings', () => { `; expectEmit(result.source, template, 'Incorrect template'); }); - }); describe('non bindable behavior', () => { @@ -1420,7 +1421,5 @@ describe('compiler compliance: bindings', () => { const result = compile(files, angularFiles); expectEmit(result.source, template, 'Incorrect handling of elements with no children'); }); - }); - }); diff --git a/packages/compiler-cli/test/compliance/r3_view_compiler_di_spec.ts b/packages/compiler-cli/test/compliance/r3_view_compiler_di_spec.ts index 935d4e447a..91f70e9d03 100644 --- a/packages/compiler-cli/test/compliance/r3_view_compiler_di_spec.ts +++ b/packages/compiler-cli/test/compliance/r3_view_compiler_di_spec.ts @@ -386,8 +386,7 @@ describe('compiler compliance: dependency injection', () => { expectEmit(source, MyPipeDefs, 'Invalid pipe factory function'); expectEmit(source, MyOtherPipeDefs, 'Invalid pipe factory function'); - expect(source.match(/MyPipe\.ɵfac =/g) !.length).toBe(1); - expect(source.match(/MyOtherPipe\.ɵfac =/g) !.length).toBe(1); + expect(source.match(/MyPipe\.ɵfac =/g)!.length).toBe(1); + expect(source.match(/MyOtherPipe\.ɵfac =/g)!.length).toBe(1); }); - }); diff --git a/packages/compiler-cli/test/compliance/r3_view_compiler_directives_spec.ts b/packages/compiler-cli/test/compliance/r3_view_compiler_directives_spec.ts index 918ef6701e..b71ff345c9 100644 --- a/packages/compiler-cli/test/compliance/r3_view_compiler_directives_spec.ts +++ b/packages/compiler-cli/test/compliance/r3_view_compiler_directives_spec.ts @@ -10,7 +10,6 @@ import {setup} from '@angular/compiler/test/aot/test_util'; import {compile, expectEmit} from './mock_compile'; describe('compiler compliance: directives', () => { - const angularFiles = setup({ compileAngular: false, compileAnimations: false, @@ -18,7 +17,6 @@ describe('compiler compliance: directives', () => { }); describe('matching', () => { - it('should not match directives on i18n attribute', () => { const files = { app: { @@ -114,7 +112,6 @@ describe('compiler compliance: directives', () => { }); it('should match directives on element bindings', () => { - const files = { app: { 'spec.ts': ` @@ -273,7 +270,6 @@ describe('compiler compliance: directives', () => { }); it('should match directives on ng-template bindings', () => { - const files = { app: { 'spec.ts': ` @@ -321,7 +317,6 @@ describe('compiler compliance: directives', () => { }); it('should match structural directives', () => { - const files = { app: { 'spec.ts': ` @@ -362,11 +357,9 @@ describe('compiler compliance: directives', () => { const source = result.source; expectEmit(source, MyComponentDefinition, 'Incorrect ChildComponent.ɵcmp'); - }); it('should match directives on element outputs', () => { - const files = { app: { 'spec.ts': ` @@ -413,6 +406,5 @@ describe('compiler compliance: directives', () => { expectEmit(source, MyComponentDefinition, 'Incorrect ChildComponent.ɵcmp'); }); - }); }); diff --git a/packages/compiler-cli/test/compliance/r3_view_compiler_i18n_spec.ts b/packages/compiler-cli/test/compliance/r3_view_compiler_i18n_spec.ts index 935859f2df..eee7e684ed 100644 --- a/packages/compiler-cli/test/compliance/r3_view_compiler_i18n_spec.ts +++ b/packages/compiler-cli/test/compliance/r3_view_compiler_i18n_spec.ts @@ -58,7 +58,9 @@ const verifyTranslationIds = }); const regexp = /const\s*MSG_EXTERNAL_(.+?)\s*=\s*goog\.getMsg/g; const ids = extract(output, regexp, v => v[1]); - ids.forEach(id => { generatedIds.add(id.split('$$')[0]); }); + ids.forEach(id => { + generatedIds.add(id.split('$$')[0]); + }); const delta = diff(extractedIds, generatedIds); if (delta.size) { // check if we have ids in exception list @@ -179,7 +181,6 @@ const verify = (input: string, output: string, extra: any = {}): void => { }; describe('i18n support in the template compiler', () => { - describe('element attributes', () => { it('should add the meaning and description as JsDoc comments and metadata blocks', () => { const input = ` @@ -193,7 +194,7 @@ describe('i18n support in the template compiler', () => {
Content H
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { /** @@ -269,8 +270,8 @@ describe('i18n support in the template compiler', () => { if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { /** * @desc [BACKUP_$` + - String.raw `{MESSAGE}_ID:idH]` + - '`' + String.raw `desc + String.raw`{MESSAGE}_ID:idH]` + + '`' + String.raw`desc */ const $MSG_EXTERNAL_idG$$APP_SPEC_TS_24$ = goog.getMsg("Title G"); $I18N_23$ = $MSG_EXTERNAL_idG$$APP_SPEC_TS_24$; @@ -338,7 +339,7 @@ describe('i18n support in the template compiler', () => { // TODO (FW-1942): update the code to avoid adding `title` attribute in plain form // into the `consts` array on Component def. - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_6616505470450179563$$APP_SPEC_TS_1$ = goog.getMsg("Hello"); @@ -368,7 +369,7 @@ describe('i18n support in the template compiler', () => { // TODO (FW-1942): update the code to avoid adding `title` attribute in plain form // into the `consts` array on Component def. - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_6616505470450179563$$APP_SPEC_TS_1$ = goog.getMsg("Hello"); @@ -409,7 +410,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_3771704108176831903$$APP_SPEC_TS_1$ = goog.getMsg("Hello {$interpolation}", { @@ -419,7 +420,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \`Hello $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c2$ = ["title", $I18N_0$]; … @@ -444,7 +445,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_3771704108176831903$$APP_SPEC_TS__1$ = goog.getMsg("Hello {$interpolation}", { @@ -454,7 +455,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \`Hello $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c2$ = ["title", $I18N_0$]; … @@ -531,7 +532,7 @@ describe('i18n support in the template compiler', () => {
`; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { /** @@ -572,7 +573,7 @@ describe('i18n support in the template compiler', () => { > `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_5526535577705876535$$APP_SPEC_TS_1$ = goog.getMsg("static text"); @@ -594,7 +595,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_2$ = $localize \`:m|d:intro $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } var $I18N_3$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { @@ -609,7 +610,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_3$ = $localize \`:m1|d1:$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c1$ = [ "aria-roledescription", $I18N_1$, @@ -629,9 +630,9 @@ describe('i18n support in the template compiler', () => { } else { $I18N_6$ = $localize \`:m2|d2:$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: and $` + - String.raw `{"\uFFFD1\uFFFD"}:INTERPOLATION_1: and again $` + - String.raw `{"\uFFFD2\uFFFD"}:INTERPOLATION_2:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: and $` + + String.raw`{"\uFFFD1\uFFFD"}:INTERPOLATION_1: and again $` + + String.raw`{"\uFFFD2\uFFFD"}:INTERPOLATION_2:\`; } var $I18N_7$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { @@ -642,7 +643,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_7$ = $localize \`$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c3$ = [ "title", $I18N_6$, @@ -651,7 +652,10 @@ describe('i18n support in the template compiler', () => { … decls: 5, vars: 8, - consts: [["id", "dynamic-1", ${AttributeMarker.I18n}, "aria-roledescription", "title", "aria-label"], ["id", "dynamic-2", ${AttributeMarker.I18n}, "title", "aria-roledescription"]], + consts: [["id", "dynamic-1", ${ + AttributeMarker + .I18n}, "aria-roledescription", "title", "aria-label"], ["id", "dynamic-2", ${ + AttributeMarker.I18n}, "title", "aria-roledescription"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div", 0); @@ -680,7 +684,7 @@ describe('i18n support in the template compiler', () => {
`; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { /** @@ -694,7 +698,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_1$ = $localize \`:m|d:intro $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c3$ = ["title", $I18N_1$]; … @@ -722,7 +726,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { /** @@ -736,7 +740,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_1$ = $localize \`:m|d:different scope $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c2$ = ["title", $I18N_1$]; function MyComponent_div_0_Template(rf, ctx) { @@ -758,7 +762,8 @@ describe('i18n support in the template compiler', () => { … decls: 1, vars: 1, - consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], [${AttributeMarker.I18n}, "title"]], + consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], [${ + AttributeMarker.I18n}, "title"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtemplate(0, MyComponent_div_0_Template, 4, 3, "div", 0); @@ -777,7 +782,7 @@ describe('i18n support in the template compiler', () => {
`; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_3462388422673575127$$APP_SPEC_TS_2$ = goog.getMsg("{$interpolation} title", { @@ -787,7 +792,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_1$ = $localize \`$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: title\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: title\`; } const $_c3$ = ["title", $I18N_1$]; … @@ -825,7 +830,7 @@ describe('i18n support in the template compiler', () => { > `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_5526535577705876535$$APP_SPEC_TS_1$ = goog.getMsg("static text"); @@ -847,7 +852,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_2$ = $localize \`:m|d:intro $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } var $I18N_3$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { @@ -862,7 +867,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_3$ = $localize \`:m1|d1:$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c1$ = [ "aria-roledescription", $I18N_1$, @@ -882,9 +887,9 @@ describe('i18n support in the template compiler', () => { } else { $I18N_6$ = $localize \`:m2|d2:$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: and $` + - String.raw `{"\uFFFD1\uFFFD"}:INTERPOLATION_1: and again $` + - String.raw `{"\uFFFD2\uFFFD"}:INTERPOLATION_2:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: and $` + + String.raw`{"\uFFFD1\uFFFD"}:INTERPOLATION_1: and again $` + + String.raw`{"\uFFFD2\uFFFD"}:INTERPOLATION_2:\`; } var $I18N_7$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { @@ -895,7 +900,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_7$ = $localize \`$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c3$ = [ "title", $I18N_6$, @@ -938,7 +943,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_2$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { /** @@ -952,7 +957,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_2$ = $localize \`:m|d:different scope $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c4$ = ["title", $I18N_2$]; function MyComponent_div_0_Template(rf, ctx) { @@ -974,7 +979,8 @@ describe('i18n support in the template compiler', () => { … decls: 1, vars: 1, - consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], [${AttributeMarker.I18n}, "title"]], + consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], [${ + AttributeMarker.I18n}, "title"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtemplate(0, MyComponent_div_0_Template, 4, 3, "div", 0); @@ -993,7 +999,7 @@ describe('i18n support in the template compiler', () => {
Some content
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { /** @@ -1036,7 +1042,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_ID_WITH_INVALID_CHARS$$APP_SPEC_TS_1$ = goog.getMsg("Element title"); @@ -1075,7 +1081,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelement(0, "div"); @@ -1097,7 +1103,7 @@ describe('i18n support in the template compiler', () => {
Some text
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_APP_SPEC_TS_1$ = goog.getMsg("Some text"); @@ -1115,11 +1121,11 @@ describe('i18n support in the template compiler', () => {
Some text 'with single quotes', "with double quotes", \`with backticks\` and without quotes.
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_4924931801512133405$$APP_SPEC_TS_0$ = goog.getMsg("Some text 'with single quotes', \"with double quotes\", ` + - '`with backticks`' + String.raw ` and without quotes."); + '`with backticks`' + String.raw` and without quotes."); $I18N_0$ = $MSG_EXTERNAL_4924931801512133405$$APP_SPEC_TS_0$; } else { @@ -1132,16 +1138,16 @@ describe('i18n support in the template compiler', () => { it('should handle interpolations wrapped in backticks', () => { const input = '
`{{ count }}`
'; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_APP_SPEC_TS_1$ = goog.getMsg("` + - '`{$interpolation}`' + String.raw `", { "interpolation": "\uFFFD0\uFFFD" }); + '`{$interpolation}`' + String.raw`", { "interpolation": "\uFFFD0\uFFFD" }); $I18N_0$ = $MSG_APP_SPEC_TS_1$; } else { $I18N_0$ = $localize \`\\\`$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\\\`\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\\\`\`; }`; verify(input, output); }); @@ -1155,7 +1161,7 @@ describe('i18n support in the template compiler', () => {
My i18n block #3
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_4890179241114413722$$APP_SPEC_TS_0$ = goog.getMsg("My i18n block #1"); @@ -1213,7 +1219,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_7597881511811528589$$APP_SPEC_TS_0$ = goog.getMsg(" Named interpolation: {$phA} Named interpolation with spaces: {$phB} ", { @@ -1224,8 +1230,8 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` Named interpolation: $` + - String.raw `{"\uFFFD0\uFFFD"}:PH_A: Named interpolation with spaces: $` + - String.raw `{"\uFFFD1\uFFFD"}:PH_B: \`; + String.raw`{"\uFFFD0\uFFFD"}:PH_A: Named interpolation with spaces: $` + + String.raw`{"\uFFFD1\uFFFD"}:PH_B: \`; } … decls: 2, @@ -1252,7 +1258,7 @@ describe('i18n support in the template compiler', () => {
{% valueA %}
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_6749967533321674787$$APP_SPEC_TS_0$ = goog.getMsg("{$interpolation}", { @@ -1262,7 +1268,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \`$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } … template: function MyComponent_Template(rf, ctx) { @@ -1290,7 +1296,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_APP_SPEC_TS_1$$APP_SPEC_TS_1$ = goog.getMsg(" {$interpolation} {$interpolation_1} {$interpolation_2} ", { @@ -1302,9 +1308,9 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + - String.raw `{"\uFFFD1\uFFFD"}:INTERPOLATION_1: $` + - String.raw `{"\uFFFD2\uFFFD"}:INTERPOLATION_2: \`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + + String.raw`{"\uFFFD1\uFFFD"}:INTERPOLATION_1: $` + + String.raw`{"\uFFFD2\uFFFD"}:INTERPOLATION_2: \`; } … template: function MyComponent_Template(rf, ctx) { @@ -1333,7 +1339,7 @@ describe('i18n support in the template compiler', () => {
My i18n block #{{ three + four + five }}
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_572579892698764378$$APP_SPEC_TS_0$ = goog.getMsg("My i18n block #{$interpolation}", { @@ -1343,7 +1349,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \`My i18n block #$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { @@ -1354,7 +1360,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_1$ = $localize \`My i18n block #$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } var $I18N_2$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { @@ -1365,7 +1371,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_2$ = $localize \`My i18n block #$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } … decls: 7, @@ -1418,7 +1424,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_7905233330103651696$$APP_SPEC_TS_0$ = goog.getMsg(" My i18n block #{$interpolation} {$startTagSpan}Plain text in nested element{$closeTagSpan}", { @@ -1430,9 +1436,9 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` My i18n block #$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + - String.raw `{"\uFFFD#2\uFFFD"}:START_TAG_SPAN:Plain text in nested element$` + - String.raw `{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_SPAN:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + + String.raw`{"\uFFFD#2\uFFFD"}:START_TAG_SPAN:Plain text in nested element$` + + String.raw`{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_SPAN:\`; } var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { @@ -1448,14 +1454,14 @@ describe('i18n support in the template compiler', () => { } else { $I18N_1$ = $localize \` My i18n block #$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + - String.raw `{"[\uFFFD#6\uFFFD|\uFFFD#7\uFFFD]"}:START_TAG_DIV:$` + - String.raw `{"[\uFFFD#6\uFFFD|\uFFFD#7\uFFFD]"}:START_TAG_DIV:$` + String.raw + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + + String.raw`{"[\uFFFD#6\uFFFD|\uFFFD#7\uFFFD]"}:START_TAG_DIV:$` + + String.raw`{"[\uFFFD#6\uFFFD|\uFFFD#7\uFFFD]"}:START_TAG_DIV:$` + String.raw `{"\uFFFD#8\uFFFD"}:START_TAG_SPAN: More bindings in more nested element: $` + - String.raw `{"\uFFFD1\uFFFD"}:INTERPOLATION_1: $` + - String.raw `{"\uFFFD/#8\uFFFD"}:CLOSE_TAG_SPAN:$` + - String.raw `{"[\uFFFD/#7\uFFFD|\uFFFD/#6\uFFFD]"}:CLOSE_TAG_DIV:$` + - String.raw `{"[\uFFFD/#7\uFFFD|\uFFFD/#6\uFFFD]"}:CLOSE_TAG_DIV:\`; + String.raw`{"\uFFFD1\uFFFD"}:INTERPOLATION_1: $` + + String.raw`{"\uFFFD/#8\uFFFD"}:CLOSE_TAG_SPAN:$` + + String.raw`{"[\uFFFD/#7\uFFFD|\uFFFD/#6\uFFFD]"}:CLOSE_TAG_DIV:$` + + String.raw`{"[\uFFFD/#7\uFFFD|\uFFFD/#6\uFFFD]"}:CLOSE_TAG_DIV:\`; } $I18N_1$ = $r3$.ɵɵi18nPostprocess($I18N_1$); … @@ -1509,7 +1515,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_2$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_4782264005467235841$$APP_SPEC_TS_3$ = goog.getMsg("Span title {$interpolation} and {$interpolation_1}", { @@ -1520,8 +1526,8 @@ describe('i18n support in the template compiler', () => { } else { $I18N_2$ = $localize \`Span title $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: and $` + - String.raw `{"\uFFFD1\uFFFD"}:INTERPOLATION_1:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: and $` + + String.raw`{"\uFFFD1\uFFFD"}:INTERPOLATION_1:\`; } const $_c4$ = ["title", $I18N_2$]; var $I18N_0$; @@ -1535,9 +1541,9 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` My i18n block #1 with value: $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + String.raw + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + String.raw `{"\uFFFD#2\uFFFD"}:START_TAG_SPAN: Plain text in nested element (block #1) $` + - String.raw `{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_SPAN:\`; + String.raw`{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_SPAN:\`; } var $I18N_7$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { @@ -1548,7 +1554,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_7$ = $localize \`Span title $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c9$ = ["title", $I18N_7$]; var $I18N_6$; @@ -1562,9 +1568,9 @@ describe('i18n support in the template compiler', () => { } else { $I18N_6$ = $localize \` My i18n block #2 with value $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + String.raw + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + String.raw `{"\uFFFD#7\uFFFD"}:START_TAG_SPAN: Plain text in nested element (block #2) $` + - String.raw `{"\uFFFD/#7\uFFFD"}:CLOSE_TAG_SPAN:\`; + String.raw`{"\uFFFD/#7\uFFFD"}:CLOSE_TAG_SPAN:\`; } … decls: 9, @@ -1623,7 +1629,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_7679414751795588050$$APP_SPEC_TS__1$ = goog.getMsg(" Some other content {$interpolation} {$startTagDiv} More nested levels with bindings {$interpolation_1} {$closeTagDiv}", { @@ -1636,10 +1642,10 @@ describe('i18n support in the template compiler', () => { } else { $I18N_1$ = $localize \` Some other content $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + - String.raw `{"\uFFFD#3\uFFFD"}:START_TAG_DIV: More nested levels with bindings $` + - String.raw `{"\uFFFD1\uFFFD"}:INTERPOLATION_1: $` + - String.raw `{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_DIV:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION: $` + + String.raw`{"\uFFFD#3\uFFFD"}:START_TAG_DIV: More nested levels with bindings $` + + String.raw`{"\uFFFD1\uFFFD"}:INTERPOLATION_1: $` + + String.raw`{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_DIV:\`; } … function MyComponent_div_2_Template(rf, ctx) { @@ -1688,7 +1694,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` function MyComponent_img_1_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelement(0, "img", 0); @@ -1703,7 +1709,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_2$ = $localize \`App logo #$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } const $_c4$ = ["title", $I18N_2$]; function MyComponent_img_2_Template(rf, ctx) { @@ -1721,7 +1727,11 @@ describe('i18n support in the template compiler', () => { … decls: 3, vars: 2, - consts: [["src", "logo.png"], ["src", "logo.png", ${AttributeMarker.Template}, "ngIf"], ["src", "logo.png", ${AttributeMarker.Bindings}, "title", ${AttributeMarker.Template}, "ngIf"], ["src", "logo.png", ${AttributeMarker.I18n}, "title"]], + consts: [["src", "logo.png"], ["src", "logo.png", ${ + AttributeMarker.Template}, "ngIf"], ["src", "logo.png", ${ + AttributeMarker.Bindings}, "title", ${ + AttributeMarker.Template}, "ngIf"], ["src", "logo.png", ${ + AttributeMarker.I18n}, "title"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelement(0, "img", 0); @@ -1765,7 +1775,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` function MyComponent_div_2_div_4_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵi18nStart(0, $I18N_0$, 2); @@ -1821,13 +1831,13 @@ describe('i18n support in the template compiler', () => { $I18N_0$ = $localize \` Some content $` + String.raw `{"\uFFFD*2:1\uFFFD\uFFFD#1:1\uFFFD"}:START_TAG_DIV_2: Some other content $` + - String.raw `{"\uFFFD0:1\uFFFD"}:INTERPOLATION: $` + String.raw + String.raw`{"\uFFFD0:1\uFFFD"}:INTERPOLATION: $` + String.raw `{"[\uFFFD#2:1\uFFFD|\uFFFD#2:2\uFFFD|\uFFFD#2:3\uFFFD]"}:START_TAG_DIV: More nested levels with bindings $` + - String.raw `{"\uFFFD1:1\uFFFD"}:INTERPOLATION_1: $` + String.raw + String.raw`{"\uFFFD1:1\uFFFD"}:INTERPOLATION_1: $` + String.raw `{"\uFFFD*4:2\uFFFD\uFFFD#1:2\uFFFD"}:START_TAG_DIV_1: Content inside sub-template $` + - String.raw `{"\uFFFD0:2\uFFFD"}:INTERPOLATION_2: $` + String.raw + String.raw`{"\uFFFD0:2\uFFFD"}:INTERPOLATION_2: $` + String.raw `{"[\uFFFD#2:1\uFFFD|\uFFFD#2:2\uFFFD|\uFFFD#2:3\uFFFD]"}:START_TAG_DIV: Bottom level element $` + - String.raw `{"\uFFFD1:2\uFFFD"}:INTERPOLATION_3: $` + String.raw + String.raw`{"\uFFFD1:2\uFFFD"}:INTERPOLATION_3: $` + String.raw `{"[\uFFFD/#2:2\uFFFD|\uFFFD/#1:2\uFFFD\uFFFD/*4:2\uFFFD|\uFFFD/#2:1\uFFFD|\uFFFD/#1:1\uFFFD\uFFFD/*2:1\uFFFD|\uFFFD/#2:3\uFFFD|\uFFFD/#1:3\uFFFD\uFFFD/*3:3\uFFFD]"}:CLOSE_TAG_DIV:$` + String.raw `{"[\uFFFD/#2:2\uFFFD|\uFFFD/#1:2\uFFFD\uFFFD/*4:2\uFFFD|\uFFFD/#2:1\uFFFD|\uFFFD/#1:1\uFFFD\uFFFD/*2:1\uFFFD|\uFFFD/#2:3\uFFFD|\uFFFD/#1:3\uFFFD\uFFFD/*3:3\uFFFD]"}:CLOSE_TAG_DIV:$` + @@ -1837,9 +1847,9 @@ describe('i18n support in the template compiler', () => { `{"[\uFFFD/#2:2\uFFFD|\uFFFD/#1:2\uFFFD\uFFFD/*4:2\uFFFD|\uFFFD/#2:1\uFFFD|\uFFFD/#1:1\uFFFD\uFFFD/*2:1\uFFFD|\uFFFD/#2:3\uFFFD|\uFFFD/#1:3\uFFFD\uFFFD/*3:3\uFFFD]"}:CLOSE_TAG_DIV:$` + String.raw `{"\uFFFD*3:3\uFFFD\uFFFD#1:3\uFFFD"}:START_TAG_DIV_3: Some other content $` + - String.raw `{"\uFFFD0:3\uFFFD"}:INTERPOLATION_4: $` + String.raw + String.raw`{"\uFFFD0:3\uFFFD"}:INTERPOLATION_4: $` + String.raw `{"[\uFFFD#2:1\uFFFD|\uFFFD#2:2\uFFFD|\uFFFD#2:3\uFFFD]"}:START_TAG_DIV: More nested levels with bindings $` + - String.raw `{"\uFFFD1:3\uFFFD"}:INTERPOLATION_5: $` + String.raw + String.raw`{"\uFFFD1:3\uFFFD"}:INTERPOLATION_5: $` + String.raw `{"[\uFFFD/#2:2\uFFFD|\uFFFD/#1:2\uFFFD\uFFFD/*4:2\uFFFD|\uFFFD/#2:1\uFFFD|\uFFFD/#1:1\uFFFD\uFFFD/*2:1\uFFFD|\uFFFD/#2:3\uFFFD|\uFFFD/#1:3\uFFFD\uFFFD/*3:3\uFFFD]"}:CLOSE_TAG_DIV:$` + String.raw `{"[\uFFFD/#2:2\uFFFD|\uFFFD/#1:2\uFFFD\uFFFD/*4:2\uFFFD|\uFFFD/#2:1\uFFFD|\uFFFD/#1:1\uFFFD\uFFFD/*2:1\uFFFD|\uFFFD/#2:3\uFFFD|\uFFFD/#1:3\uFFFD\uFFFD/*3:3\uFFFD]"}:CLOSE_TAG_DIV:\`; @@ -1891,7 +1901,7 @@ describe('i18n support in the template compiler', () => {
Some other content {{ valueA }}
`; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_119975189388320493$$APP_SPEC_TS__1$ = goog.getMsg("Some other content {$startTagSpan}{$interpolation}{$closeTagSpan}", { @@ -1903,9 +1913,9 @@ describe('i18n support in the template compiler', () => { } else { $I18N_1$ = $localize \`Some other content $` + - String.raw `{"\uFFFD#2\uFFFD"}:START_TAG_SPAN:$` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:$` + - String.raw `{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_SPAN:\`; + String.raw`{"\uFFFD#2\uFFFD"}:START_TAG_SPAN:$` + + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:$` + + String.raw`{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_SPAN:\`; } … function MyComponent_div_0_Template(rf, ctx) { @@ -1945,7 +1955,7 @@ describe('i18n support in the template compiler', () => {
Hello
`; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_APP_SPEC_TS_2$ = goog.getMsg("Hello"); @@ -1976,7 +1986,7 @@ describe('i18n support in the template compiler', () => {
My i18n block #1
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_4890179241114413722$$APP_SPEC_TS_0$ = goog.getMsg("My i18n block #1"); @@ -2003,7 +2013,7 @@ describe('i18n support in the template compiler', () => {
{age, select, 10 {ten} 20 {twenty} other {other}}
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_8806993169187953163$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, 10 {ten} 20 {twenty} other {other}}"); @@ -2041,7 +2051,7 @@ describe('i18n support in the template compiler', () => { My i18n block #2 `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_2413150872298537152$$APP_SPEC_TS_0$ = goog.getMsg("My i18n block #2"); @@ -2083,7 +2093,7 @@ describe('i18n support in the template compiler', () => { Text #2 `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_5295701706185791735$$APP_SPEC_TS_1$ = goog.getMsg("Text #1"); @@ -2103,7 +2113,8 @@ describe('i18n support in the template compiler', () => { … decls: 4, vars: 0, - consts: [[${AttributeMarker.Classes}, "myClass"], [${AttributeMarker.Styles}, "padding", "10px"]], + consts: [[${AttributeMarker.Classes}, "myClass"], [${ + AttributeMarker.Styles}, "padding", "10px"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "span", 0); @@ -2126,7 +2137,7 @@ describe('i18n support in the template compiler', () => { Some content: {{ valueA | uppercase }} `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_355394464191978948$$APP_SPEC_TS_0$ = goog.getMsg("Some content: {$interpolation}", { @@ -2136,7 +2147,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \`Some content: $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } … decls: 3, @@ -2164,7 +2175,7 @@ describe('i18n support in the template compiler', () => { Some content: {{ valueA | uppercase }} `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_355394464191978948$$APP_SPEC_TS__0$ = goog.getMsg("Some content: {$interpolation}", { @@ -2174,7 +2185,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \`Some content: $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION:\`; } function MyComponent_ng_template_0_Template(rf, ctx) { if (rf & 1) { @@ -2208,7 +2219,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_702706566400598764$$APP_SPEC_TS_0$ = goog.getMsg("{$startTagNgTemplate}Template content: {$interpolation}{$closeTagNgTemplate}{$startTagNgContainer}Container content: {$interpolation_1}{$closeTagNgContainer}", { @@ -2223,12 +2234,12 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \`$` + - String.raw `{"\uFFFD*2:1\uFFFD"}:START_TAG_NG_TEMPLATE:Template content: $` + - String.raw `{"\uFFFD0:1\uFFFD"}:INTERPOLATION:$` + - String.raw `{"\uFFFD/*2:1\uFFFD"}:CLOSE_TAG_NG_TEMPLATE:$` + - String.raw `{"\uFFFD#3\uFFFD"}:START_TAG_NG_CONTAINER:Container content: $` + - String.raw `{"\uFFFD0\uFFFD"}:INTERPOLATION_1:$` + - String.raw `{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_NG_CONTAINER:\`; + String.raw`{"\uFFFD*2:1\uFFFD"}:START_TAG_NG_TEMPLATE:Template content: $` + + String.raw`{"\uFFFD0:1\uFFFD"}:INTERPOLATION:$` + + String.raw`{"\uFFFD/*2:1\uFFFD"}:CLOSE_TAG_NG_TEMPLATE:$` + + String.raw`{"\uFFFD#3\uFFFD"}:START_TAG_NG_CONTAINER:Container content: $` + + String.raw`{"\uFFFD0\uFFFD"}:INTERPOLATION_1:$` + + String.raw`{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_NG_CONTAINER:\`; } function MyComponent_ng_template_2_Template(rf, ctx) { if (rf & 1) { @@ -2272,7 +2283,7 @@ describe('i18n support in the template compiler', () => { {age, select, 10 {ten} 20 {twenty} other {other}} `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_8806993169187953163$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, 10 {ten} 20 {twenty} other {other}}"); @@ -2341,7 +2352,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` function MyComponent_ng_template_2_ng_template_2_ng_template_1_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵi18n(0, $I18N_0$, 3); @@ -2380,11 +2391,11 @@ describe('i18n support in the template compiler', () => { $I18N_0$ = $localize \`$` + String.raw `{"[\uFFFD*2:1\uFFFD|\uFFFD*2:2\uFFFD|\uFFFD*1:3\uFFFD]"}:START_TAG_NG_TEMPLATE: Template A: $` + - String.raw `{"\uFFFD0:1\uFFFD"}:INTERPOLATION: $` + String.raw + String.raw`{"\uFFFD0:1\uFFFD"}:INTERPOLATION: $` + String.raw `{"[\uFFFD*2:1\uFFFD|\uFFFD*2:2\uFFFD|\uFFFD*1:3\uFFFD]"}:START_TAG_NG_TEMPLATE: Template B: $` + - String.raw `{"\uFFFD0:2\uFFFD"}:INTERPOLATION_1: $` + String.raw + String.raw`{"\uFFFD0:2\uFFFD"}:INTERPOLATION_1: $` + String.raw `{"[\uFFFD*2:1\uFFFD|\uFFFD*2:2\uFFFD|\uFFFD*1:3\uFFFD]"}:START_TAG_NG_TEMPLATE: Template C: $` + - String.raw `{"\uFFFD0:3\uFFFD"}:INTERPOLATION_2: $` + String.raw + String.raw`{"\uFFFD0:3\uFFFD"}:INTERPOLATION_2: $` + String.raw `{"[\uFFFD/*1:3\uFFFD|\uFFFD/*2:2\uFFFD|\uFFFD/*2:1\uFFFD]"}:CLOSE_TAG_NG_TEMPLATE:$` + String.raw `{"[\uFFFD/*1:3\uFFFD|\uFFFD/*2:2\uFFFD|\uFFFD/*2:1\uFFFD]"}:CLOSE_TAG_NG_TEMPLATE:$` + @@ -2429,7 +2440,7 @@ describe('i18n support in the template compiler', () => { {age, select, 10 {ten} 20 {twenty} other {other}} `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_7842238767399919809$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, male {male} female {female} other {other}}"); @@ -2493,7 +2504,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_4891196282781544695$$APP_SPEC_TS_0$ = goog.getMsg("{$tagImg} is my logo #1 ", { @@ -2503,7 +2514,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \`$` + - String.raw `{"\uFFFD#2\uFFFD\uFFFD/#2\uFFFD"}:TAG_IMG: is my logo #1 \`; + String.raw`{"\uFFFD#2\uFFFD\uFFFD/#2\uFFFD"}:TAG_IMG: is my logo #1 \`; } var $I18N_2$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { @@ -2514,7 +2525,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_2$ = $localize \`$` + - String.raw `{"\uFFFD#1\uFFFD\uFFFD/#1\uFFFD"}:TAG_IMG: is my logo #2 \`; + String.raw`{"\uFFFD#1\uFFFD\uFFFD/#1\uFFFD"}:TAG_IMG: is my logo #2 \`; } function MyComponent_ng_template_3_Template(rf, ctx) { if (rf & 1) { @@ -2550,7 +2561,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_8537814667662432133$$APP_SPEC_TS__0$ = goog.getMsg(" Root content {$startTagNgContainer} Nested content {$closeTagNgContainer}", { @@ -2563,7 +2574,7 @@ describe('i18n support in the template compiler', () => { $I18N_0$ = $localize \` Root content $` + String.raw `{"\uFFFD*1:1\uFFFD\uFFFD#1:1\uFFFD"}:START_TAG_NG_CONTAINER: Nested content $` + - String.raw `{"\uFFFD/#1:1\uFFFD\uFFFD/*1:1\uFFFD"}:CLOSE_TAG_NG_CONTAINER:\`; + String.raw`{"\uFFFD/#1:1\uFFFD\uFFFD/*1:1\uFFFD"}:CLOSE_TAG_NG_CONTAINER:\`; } … `; @@ -2580,7 +2591,7 @@ describe('i18n support in the template compiler', () => { // TODO(FW-635): currently we generate unique consts for each i18n block even though it // might contain the same content. This should be optimized by translation statements caching, // that can be implemented in the future within FW-635. - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_6563391987554512024$$APP_SPEC_TS_0$ = goog.getMsg("Test"); @@ -2610,7 +2621,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_APP_SPEC_TS_1$ = goog.getMsg(" Hello {$startTagNgContainer}there{$closeTagNgContainer}", { "startTagNgContainer": "\uFFFD#2\uFFFD", "closeTagNgContainer": "\uFFFD/#2\uFFFD" }); @@ -2618,8 +2629,8 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` Hello $` + - String.raw `{"\uFFFD#2\uFFFD"}:START_TAG_NG_CONTAINER:there$` + - String.raw `{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_NG_CONTAINER:\`; + String.raw`{"\uFFFD#2\uFFFD"}:START_TAG_NG_CONTAINER:there$` + + String.raw`{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_NG_CONTAINER:\`; } … decls: 3, @@ -2646,7 +2657,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_APP_SPEC_TS_1$ = goog.getMsg(" Hello {$startTagNgContainer}there {$startTagStrong}!{$closeTagStrong}{$closeTagNgContainer}", { "startTagNgContainer": "\uFFFD#2\uFFFD", "startTagStrong": "\uFFFD#3\uFFFD", "closeTagStrong": "\uFFFD/#3\uFFFD", "closeTagNgContainer": "\uFFFD/#2\uFFFD" }); @@ -2654,10 +2665,10 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` Hello $` + - String.raw `{"\uFFFD#2\uFFFD"}:START_TAG_NG_CONTAINER:there $` + - String.raw `{"\uFFFD#3\uFFFD"}:START_TAG_STRONG:!$` + - String.raw `{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_STRONG:$` + - String.raw `{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_NG_CONTAINER:\`; + String.raw`{"\uFFFD#2\uFFFD"}:START_TAG_NG_CONTAINER:there $` + + String.raw`{"\uFFFD#3\uFFFD"}:START_TAG_STRONG:!$` + + String.raw`{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_STRONG:$` + + String.raw`{"\uFFFD/#2\uFFFD"}:CLOSE_TAG_NG_CONTAINER:\`; } … decls: 4, @@ -2686,7 +2697,7 @@ describe('i18n support in the template compiler', () => { Content B `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_3308216566145348998$$APP_SPEC_TS___2$ = goog.getMsg("Content A"); @@ -2747,7 +2758,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_963542717423364282$$APP_SPEC_TS_0$ = goog.getMsg("\n Some text\n {$startTagSpan}Text inside span{$closeTagSpan}\n ", { @@ -2760,8 +2771,8 @@ describe('i18n support in the template compiler', () => { $I18N_0$ = $localize \` Some text $` + - String.raw `{"\uFFFD#3\uFFFD"}:START_TAG_SPAN:Text inside span$` + - String.raw `{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_SPAN: + String.raw`{"\uFFFD#3\uFFFD"}:START_TAG_SPAN:Text inside span$` + + String.raw`{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_SPAN: \`; } … @@ -2788,7 +2799,7 @@ describe('i18n support in the template compiler', () => {
{gender, select, male {male} female {female} other {other}}
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_7842238767399919809$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, male {male} female {female} other {other}}"); @@ -2825,7 +2836,7 @@ describe('i18n support in the template compiler', () => {
{gender, select, single {'single quotes'} double {"double quotes"} other {other}}
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_4166854826696768832$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, single {'single quotes'} double {\"double quotes\"} other {other}}"); @@ -2847,7 +2858,7 @@ describe('i18n support in the template compiler', () => { {age, select, 10 {ten} 20 {twenty} other {other}} `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_8806993169187953163$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, 10 {ten} 20 {twenty} other {other}}"); @@ -2887,7 +2898,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_7842238767399919809$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, male {male} female {female} other {other}}"); @@ -2955,7 +2966,9 @@ describe('i18n support in the template compiler', () => { … decls: 4, vars: 3, - consts: [["title", "icu only", ${AttributeMarker.Template}, "ngIf"], ["title", "icu and text", ${AttributeMarker.Template}, "ngIf"], ["title", "icu only"], ["title", "icu and text"]], + consts: [["title", "icu only", ${ + AttributeMarker.Template}, "ngIf"], ["title", "icu and text", ${ + AttributeMarker.Template}, "ngIf"], ["title", "icu only"], ["title", "icu and text"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div"); @@ -2984,7 +2997,7 @@ describe('i18n support in the template compiler', () => {
{age, select, 10 {ten} 20 {twenty} other {{% other %}}}
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_2949673783721159566$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, 10 {ten} 20 {twenty} other {{INTERPOLATION}}}"); @@ -3024,7 +3037,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_2417296354340576868$$APP_SPEC_TS_1$ = goog.getMsg("{VAR_SELECT, select, male {male - {START_BOLD_TEXT}male{CLOSE_BOLD_TEXT}} female {female {START_BOLD_TEXT}female{CLOSE_BOLD_TEXT}} other {{START_TAG_DIV}{START_ITALIC_TEXT}other{CLOSE_ITALIC_TEXT}{CLOSE_TAG_DIV}}}"); @@ -3057,13 +3070,13 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` $` + - String.raw `{$I18N_1$}:ICU: $` + - String.raw `{"\uFFFD#2\uFFFD"}:START_BOLD_TEXT:Other content$` + - String.raw `{"\uFFFD/#2\uFFFD"}:CLOSE_BOLD_TEXT:$` + - String.raw `{"\uFFFD#3\uFFFD"}:START_TAG_DIV:$` + - String.raw `{"\uFFFD#4\uFFFD"}:START_ITALIC_TEXT:Another content$` + - String.raw `{"\uFFFD/#4\uFFFD"}:CLOSE_ITALIC_TEXT:$` + - String.raw `{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_DIV:\`; + String.raw`{$I18N_1$}:ICU: $` + + String.raw`{"\uFFFD#2\uFFFD"}:START_BOLD_TEXT:Other content$` + + String.raw`{"\uFFFD/#2\uFFFD"}:CLOSE_BOLD_TEXT:$` + + String.raw`{"\uFFFD#3\uFFFD"}:START_TAG_DIV:$` + + String.raw`{"\uFFFD#4\uFFFD"}:START_ITALIC_TEXT:Another content$` + + String.raw`{"\uFFFD/#4\uFFFD"}:CLOSE_ITALIC_TEXT:$` + + String.raw`{"\uFFFD/#3\uFFFD"}:CLOSE_TAG_DIV:\`; } … decls: 5, @@ -3096,7 +3109,7 @@ describe('i18n support in the template compiler', () => {
{gender, select, male {male of age: {{ ageA + ageB + ageC }}} female {female} other {other}}
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_6879461626778511059$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, male {male of age: {INTERPOLATION}} female {female} other {other}}"); @@ -3137,7 +3150,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_7842238767399919809$$APP_SPEC_TS_1$ = goog.getMsg("{VAR_SELECT, select, male {male} female {female} other {other}}"); @@ -3170,7 +3183,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` $` + - String.raw `{$I18N_1$}:ICU: $` + String.raw `{$I18N_2$}:ICU_1: \`; + String.raw`{$I18N_1$}:ICU: $` + String.raw`{$I18N_2$}:ICU_1: \`; } … decls: 2, @@ -3205,7 +3218,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_APP_SPEC_TS_1$ = goog.getMsg("{VAR_SELECT, select, male {male} female {female} other {other}}"); @@ -3251,12 +3264,12 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` $` + - String.raw `{"\uFFFDI18N_EXP_ICU\uFFFD"}:ICU: $` + - String.raw `{"\uFFFD#2\uFFFD"}:START_TAG_DIV: $` + - String.raw `{"\uFFFDI18N_EXP_ICU\uFFFD"}:ICU: $` + String.raw + String.raw`{"\uFFFDI18N_EXP_ICU\uFFFD"}:ICU: $` + + String.raw`{"\uFFFD#2\uFFFD"}:START_TAG_DIV: $` + + String.raw`{"\uFFFDI18N_EXP_ICU\uFFFD"}:ICU: $` + String.raw `{"[\uFFFD/#2\uFFFD|\uFFFD/#1:1\uFFFD\uFFFD/*3:1\uFFFD]"}:CLOSE_TAG_DIV:$` + - String.raw `{"\uFFFD*3:1\uFFFD\uFFFD#1:1\uFFFD"}:START_TAG_DIV_1: $` + - String.raw `{"\uFFFDI18N_EXP_ICU\uFFFD"}:ICU: $` + String.raw + String.raw`{"\uFFFD*3:1\uFFFD\uFFFD#1:1\uFFFD"}:START_TAG_DIV_1: $` + + String.raw`{"\uFFFDI18N_EXP_ICU\uFFFD"}:ICU: $` + String.raw `{"[\uFFFD/#2\uFFFD|\uFFFD/#1:1\uFFFD\uFFFD/*3:1\uFFFD]"}:CLOSE_TAG_DIV:\`; } $I18N_0$ = $r3$.ɵɵi18nPostprocess($I18N_0$, { @@ -3314,7 +3327,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_343563413083115114$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT_1, select, male {male of age: {VAR_SELECT, select, 10 {ten} 20 {twenty} 30 {thirty} other {other}}} female {female} other {other}}"); @@ -3334,7 +3347,7 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` $` + - String.raw `{$I18N_1$}:ICU: \`; + String.raw`{$I18N_1$}:ICU: \`; } … decls: 2, vars: 2, @@ -3370,7 +3383,7 @@ describe('i18n support in the template compiler', () => { } `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_6870293071705078389$$APP_SPEC_TS_1$ = goog.getMsg("{VAR_PLURAL, plural, =0 {zero} =2 {{INTERPOLATION} {VAR_SELECT, select, cat {cats} dog {dogs} other {animals}} !} other {other - {INTERPOLATION}}}"); @@ -3414,7 +3427,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_7842238767399919809$$APP_SPEC_TS_1$ = goog.getMsg("{VAR_SELECT, select, male {male} female {female} other {other}}"); @@ -3449,10 +3462,10 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` $` + - String.raw `{$I18N_1$}:ICU: $` + - String.raw `{"\uFFFD*2:1\uFFFD\uFFFD#1:1\uFFFD"}:START_TAG_SPAN: $` + - String.raw `{$I18N_3$}:ICU_1: $` + - String.raw `{"\uFFFD/#1:1\uFFFD\uFFFD/*2:1\uFFFD"}:CLOSE_TAG_SPAN:\`; + String.raw`{$I18N_1$}:ICU: $` + + String.raw`{"\uFFFD*2:1\uFFFD\uFFFD#1:1\uFFFD"}:START_TAG_SPAN: $` + + String.raw`{$I18N_3$}:ICU_1: $` + + String.raw`{"\uFFFD/#1:1\uFFFD\uFFFD/*2:1\uFFFD"}:CLOSE_TAG_SPAN:\`; } function MyComponent_span_2_Template(rf, ctx) { if (rf & 1) { @@ -3501,7 +3514,7 @@ describe('i18n support in the template compiler', () => { `; - const output = String.raw ` + const output = String.raw` var $I18N_1$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_7825031864601787094$$APP_SPEC_TS_1$ = goog.getMsg("{VAR_SELECT, select, male {male {INTERPOLATION}} female {female {INTERPOLATION_1}} other {other}}"); @@ -3539,10 +3552,10 @@ describe('i18n support in the template compiler', () => { } else { $I18N_0$ = $localize \` $` + - String.raw `{I18N_1}:ICU: $` + - String.raw `{"\uFFFD*2:1\uFFFD\uFFFD#1:1\uFFFD"}:START_TAG_SPAN: $` + - String.raw `{I18N_3}:ICU_1: $` + - String.raw `{"\uFFFD/#1:1\uFFFD\uFFFD/*2:1\uFFFD"}:CLOSE_TAG_SPAN:\`; + String.raw`{I18N_1}:ICU: $` + + String.raw`{"\uFFFD*2:1\uFFFD\uFFFD#1:1\uFFFD"}:START_TAG_SPAN: $` + + String.raw`{I18N_3}:ICU_1: $` + + String.raw`{"\uFFFD/#1:1\uFFFD\uFFFD/*2:1\uFFFD"}:CLOSE_TAG_SPAN:\`; } function MyComponent_span_2_Template(rf, ctx) { if (rf & 1) { @@ -3592,7 +3605,7 @@ describe('i18n support in the template compiler', () => { } `; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { const $MSG_EXTERNAL_6318060397235942326$$APP_SPEC_TS_0$ = goog.getMsg("{VAR_SELECT, select, male {male {PH_A}} female {female {PH_B}} other {other {PH_WITH_SPACES}}}"); @@ -3632,7 +3645,7 @@ describe('i18n support in the template compiler', () => {
{count, select, 1 {one} other {more than one}}
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { /** @@ -3656,7 +3669,7 @@ describe('i18n support in the template compiler', () => { it('should add legacy message ids if `enableI18nLegacyMessageIdFormat` is true', () => { const input = `
Some Message
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { … } else { @@ -3671,7 +3684,7 @@ describe('i18n support in the template compiler', () => { it('should add legacy message ids if `enableI18nLegacyMessageIdFormat` is undefined', () => { const input = `
Some Message
`; - const output = String.raw ` + const output = String.raw` var $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { … } else { diff --git a/packages/compiler-cli/test/compliance/r3_view_compiler_input_outputs_spec.ts b/packages/compiler-cli/test/compliance/r3_view_compiler_input_outputs_spec.ts index b77b35449e..5d435b8d66 100644 --- a/packages/compiler-cli/test/compliance/r3_view_compiler_input_outputs_spec.ts +++ b/packages/compiler-cli/test/compliance/r3_view_compiler_input_outputs_spec.ts @@ -85,5 +85,4 @@ describe('compiler compliance: listen()', () => { expectEmit(result.source, componentDef, 'Incorrect component definition'); expectEmit(result.source, directiveDef, 'Incorrect directive definition'); }); - }); diff --git a/packages/compiler-cli/test/compliance/r3_view_compiler_listener_spec.ts b/packages/compiler-cli/test/compliance/r3_view_compiler_listener_spec.ts index 9534349ef4..b43dcafd45 100644 --- a/packages/compiler-cli/test/compliance/r3_view_compiler_listener_spec.ts +++ b/packages/compiler-cli/test/compliance/r3_view_compiler_listener_spec.ts @@ -10,8 +10,8 @@ import {setup} from '@angular/compiler/test/aot/test_util'; import {compile, expectEmit} from './mock_compile'; /* These tests are codified version of the tests in compiler_canonical_spec.ts. Every - * test in compiler_canonical_spec.ts should have a corresponding test here. - */ + * test in compiler_canonical_spec.ts should have a corresponding test here. + */ describe('compiler compliance: listen()', () => { const angularFiles = setup({ compileAngular: false, @@ -292,7 +292,8 @@ describe('compiler compliance: listen()', () => { const template = ` … - consts: [[${AttributeMarker.Bindings}, "click", "change"], [${AttributeMarker.Bindings}, "update", "delete"]], + consts: [[${AttributeMarker.Bindings}, "click", "change"], [${ + AttributeMarker.Bindings}, "update", "delete"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div", 0); @@ -446,5 +447,4 @@ describe('compiler compliance: listen()', () => { const result = compile(files, angularFiles); expectEmit(result.source, template, 'Incorrect host bindings'); }); - }); diff --git a/packages/compiler-cli/test/compliance/r3_view_compiler_styling_spec.ts b/packages/compiler-cli/test/compliance/r3_view_compiler_styling_spec.ts index ba79859605..685b1ef69c 100644 --- a/packages/compiler-cli/test/compliance/r3_view_compiler_styling_spec.ts +++ b/packages/compiler-cli/test/compliance/r3_view_compiler_styling_spec.ts @@ -622,7 +622,6 @@ describe('compiler compliance: styling', () => { const result = compile(files, angularFiles); expect(result.source).not.toContain('styling'); }); - }); describe('[class]', () => { @@ -743,7 +742,8 @@ describe('compiler compliance: styling', () => { selectors:[["my-component"]], decls: 1, vars: 2, - consts: [[${AttributeMarker.Classes}, "foo", ${AttributeMarker.Styles}, "width", "100px"]], + consts: [[${AttributeMarker.Classes}, "foo", ${ + AttributeMarker.Styles}, "width", "100px"]], template: function MyComponent_Template(rf, $ctx$) { if (rf & 1) { $r3$.ɵɵelement(0, "div", 0); @@ -782,7 +782,6 @@ describe('compiler compliance: styling', () => { const result = compile(files, angularFiles); expect(result.source).not.toContain('styling'); }); - }); describe('[style] mixed with [class]', () => { @@ -1005,7 +1004,8 @@ describe('compiler compliance: styling', () => { }; const template = ` - hostAttrs: [${AttributeMarker.Classes}, "foo", "baz", ${AttributeMarker.Styles}, "width", "200px", "height", "500px"], + hostAttrs: [${AttributeMarker.Classes}, "foo", "baz", ${ + AttributeMarker.Styles}, "width", "200px", "height", "500px"], hostVars: 8, hostBindings: function MyComponent_HostBindings(rf, ctx) { if (rf & 2) { @@ -1594,7 +1594,6 @@ describe('compiler compliance: styling', () => { expectEmit(result.source, template, 'Incorrect handling of interpolated style properties'); }); - }); describe('instruction chaining', () => { @@ -1981,7 +1980,8 @@ describe('compiler compliance: styling', () => { }; const template = ` - hostAttrs: ["title", "foo title", ${AttributeMarker.Classes}, "foo", "baz", ${AttributeMarker.Styles}, "width", "200px", "height", "500px"], + hostAttrs: ["title", "foo title", ${AttributeMarker.Classes}, "foo", "baz", ${ + AttributeMarker.Styles}, "width", "200px", "height", "500px"], hostVars: 6, hostBindings: function MyComponent_HostBindings(rf, ctx) { if (rf & 2) { diff --git a/packages/compiler-cli/test/compliance/r3_view_compiler_template_spec.ts b/packages/compiler-cli/test/compliance/r3_view_compiler_template_spec.ts index c6e795d9ba..4b10387526 100644 --- a/packages/compiler-cli/test/compliance/r3_view_compiler_template_spec.ts +++ b/packages/compiler-cli/test/compliance/r3_view_compiler_template_spec.ts @@ -103,7 +103,10 @@ describe('compiler compliance: template', () => { } } // ... - consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], [${AttributeMarker.Bindings}, "title", "click", ${AttributeMarker.Template}, "ngFor", "ngForOf"], [${AttributeMarker.Bindings}, "title", "click"]], + consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], [${ + AttributeMarker.Bindings}, "title", "click", ${ + AttributeMarker.Template}, "ngFor", "ngForOf"], [${ + AttributeMarker.Bindings}, "title", "click"]], template:function MyComponent_Template(rf, ctx){ if (rf & 1) { $i0$.ɵɵtemplate(0, MyComponent_ul_0_Template, 2, 1, "ul", 0); @@ -157,7 +160,8 @@ describe('compiler compliance: template', () => { } } // ... - consts: [[${AttributeMarker.Bindings}, "click", ${AttributeMarker.Template}, "ngFor", "ngForOf"], [${AttributeMarker.Bindings}, "click"]], + consts: [[${AttributeMarker.Bindings}, "click", ${ + AttributeMarker.Template}, "ngFor", "ngForOf"], [${AttributeMarker.Bindings}, "click"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtemplate(0, MyComponent_div_0_Template, 1, 0, "div", 0); @@ -329,7 +333,8 @@ describe('compiler compliance: template', () => { } // ... - consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], [${AttributeMarker.Template}, "ngIf"]], + consts: [[${AttributeMarker.Template}, "ngFor", "ngForOf"], [${ + AttributeMarker.Template}, "ngIf"]], template:function MyComponent_Template(rf, ctx){ if (rf & 1) { $i0$.ɵɵtemplate(0, MyComponent_div_0_Template, 2, 1, "div", 0); @@ -472,7 +477,6 @@ describe('compiler compliance: template', () => { }); it('should support local refs on ', () => { - const files = { app: { 'spec.ts': ` @@ -511,7 +515,6 @@ describe('compiler compliance: template', () => { }); it('should support directive outputs on ', () => { - const files = { app: { 'spec.ts': ` @@ -545,7 +548,6 @@ describe('compiler compliance: template', () => { const result = compile(files, angularFiles); expectEmit(result.source, template, 'Incorrect template'); - }); it('should allow directive inputs as an interpolated prop on ', () => { diff --git a/packages/compiler-cli/test/diagnostics/check_types_spec.ts b/packages/compiler-cli/test/diagnostics/check_types_spec.ts index de0810397b..d2155d93d0 100644 --- a/packages/compiler-cli/test/diagnostics/check_types_spec.ts +++ b/packages/compiler-cli/test/diagnostics/check_types_spec.ts @@ -11,7 +11,8 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import * as ts from 'typescript'; -import {TestSupport, expectNoDiagnostics, setup} from '../test_support'; + +import {expectNoDiagnostics, setup, TestSupport} from '../test_support'; type MockFiles = { [fileName: string]: string @@ -47,19 +48,19 @@ describe('ng type checker', () => { } function reject( - message: string | RegExp, location: RegExp | null, files: MockFiles, + message: string|RegExp, location: RegExp|null, files: MockFiles, overrideOptions: ng.CompilerOptions = {}) { const diagnostics = compileAndCheck([QUICKSTART, files], overrideOptions); if (!diagnostics || !diagnostics.length) { throw new Error('Expected a diagnostic error message'); } else { - const matches: (d: ng.Diagnostic | ts.Diagnostic) => boolean = typeof message === 'string' ? + const matches: (d: ng.Diagnostic|ts.Diagnostic) => boolean = typeof message === 'string' ? d => ng.isNgDiagnostic(d)&& d.messageText == message : d => ng.isNgDiagnostic(d) && message.test(d.messageText); const matchingDiagnostics = diagnostics.filter(matches) as ng.Diagnostic[]; if (!matchingDiagnostics || !matchingDiagnostics.length) { - throw new Error( - `Expected a diagnostics matching ${message}, received\n ${diagnostics.map(d => d.messageText).join('\n ')}`); + throw new Error(`Expected a diagnostics matching ${message}, received\n ${ + diagnostics.map(d => d.messageText).join('\n ')}`); } if (location) { @@ -72,7 +73,9 @@ describe('ng type checker', () => { } } - it('should accept unmodified QuickStart', () => { accept(); }); + it('should accept unmodified QuickStart', () => { + accept(); + }); it('should accept unmodified QuickStart with tests for unused variables', () => { accept({}, { @@ -523,7 +526,7 @@ describe('ng type checker', () => { }; const r = - (message: string | RegExp, location: RegExp | null, files: MockFiles, + (message: string|RegExp, location: RegExp|null, files: MockFiles, options: ng.AngularCompilerOptions = {}) => { reject( message, location, {'src/app.component.ts': '', 'src/lib.ts': '', ...files}, @@ -712,16 +715,18 @@ describe('ng type checker', () => { }); function addTests(config: {fullTemplateTypeCheck: boolean}) { - function a(template: string) { accept({'src/app.component.html': template}, config); } + function a(template: string) { + accept({'src/app.component.html': template}, config); + } - function r(template: string, message: string | RegExp, location: string) { + function r(template: string, message: string|RegExp, location: string) { reject( message, new RegExp(`app\.component\.html\@${location}$`), {'src/app.component.html': template}, config); } function rejectOnlyWithFullTemplateTypeCheck( - template: string, message: string | RegExp, location: string) { + template: string, message: string|RegExp, location: string) { if (config.fullTemplateTypeCheck) { r(template, message, location); } else { @@ -732,23 +737,33 @@ describe('ng type checker', () => { it('should report an invalid field access', () => { r('
{{fame}}
', `Property 'fame' does not exist on type 'AppComponent'.`, '0:5'); }); - it('should reject a reference to a field of a nullable', - () => { r('
{{maybePerson.name}}
', `Object is possibly 'undefined'.`, '0:5'); }); - it('should accept a reference to a field of a nullable using using non-null-assert', - () => { a('{{maybePerson!.name}}'); }); - it('should accept a safe property access of a nullable person', - () => { a('{{maybePerson?.name}}'); }); + it('should reject a reference to a field of a nullable', () => { + r('
{{maybePerson.name}}
', `Object is possibly 'undefined'.`, '0:5'); + }); + it('should accept a reference to a field of a nullable using using non-null-assert', () => { + a('{{maybePerson!.name}}'); + }); + it('should accept a safe property access of a nullable person', () => { + a('{{maybePerson?.name}}'); + }); - it('should accept using a library pipe', () => { a('{{1 | libPipe}}'); }); - it('should accept using a library directive', - () => { a('
{{libDir.name}}
'); }); + it('should accept using a library pipe', () => { + a('{{1 | libPipe}}'); + }); + it('should accept using a library directive', () => { + a('
{{libDir.name}}
'); + }); - it('should accept a function call', () => { a('{{getName()}}'); }); + it('should accept a function call', () => { + a('{{getName()}}'); + }); it('should reject an invalid method', () => { r('
{{getFame()}}
', `Property 'getFame' does not exist on type 'AppComponent'. Did you mean 'getName'?`, '0:5'); }); - it('should accept a field access of a method result', () => { a('{{getPerson().name}}'); }); + it('should accept a field access of a method result', () => { + a('{{getPerson().name}}'); + }); it('should reject an invalid field reference of a method result', () => { r('
{{getPerson().fame}}
', `Property 'fame' does not exist on type 'Person'.`, '0:5'); @@ -756,10 +771,13 @@ describe('ng type checker', () => { it('should reject an access to a nullable field of a method result', () => { r('
{{getMaybePerson().name}}
', `Object is possibly 'undefined'.`, '0:5'); }); - it('should accept a nullable assert of a nullable field references of a method result', - () => { a('{{getMaybePerson()!.name}}'); }); + it('should accept a nullable assert of a nullable field references of a method result', () => { + a('{{getMaybePerson()!.name}}'); + }); it('should accept a safe property access of a nullable field reference of a method result', - () => { a('{{getMaybePerson()?.name}}'); }); + () => { + a('{{getMaybePerson()?.name}}'); + }); it('should report an invalid field access inside of an ng-template', () => { rejectOnlyWithFullTemplateTypeCheck( @@ -779,8 +797,9 @@ describe('ng type checker', () => { } describe('with lowered expressions', () => { - it('should not report lowered expressions as errors', - () => { expectNoDiagnostics({}, compileAndCheck([LOWERING_QUICKSTART])); }); + it('should not report lowered expressions as errors', () => { + expectNoDiagnostics({}, compileAndCheck([LOWERING_QUICKSTART])); + }); }); }); diff --git a/packages/compiler-cli/test/diagnostics/typescript_version_spec.ts b/packages/compiler-cli/test/diagnostics/typescript_version_spec.ts index 605b3e1ed7..3e817cced5 100644 --- a/packages/compiler-cli/test/diagnostics/typescript_version_spec.ts +++ b/packages/compiler-cli/test/diagnostics/typescript_version_spec.ts @@ -18,8 +18,9 @@ describe('toNumbers', () => { }); describe('compareNumbers', () => { - - it('should handle empty arrays', () => { expect(compareNumbers([], [])).toEqual(0); }); + it('should handle empty arrays', () => { + expect(compareNumbers([], [])).toEqual(0); + }); it('should handle arrays of same length', () => { expect(compareNumbers([1], [3])).toEqual(-1); diff --git a/packages/compiler-cli/test/extract_i18n_spec.ts b/packages/compiler-cli/test/extract_i18n_spec.ts index f2d4aad046..39569ac554 100644 --- a/packages/compiler-cli/test/extract_i18n_spec.ts +++ b/packages/compiler-cli/test/extract_i18n_spec.ts @@ -207,7 +207,9 @@ describe('extract_i18n command line', () => { beforeEach(() => { errorSpy = jasmine.createSpy('consoleError').and.callFake(console.error); const support = setup(); - write = (fileName: string, content: string) => { support.write(fileName, content); }; + write = (fileName: string, content: string) => { + support.write(fileName, content); + }; basePath = support.basePath; outDir = path.join(basePath, 'built'); write('tsconfig-base.json', `{ diff --git a/packages/compiler-cli/test/helpers/src/mock_file_loading.ts b/packages/compiler-cli/test/helpers/src/mock_file_loading.ts index 8cfdf54f3f..baf20e7ed4 100644 --- a/packages/compiler-cli/test/helpers/src/mock_file_loading.ts +++ b/packages/compiler-cli/test/helpers/src/mock_file_loading.ts @@ -7,7 +7,7 @@ */ /// -import {readFileSync, readdirSync, statSync} from 'fs'; +import {readdirSync, readFileSync, statSync} from 'fs'; import {resolve} from 'path'; import {getAngularPackagesFromRunfiles, resolveNpmTreeArtifact} from '..'; diff --git a/packages/compiler-cli/test/helpers/src/runfile_helpers.ts b/packages/compiler-cli/test/helpers/src/runfile_helpers.ts index bb848881dd..72ad3c9d7b 100644 --- a/packages/compiler-cli/test/helpers/src/runfile_helpers.ts +++ b/packages/compiler-cli/test/helpers/src/runfile_helpers.ts @@ -22,7 +22,7 @@ export function getAngularPackagesFromRunfiles() { const runfilesManifestPath = process.env.RUNFILES_MANIFEST_FILE; if (!runfilesManifestPath) { - const packageRunfilesDir = path.join(process.env.RUNFILES !, 'angular/packages'); + const packageRunfilesDir = path.join(process.env.RUNFILES!, 'angular/packages'); return fs.readdirSync(packageRunfilesDir) .map(name => ({name, pkgPath: path.join(packageRunfilesDir, name, 'npm_package/')})) diff --git a/packages/compiler-cli/test/metadata/bundler_spec.ts b/packages/compiler-cli/test/metadata/bundler_spec.ts index 8e147e1a98..7f8d297a1d 100644 --- a/packages/compiler-cli/test/metadata/bundler_spec.ts +++ b/packages/compiler-cli/test/metadata/bundler_spec.ts @@ -15,7 +15,6 @@ import {ClassMetadata, MetadataEntry, MetadataGlobalReferenceExpression, ModuleM import {Directory, MockAotContext, MockCompilerHost} from '../mocks'; describe('compiler host adapter', () => { - it('should retrieve metadata for an explicit index relative path reference', () => { const context = new MockAotContext('.', SIMPLE_LIBRARY); const host = new MockCompilerHost(context); @@ -28,7 +27,7 @@ describe('compiler host adapter', () => { const metadata = adapter.getMetadataFor('./lib/src/two/index', '.'); expect(metadata).toBeDefined(); - expect(Object.keys(metadata !.metadata).sort()).toEqual([ + expect(Object.keys(metadata!.metadata).sort()).toEqual([ 'PrivateTwo', 'TWO_CLASSES', 'Two', @@ -48,7 +47,7 @@ describe('compiler host adapter', () => { const metadata = adapter.getMetadataFor('./lib/src/two', '.'); expect(metadata).toBeDefined(); - expect(Object.keys(metadata !.metadata).sort()).toEqual([ + expect(Object.keys(metadata!.metadata).sort()).toEqual([ 'PrivateTwo', 'TWO_CLASSES', 'Two', @@ -82,7 +81,7 @@ describe('compiler host adapter', () => { const metadata = adapter.getMetadataFor('./lib/src/index', '.'); expect(metadata).toBeDefined(); - expect(metadata !.exports !.map(e => e.export !) + expect(metadata!.exports!.map(e => e.export !) .reduce((prev, next) => prev.concat(next), []) .sort()) .toEqual([ @@ -127,13 +126,13 @@ describe('compiler host adapter', () => { const metadata = adapter.getMetadataFor('./lib', '.'); expect(metadata).toBeDefined(); - expect(Object.keys(metadata !.metadata).sort()).toEqual([ + expect(Object.keys(metadata!.metadata).sort()).toEqual([ 'ONE_CLASSES', 'One', 'OneMore', 'PrivateOne', ]); - expect(Array.isArray(metadata !.metadata !['ONE_CLASSES'])).toBeTruthy(); + expect(Array.isArray(metadata!.metadata!['ONE_CLASSES'])).toBeTruthy(); }); it('should look for non-declaration file when resolving metadata via a package.json "types" entry', @@ -180,19 +179,17 @@ describe('compiler host adapter', () => { const metadata = adapter.getMetadataFor('./lib', '.'); expect(metadata).toBeDefined(); - expect(Object.keys(metadata !.metadata).sort()).toEqual([ + expect(Object.keys(metadata!.metadata).sort()).toEqual([ 'ONE_CLASSES', 'One', 'OneMore', 'PrivateOne', ]); - expect(Array.isArray(metadata !.metadata !['ONE_CLASSES'])).toBeTruthy(); - + expect(Array.isArray(metadata!.metadata!['ONE_CLASSES'])).toBeTruthy(); }); }); describe('metadata bundler', () => { - it('should be able to bundle a simple library', () => { const host = new MockStringBundlerHost('/', SIMPLE_LIBRARY); const bundler = new MetadataBundler('/lib/index', undefined, host, 'prfx_'); @@ -203,9 +200,9 @@ describe('metadata bundler', () => { const originalOne = './src/one'; const originalTwo = './src/two/index'; - expect(Object.keys(result.metadata.origins !) + expect(Object.keys(result.metadata.origins!) .sort() - .map(name => ({name, value: result.metadata.origins ![name]}))) + .map(name => ({name, value: result.metadata.origins![name]}))) .toEqual([ {name: 'ONE_CLASSES', value: originalOne}, {name: 'One', value: originalOne}, {name: 'OneMore', value: originalOne}, {name: 'TWO_CLASSES', value: originalTwo}, @@ -239,7 +236,7 @@ describe('metadata bundler', () => { }); const bundler = new MetadataBundler('/lib/index', undefined, host); const bundledMetadata = bundler.getMetadataBundle().metadata; - const deepIndexMetadata = host.getMetadataFor('/lib/deep/index') !; + const deepIndexMetadata = host.getMetadataFor('/lib/deep/index')!; // The unbundled metadata should reference symbols using the relative module path. expect(deepIndexMetadata.metadata['MyClass']).toEqual(jasmine.objectContaining({ @@ -419,7 +416,7 @@ describe('metadata bundler', () => { from: 'external_one' } ]); - expect(result.metadata.origins !['E']).toBeUndefined(); + expect(result.metadata.origins!['E']).toBeUndefined(); }); it('should be able to bundle a library with multiple unnamed re-exports', () => { @@ -456,7 +453,7 @@ describe('metadata bundler', () => { const bundler = new MetadataBundler('/public-api', undefined, host); const result = bundler.getMetadataBundle(); - const {A, A2, A3, B1, B2} = result.metadata.metadata as{ + const {A, A2, A3, B1, B2} = result.metadata.metadata as { A: ClassMetadata, A2: MetadataGlobalReferenceExpression, A3: ClassMetadata, diff --git a/packages/compiler-cli/test/metadata/collector_spec.ts b/packages/compiler-cli/test/metadata/collector_spec.ts index dffe560d32..5b591e0bea 100644 --- a/packages/compiler-cli/test/metadata/collector_spec.ts +++ b/packages/compiler-cli/test/metadata/collector_spec.ts @@ -9,9 +9,9 @@ import * as ts from 'typescript'; import {MetadataCollector} from '../../src/metadata/collector'; -import {ClassMetadata, ConstructorMetadata, METADATA_VERSION, MetadataEntry, MetadataMap, MetadataSymbolicExpression, ModuleMetadata, isClassMetadata, isMetadataGlobalReferenceExpression} from '../../src/metadata/schema'; +import {ClassMetadata, ConstructorMetadata, isClassMetadata, isMetadataGlobalReferenceExpression, METADATA_VERSION, MetadataEntry, MetadataMap, MetadataSymbolicExpression, ModuleMetadata} from '../../src/metadata/schema'; -import {Directory, Host, expectValidSources} from './typescript.mocks'; +import {Directory, expectValidSources, Host} from './typescript.mocks'; describe('Collector', () => { const documentRegistry = ts.createDocumentRegistry(); @@ -40,20 +40,22 @@ describe('Collector', () => { 'interface-reference.ts', 'static-type-check-members.ts', ]); service = ts.createLanguageService(host, documentRegistry); - program = service.getProgram() !; + program = service.getProgram()!; collector = new MetadataCollector({quotedNames: true}); }); - it('should not have errors in test data', () => { expectValidSources(service, program); }); + it('should not have errors in test data', () => { + expectValidSources(service, program); + }); it('should return undefined for modules that have no metadata', () => { - const sourceFile = program.getSourceFile('app/empty.ts') !; + const sourceFile = program.getSourceFile('app/empty.ts')!; const metadata = collector.getMetadata(sourceFile); expect(metadata).toBeUndefined(); }); it('should treat all symbols of .d.ts files as exported', () => { - const sourceFile = program.getSourceFile('declarations.d.ts') !; + const sourceFile = program.getSourceFile('declarations.d.ts')!; const metadata = collector.getMetadata(sourceFile); expect(metadata).toEqual({ __symbolic: 'module', @@ -66,7 +68,7 @@ describe('Collector', () => { }); it('should return an interface reference for types', () => { - const sourceFile = program.getSourceFile('/exported-type.ts') !; + const sourceFile = program.getSourceFile('/exported-type.ts')!; const metadata = collector.getMetadata(sourceFile); expect(metadata).toEqual({ __symbolic: 'module', @@ -76,7 +78,7 @@ describe('Collector', () => { }); it('should return an interface reference for interfaces', () => { - const sourceFile = program.getSourceFile('app/hero.ts') !; + const sourceFile = program.getSourceFile('app/hero.ts')!; const metadata = collector.getMetadata(sourceFile); expect(metadata).toEqual({ __symbolic: 'module', @@ -86,13 +88,13 @@ describe('Collector', () => { }); it('should preserve module names from TypeScript sources', () => { - const sourceFile = program.getSourceFile('named-module.d.ts') !; + const sourceFile = program.getSourceFile('named-module.d.ts')!; const metadata = collector.getMetadata(sourceFile); - expect(metadata !['importAs']).toEqual('some-named-module'); + expect(metadata!['importAs']).toEqual('some-named-module'); }); it('should be able to collect a simple component\'s metadata', () => { - const sourceFile = program.getSourceFile('app/hero-detail.component.ts') !; + const sourceFile = program.getSourceFile('app/hero-detail.component.ts')!; const metadata = collector.getMetadata(sourceFile); expect(metadata).toEqual({ __symbolic: 'module', @@ -144,7 +146,7 @@ describe('Collector', () => { }); it('should be able to get a more complicated component\'s metadata', () => { - const sourceFile = program.getSourceFile('/app/app.component.ts') !; + const sourceFile = program.getSourceFile('/app/app.component.ts')!; const metadata = collector.getMetadata(sourceFile); expect(metadata).toEqual({ __symbolic: 'module', @@ -236,7 +238,7 @@ describe('Collector', () => { }); it('should return the values of exported variables', () => { - const sourceFile = program.getSourceFile('/app/mock-heroes.ts') !; + const sourceFile = program.getSourceFile('/app/mock-heroes.ts')!; const metadata = collector.getMetadata(sourceFile); expect(metadata).toEqual({ __symbolic: 'module', @@ -262,14 +264,14 @@ describe('Collector', () => { let casesMetadata: ModuleMetadata; beforeEach(() => { - casesFile = program.getSourceFile('/app/cases-data.ts') !; - casesMetadata = collector.getMetadata(casesFile) !; + casesFile = program.getSourceFile('/app/cases-data.ts')!; + casesMetadata = collector.getMetadata(casesFile)!; }); it('should provide any reference for an any ctor parameter type', () => { const casesAny = casesMetadata.metadata['CaseAny']; expect(casesAny).toBeTruthy(); - const ctorData = casesAny.members !['__ctor__'] as ConstructorMetadata[]; + const ctorData = casesAny.members!['__ctor__'] as ConstructorMetadata[]; expect(ctorData).toEqual([{ __symbolic: 'constructor', parameters: [{__symbolic: 'reference', name: 'any'} as MetadataSymbolicExpression] @@ -300,7 +302,8 @@ describe('Collector', () => { it('should record references to parameterized types', () => { const casesForIn = casesMetadata.metadata['NgFor']; expect(casesForIn).toEqual({ - __symbolic: 'class', decorators: [{ + __symbolic: 'class', + decorators: [{ __symbolic: 'call', expression: { __symbolic: 'reference', @@ -310,21 +313,21 @@ describe('Collector', () => { character: 7 } }], - members: { - __ctor__: [{ - __symbolic: 'constructor', - parameters: [{ - __symbolic: 'reference', - name: 'ClassReference', - arguments: [{__symbolic: 'reference', name: 'NgForRow'}] - }] - }] - } + members: { + __ctor__: [{ + __symbolic: 'constructor', + parameters: [{ + __symbolic: 'reference', + name: 'ClassReference', + arguments: [{__symbolic: 'reference', name: 'NgForRow'}] + }] + }] + } } as any as ClassMetadata); // TODO: Review use of `any` here (#19904) }); it('should report errors for destructured imports', () => { - const unsupported1 = program.getSourceFile('/unsupported-1.ts') !; + const unsupported1 = program.getSourceFile('/unsupported-1.ts')!; const metadata = collector.getMetadata(unsupported1); expect(metadata).toEqual({ __symbolic: 'module', @@ -340,11 +343,11 @@ describe('Collector', () => { }); it('should report an error for references to unexpected types', () => { - const unsupported1 = program.getSourceFile('/unsupported-2.ts') !; - const metadata = collector.getMetadata(unsupported1) !; + const unsupported1 = program.getSourceFile('/unsupported-2.ts')!; + const metadata = collector.getMetadata(unsupported1)!; const barClass = metadata.metadata['Bar']; - const ctor = barClass.members !['__ctor__'][0]; - const parameter = ctor.parameters ![0]; + const ctor = barClass.members!['__ctor__'][0]; + const parameter = ctor.parameters![0]; expect(parameter).toEqual({ __symbolic: 'error', message: 'Reference to non-exported class', @@ -355,18 +358,19 @@ describe('Collector', () => { }); it('should be able to handle import star type references', () => { - const importStar = program.getSourceFile('/import-star.ts') !; - const metadata = collector.getMetadata(importStar) !; + const importStar = program.getSourceFile('/import-star.ts')!; + const metadata = collector.getMetadata(importStar)!; const someClass = metadata.metadata['SomeClass']; - const ctor = someClass.members !['__ctor__'][0]; + const ctor = someClass.members!['__ctor__'][0]; const parameters = ctor.parameters; - expect(parameters).toEqual([{ - __symbolic: 'reference', module: 'angular2/common', name: 'NgFor', line: 6, character: 29 - } as MetadataSymbolicExpression]); + expect(parameters).toEqual([ + {__symbolic: 'reference', module: 'angular2/common', name: 'NgFor', line: 6, character: 29} as + MetadataSymbolicExpression + ]); }); it('should record all exported classes', () => { - const sourceFile = program.getSourceFile('/exported-classes.ts') !; + const sourceFile = program.getSourceFile('/exported-classes.ts')!; const metadata = collector.getMetadata(sourceFile); expect(metadata).toEqual({ __symbolic: 'module', @@ -380,7 +384,7 @@ describe('Collector', () => { }); it('should be able to record functions', () => { - const exportedFunctions = program.getSourceFile('/exported-functions.ts') !; + const exportedFunctions = program.getSourceFile('/exported-functions.ts')!; const metadata = collector.getMetadata(exportedFunctions); expect(metadata).toEqual({ __symbolic: 'module', @@ -440,26 +444,27 @@ describe('Collector', () => { }); it('should be able to handle import star type references', () => { - const importStar = program.getSourceFile('/import-star.ts') !; - const metadata = collector.getMetadata(importStar) !; + const importStar = program.getSourceFile('/import-star.ts')!; + const metadata = collector.getMetadata(importStar)!; const someClass = metadata.metadata['SomeClass']; - const ctor = someClass.members !['__ctor__'][0]; + const ctor = someClass.members!['__ctor__'][0]; const parameters = ctor.parameters; - expect(parameters).toEqual([{ - __symbolic: 'reference', module: 'angular2/common', name: 'NgFor', line: 6, character: 29 - } as MetadataSymbolicExpression]); + expect(parameters).toEqual([ + {__symbolic: 'reference', module: 'angular2/common', name: 'NgFor', line: 6, character: 29} as + MetadataSymbolicExpression + ]); }); it('should be able to collect the value of an enum', () => { - const enumSource = program.getSourceFile('/exported-enum.ts') !; - const metadata = collector.getMetadata(enumSource) !; + const enumSource = program.getSourceFile('/exported-enum.ts')!; + const metadata = collector.getMetadata(enumSource)!; const someEnum: any = metadata.metadata['SomeEnum']; expect(someEnum).toEqual({A: 0, B: 1, C: 100, D: 101}); }); it('should ignore a non-export enum', () => { - const enumSource = program.getSourceFile('/private-enum.ts') !; - const metadata = collector.getMetadata(enumSource) !; + const enumSource = program.getSourceFile('/private-enum.ts')!; + const metadata = collector.getMetadata(enumSource)!; const publicEnum: any = metadata.metadata['PublicEnum']; const privateEnum: any = metadata.metadata['PrivateEnum']; expect(publicEnum).toEqual({a: 0, b: 1, c: 2}); @@ -467,8 +472,8 @@ describe('Collector', () => { }); it('should be able to collect enums initialized from consts', () => { - const enumSource = program.getSourceFile('/exported-enum.ts') !; - const metadata = collector.getMetadata(enumSource) !; + const enumSource = program.getSourceFile('/exported-enum.ts')!; + const metadata = collector.getMetadata(enumSource)!; const complexEnum: any = metadata.metadata['ComplexEnum']; expect(complexEnum).toEqual({ A: 0, @@ -486,8 +491,8 @@ describe('Collector', () => { }); it('should be able to collect a simple static method', () => { - const staticSource = program.getSourceFile('/static-method.ts') !; - const metadata = collector.getMetadata(staticSource) !; + const staticSource = program.getSourceFile('/static-method.ts')!; + const metadata = collector.getMetadata(staticSource)!; expect(metadata).toBeDefined(); const classData = metadata.metadata['MyModule']; expect(classData).toBeDefined(); @@ -504,43 +509,45 @@ describe('Collector', () => { }); it('should be able to collect a call to a static method', () => { - const staticSource = program.getSourceFile('/static-method-call.ts') !; - const metadata = collector.getMetadata(staticSource) !; + const staticSource = program.getSourceFile('/static-method-call.ts')!; + const metadata = collector.getMetadata(staticSource)!; expect(metadata).toBeDefined(); const classData = metadata.metadata['Foo']; expect(classData).toBeDefined(); - expect(classData.decorators).toEqual([{ - __symbolic: 'call', - expression: { - __symbolic: 'reference', - module: 'angular2/core', - name: 'Component', - line: 4, - character: 5 - }, - arguments: [{ - providers: { - __symbolic: 'call', - expression: { - __symbolic: 'select', + expect(classData.decorators).toEqual([ + { + __symbolic: 'call', + expression: { + __symbolic: 'reference', + module: 'angular2/core', + name: 'Component', + line: 4, + character: 5 + }, + arguments: [{ + providers: { + __symbolic: 'call', expression: { - __symbolic: 'reference', - module: './static-method', - name: 'MyModule', - line: 5, - character: 17 + __symbolic: 'select', + expression: { + __symbolic: 'reference', + module: './static-method', + name: 'MyModule', + line: 5, + character: 17 + }, + member: 'with' }, - member: 'with' - }, - arguments: ['a'] - } - }] - }] as any as MetadataSymbolicExpression[]); // TODO: Review use of `any` here (#19904) + arguments: ['a'] + } + }] + } + ] as any as MetadataSymbolicExpression[]); // TODO: Review use of `any` here (#19904) }); it('should be able to collect a static field', () => { - const staticSource = program.getSourceFile('/static-field.ts') !; - const metadata = collector.getMetadata(staticSource) !; + const staticSource = program.getSourceFile('/static-field.ts')!; + const metadata = collector.getMetadata(staticSource)!; expect(metadata).toBeDefined(); const classData = metadata.metadata['MyModule']; expect(classData).toBeDefined(); @@ -548,8 +555,8 @@ describe('Collector', () => { }); it('should ignore static type check members without a value', () => { - const typeCheckMembers = program.getSourceFile('/static-type-check-members.ts') !; - const metadata = collector.getMetadata(typeCheckMembers) !; + const typeCheckMembers = program.getSourceFile('/static-type-check-members.ts')!; + const metadata = collector.getMetadata(typeCheckMembers)!; const classData = metadata.metadata['MyDirective']; expect(classData.statics).toEqual({ foo: 'bar', @@ -560,42 +567,44 @@ describe('Collector', () => { }); it('should be able to collect a reference to a static field', () => { - const staticSource = program.getSourceFile('/static-field-reference.ts') !; - const metadata = collector.getMetadata(staticSource) !; + const staticSource = program.getSourceFile('/static-field-reference.ts')!; + const metadata = collector.getMetadata(staticSource)!; expect(metadata).toBeDefined(); const classData = metadata.metadata['Foo']; expect(classData).toBeDefined(); - expect(classData.decorators).toEqual([{ - __symbolic: 'call', - expression: { - __symbolic: 'reference', - module: 'angular2/core', - name: 'Component', - line: 4, - character: 5 - }, - arguments: [{ - providers: [{ - provide: 'a', - useValue: { - __symbolic: 'select', - expression: { - __symbolic: 'reference', - module: './static-field', - name: 'MyModule', - line: 5, - character: 45 - }, - member: 'VALUE' - } + expect(classData.decorators).toEqual([ + { + __symbolic: 'call', + expression: { + __symbolic: 'reference', + module: 'angular2/core', + name: 'Component', + line: 4, + character: 5 + }, + arguments: [{ + providers: [{ + provide: 'a', + useValue: { + __symbolic: 'select', + expression: { + __symbolic: 'reference', + module: './static-field', + name: 'MyModule', + line: 5, + character: 45 + }, + member: 'VALUE' + } + }] }] - }] - }] as any as MetadataSymbolicExpression[]); // TODO: Review use of `any` here (#19904) + } + ] as any as MetadataSymbolicExpression[]); // TODO: Review use of `any` here (#19904) }); it('should be able to collect a method with a conditional expression', () => { - const source = program.getSourceFile('/static-method-with-if.ts') !; - const metadata = collector.getMetadata(source) !; + const source = program.getSourceFile('/static-method-with-if.ts')!; + const metadata = collector.getMetadata(source)!; expect(metadata).toBeDefined(); const classData = metadata.metadata['MyModule']; expect(classData).toBeDefined(); @@ -619,8 +628,8 @@ describe('Collector', () => { }); it('should be able to collect a method with a default parameter', () => { - const source = program.getSourceFile('/static-method-with-default.ts') !; - const metadata = collector.getMetadata(source) !; + const source = program.getSourceFile('/static-method-with-default.ts')!; + const metadata = collector.getMetadata(source)!; expect(metadata).toBeDefined(); const classData = metadata.metadata['MyModule']; expect(classData).toBeDefined(); @@ -648,8 +657,8 @@ describe('Collector', () => { }); it('should be able to collect re-exported symbols', () => { - const source = program.getSourceFile('/re-exports.ts') !; - const metadata = collector.getMetadata(source) !; + const source = program.getSourceFile('/re-exports.ts')!; + const metadata = collector.getMetadata(source)!; expect(metadata.exports).toEqual([ {from: './static-field', export: ['MyModule']}, {from: './static-field-reference', export: [{name: 'Foo', as: 'OtherModule'}]}, @@ -658,14 +667,14 @@ describe('Collector', () => { }); it('should be able to collect a export as symbol', () => { - const source = program.getSourceFile('export-as.d.ts') !; - const metadata = collector.getMetadata(source) !; + const source = program.getSourceFile('export-as.d.ts')!; + const metadata = collector.getMetadata(source)!; expect(metadata.metadata).toEqual({SomeFunction: {__symbolic: 'function'}}); }); it('should be able to collect exports with no module specifier', () => { - const source = program.getSourceFile('/re-exports-2.ts') !; - const metadata = collector.getMetadata(source) !; + const source = program.getSourceFile('/re-exports-2.ts')!; + const metadata = collector.getMetadata(source)!; expect(metadata.metadata).toEqual({ MyClass: Object({__symbolic: 'class'}), OtherModule: { @@ -686,8 +695,8 @@ describe('Collector', () => { }); it('should collect an error symbol if collecting a reference to a non-exported symbol', () => { - const source = program.getSourceFile('/local-symbol-ref.ts') !; - const metadata = collector.getMetadata(source) !; + const source = program.getSourceFile('/local-symbol-ref.ts')!; + const metadata = collector.getMetadata(source)!; expect(metadata.metadata).toEqual({ REQUIRED_VALIDATOR: { __symbolic: 'error', @@ -714,8 +723,8 @@ describe('Collector', () => { }); it('should collect an error symbol if collecting a reference to a non-exported function', () => { - const source = program.getSourceFile('/local-function-ref.ts') !; - const metadata = collector.getMetadata(source) !; + const source = program.getSourceFile('/local-function-ref.ts')!; + const metadata = collector.getMetadata(source)!; expect(metadata.metadata).toEqual({ REQUIRED_VALIDATOR: { __symbolic: 'error', @@ -742,8 +751,8 @@ describe('Collector', () => { }); it('should collect an error for a simple function that references a local variable', () => { - const source = program.getSourceFile('/local-symbol-ref-func.ts') !; - const metadata = collector.getMetadata(source) !; + const source = program.getSourceFile('/local-symbol-ref-func.ts')!; + const metadata = collector.getMetadata(source)!; expect(metadata.metadata).toEqual({ foo: { __symbolic: 'function', @@ -760,8 +769,8 @@ describe('Collector', () => { }); it('should collect any for interface parameter reference', () => { - const source = program.getSourceFile('/interface-reference.ts') !; - const metadata = collector.getMetadata(source) !; + const source = program.getSourceFile('/interface-reference.ts')!; + const metadata = collector.getMetadata(source)!; expect((metadata.metadata['SomeClass'] as ClassMetadata).members).toEqual({ __ctor__: [{ __symbolic: 'constructor', @@ -787,11 +796,13 @@ describe('Collector', () => { return expect(metadata.metadata['value']); } - it('should be able to collect a raw interpolated string', - () => { e('`simple value`').toBe('simple value'); }); + it('should be able to collect a raw interpolated string', () => { + e('`simple value`').toBe('simple value'); + }); - it('should be able to interpolate a single value', - () => { e('`${foo}`', 'const foo = "foo value"').toBe('foo value'); }); + it('should be able to interpolate a single value', () => { + e('`${foo}`', 'const foo = "foo value"').toBe('foo value'); + }); it('should be able to interpolate multiple values', () => { e('`foo:${foo}, bar:${bar}, end`', 'const foo = "foo"; const bar = "bar";') @@ -894,30 +905,30 @@ describe('Collector', () => { toString(): string { return \`InjectionToken \${this._desc}\`; } } as any;`, ts.ScriptTarget.Latest, true); - const metadata = collector.getMetadata(source) !; + const metadata = collector.getMetadata(source)!; expect(metadata.metadata).toEqual({InjectionToken: {__symbolic: 'class'}}); }); describe('in strict mode', () => { it('should throw if an error symbol is collecting a reference to a non-exported symbol', () => { - const source = program.getSourceFile('/local-symbol-ref.ts') !; + const source = program.getSourceFile('/local-symbol-ref.ts')!; expect(() => collector.getMetadata(source, true)).toThrowError(/Reference to a local symbol/); }); it('should throw if an error if collecting a reference to a non-exported function', () => { - const source = program.getSourceFile('/local-function-ref.ts') !; + const source = program.getSourceFile('/local-function-ref.ts')!; expect(() => collector.getMetadata(source, true)) .toThrowError(/Reference to a non-exported function/); }); it('should throw for references to unexpected types', () => { - const unsupported2 = program.getSourceFile('/unsupported-2.ts') !; + const unsupported2 = program.getSourceFile('/unsupported-2.ts')!; expect(() => collector.getMetadata(unsupported2, true)) .toThrowError(/Reference to non-exported class/); }); it('should throw for errors in a static method', () => { - const unsupported3 = program.getSourceFile('/unsupported-3.ts') !; + const unsupported3 = program.getSourceFile('/unsupported-3.ts')!; expect(() => collector.getMetadata(unsupported3, true)) .toThrowError(/Reference to a non-exported class/); }); @@ -927,34 +938,39 @@ describe('Collector', () => { it('should not throw with a class with no name', () => { const fileName = '/invalid-class.ts'; override(fileName, 'export class'); - const invalidClass = program.getSourceFile(fileName) !; + const invalidClass = program.getSourceFile(fileName)!; expect(() => collector.getMetadata(invalidClass)).not.toThrow(); }); it('should not throw with a function with no name', () => { const fileName = '/invalid-function.ts'; override(fileName, 'export function'); - const invalidFunction = program.getSourceFile(fileName) !; + const invalidFunction = program.getSourceFile(fileName)!; expect(() => collector.getMetadata(invalidFunction)).not.toThrow(); }); }); - describe('inheritance', () => { - it('should record `extends` clauses for declared classes', () => { - const metadata = collector.getMetadata(program.getSourceFile('/class-inheritance.ts') !) !; - expect(metadata.metadata['DeclaredChildClass']) + describe( + 'inheritance', () => { + it('should record `extends` clauses for declared classes', + () => { + const metadata = + collector.getMetadata(program.getSourceFile('/class-inheritance.ts')!)!; + expect(metadata.metadata['DeclaredChildClass']) .toEqual({__symbolic: 'class', extends: {__symbolic: 'reference', name: 'ParentClass'}}); - }); + }); - it('should record `extends` clauses for classes in the same file', () => { - const metadata = collector.getMetadata(program.getSourceFile('/class-inheritance.ts') !) !; - expect(metadata.metadata['ChildClassSameFile']) + it('should record `extends` clauses for classes in the same file', + () => { + const metadata = + collector.getMetadata(program.getSourceFile('/class-inheritance.ts')!)!; + expect(metadata.metadata['ChildClassSameFile']) .toEqual({__symbolic: 'class', extends: {__symbolic: 'reference', name: 'ParentClass'}}); - }); + }); - it('should record `extends` clauses for classes in a different file', () => { - const metadata = collector.getMetadata(program.getSourceFile('/class-inheritance.ts') !) !; - expect(metadata.metadata['ChildClassOtherFile']).toEqual({ + it('should record `extends` clauses for classes in a different file', () => { + const metadata = collector.getMetadata(program.getSourceFile('/class-inheritance.ts')!)!; + expect(metadata.metadata['ChildClassOtherFile']).toEqual({ __symbolic: 'class', extends: { __symbolic: 'reference', @@ -964,29 +980,29 @@ describe('Collector', () => { character: 45, } }); - }); + }); - function expectClass(entry: MetadataEntry): entry is ClassMetadata { - const result = isClassMetadata(entry); - expect(result).toBeTruthy(); - return result; - } + function expectClass(entry: MetadataEntry): entry is ClassMetadata { + const result = isClassMetadata(entry); + expect(result).toBeTruthy(); + return result; + } - it('should collect the correct arity for a class', () => { - const metadata = collector.getMetadata(program.getSourceFile('/class-arity.ts') !) !; + it('should collect the correct arity for a class', () => { + const metadata = collector.getMetadata(program.getSourceFile('/class-arity.ts')!)!; - const zero = metadata.metadata['Zero']; - if (expectClass(zero)) expect(zero.arity).toBeUndefined(); - const one = metadata.metadata['One']; - if (expectClass(one)) expect(one.arity).toBe(1); - const two = metadata.metadata['Two']; - if (expectClass(two)) expect(two.arity).toBe(2); - const three = metadata.metadata['Three']; - if (expectClass(three)) expect(three.arity).toBe(3); - const nine = metadata.metadata['Nine']; - if (expectClass(nine)) expect(nine.arity).toBe(9); - }); - }); + const zero = metadata.metadata['Zero']; + if (expectClass(zero)) expect(zero.arity).toBeUndefined(); + const one = metadata.metadata['One']; + if (expectClass(one)) expect(one.arity).toBe(1); + const two = metadata.metadata['Two']; + if (expectClass(two)) expect(two.arity).toBe(2); + const three = metadata.metadata['Three']; + if (expectClass(three)) expect(three.arity).toBe(3); + const nine = metadata.metadata['Nine']; + if (expectClass(nine)) expect(nine.arity).toBe(9); + }); + }); describe('regression', () => { it('should be able to collect a short-hand property value', () => { @@ -1053,11 +1069,12 @@ describe('Collector', () => { expect((metadata.metadata.MyIf as any).statics.typeGuard) .not.toBeUndefined('typeGuard was not collected'); }); - }); describe('references', () => { - beforeEach(() => { collector = new MetadataCollector({quotedNames: true}); }); + beforeEach(() => { + collector = new MetadataCollector({quotedNames: true}); + }); it('should record a reference to an exported field of a useValue', () => { const metadata = collectSource(` @@ -1113,13 +1130,13 @@ describe('Collector', () => { } return value; }); - expect(metadata !.metadata['a']).toEqual({__symbolic: 'reference', name: lambdaTemp}); + expect(metadata!.metadata['a']).toEqual({__symbolic: 'reference', name: lambdaTemp}); }); it('should compose substitution functions', () => { const collector = new MetadataCollector({ - substituteExpression: (value, node) => isMetadataGlobalReferenceExpression(value) && - value.name == lambdaTemp ? + substituteExpression: (value, node) => + isMetadataGlobalReferenceExpression(value) && value.name == lambdaTemp ? {__symbolic: 'reference', name: value.name + '2'} : value }); @@ -1133,19 +1150,19 @@ describe('Collector', () => { } return value; }); - expect(metadata !.metadata['a']).toEqual({__symbolic: 'reference', name: lambdaTemp + '2'}); + expect(metadata!.metadata['a']).toEqual({__symbolic: 'reference', name: lambdaTemp + '2'}); }); }); function override(fileName: string, content: string) { host.overrideFile(fileName, content); host.addFile(fileName); - program = service.getProgram() !; + program = service.getProgram()!; } function collectSource(content: string): ModuleMetadata { const sourceFile = createSource(content); - return collector.getMetadata(sourceFile) !; + return collector.getMetadata(sourceFile)!; } }); diff --git a/packages/compiler-cli/test/metadata/evaluator_spec.ts b/packages/compiler-cli/test/metadata/evaluator_spec.ts index 6bd8f5167a..405ff74189 100644 --- a/packages/compiler-cli/test/metadata/evaluator_spec.ts +++ b/packages/compiler-cli/test/metadata/evaluator_spec.ts @@ -10,7 +10,7 @@ import * as ts from 'typescript'; import {Evaluator} from '../../src/metadata/evaluator'; import {Symbols} from '../../src/metadata/symbols'; -import {Directory, Host, expectNoDiagnostics, findVar, findVarInitializer} from './typescript.mocks'; +import {Directory, expectNoDiagnostics, findVar, findVarInitializer, Host} from './typescript.mocks'; describe('Evaluator', () => { const documentRegistry = ts.createDocumentRegistry(); @@ -27,7 +27,7 @@ describe('Evaluator', () => { 'newExpression.ts', 'errors.ts', 'declared.ts' ]); service = ts.createLanguageService(host, documentRegistry); - program = service.getProgram() !; + program = service.getProgram()!; typeChecker = program.getTypeChecker(); symbols = new Symbols(null as any as ts.SourceFile); evaluator = new Evaluator(symbols, new Map()); @@ -45,7 +45,7 @@ describe('Evaluator', () => { }); it('should be able to fold literal expressions', () => { - const consts = program.getSourceFile('consts.ts') !; + const consts = program.getSourceFile('consts.ts')!; expect(evaluator.isFoldable(findVarInitializer(consts, 'someName'))).toBeTruthy(); expect(evaluator.isFoldable(findVarInitializer(consts, 'someBool'))).toBeTruthy(); expect(evaluator.isFoldable(findVarInitializer(consts, 'one'))).toBeTruthy(); @@ -53,7 +53,7 @@ describe('Evaluator', () => { }); it('should be able to fold expressions with foldable references', () => { - const expressions = program.getSourceFile('expressions.ts') !; + const expressions = program.getSourceFile('expressions.ts')!; symbols.define('someName', 'some-name'); symbols.define('someBool', true); symbols.define('one', 1); @@ -67,7 +67,7 @@ describe('Evaluator', () => { }); it('should be able to evaluate literal expressions', () => { - const consts = program.getSourceFile('consts.ts') !; + const consts = program.getSourceFile('consts.ts')!; expect(evaluator.evaluateNode(findVarInitializer(consts, 'someName'))).toBe('some-name'); expect(evaluator.evaluateNode(findVarInitializer(consts, 'someBool'))).toBe(true); expect(evaluator.evaluateNode(findVarInitializer(consts, 'one'))).toBe(1); @@ -75,7 +75,7 @@ describe('Evaluator', () => { }); it('should be able to evaluate expressions', () => { - const expressions = program.getSourceFile('expressions.ts') !; + const expressions = program.getSourceFile('expressions.ts')!; symbols.define('someName', 'some-name'); symbols.define('someBool', true); symbols.define('one', 1); @@ -118,11 +118,10 @@ describe('Evaluator', () => { expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bShiftRight'))).toEqual(-1 >> 2); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bShiftRightU'))) .toEqual(-1 >>> 2); - }); it('should report recursive references as symbolic', () => { - const expressions = program.getSourceFile('expressions.ts') !; + const expressions = program.getSourceFile('expressions.ts')!; expect(evaluator.evaluateNode(findVarInitializer(expressions, 'recursiveA'))) .toEqual({__symbolic: 'reference', name: 'recursiveB'}); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'recursiveB'))) @@ -130,13 +129,13 @@ describe('Evaluator', () => { }); it('should correctly handle special cases for CONST_EXPR', () => { - const const_expr = program.getSourceFile('const_expr.ts') !; + const const_expr = program.getSourceFile('const_expr.ts')!; expect(evaluator.evaluateNode(findVarInitializer(const_expr, 'bTrue'))).toEqual(true); expect(evaluator.evaluateNode(findVarInitializer(const_expr, 'bFalse'))).toEqual(false); }); it('should resolve a forwardRef', () => { - const forwardRef = program.getSourceFile('forwardRef.ts') !; + const forwardRef = program.getSourceFile('forwardRef.ts')!; expect(evaluator.evaluateNode(findVarInitializer(forwardRef, 'bTrue'))).toEqual(true); expect(evaluator.evaluateNode(findVarInitializer(forwardRef, 'bFalse'))).toEqual(false); }); @@ -144,7 +143,7 @@ describe('Evaluator', () => { it('should return new expressions', () => { symbols.define('Value', {__symbolic: 'reference', module: './classes', name: 'Value'}); evaluator = new Evaluator(symbols, new Map()); - const newExpression = program.getSourceFile('newExpression.ts') !; + const newExpression = program.getSourceFile('newExpression.ts')!; expect(evaluator.evaluateNode(findVarInitializer(newExpression, 'someValue'))).toEqual({ __symbolic: 'new', expression: @@ -160,9 +159,9 @@ describe('Evaluator', () => { }); it('should support reference to a declared module type', () => { - const declared = program.getSourceFile('declared.ts') !; - const aDecl = findVar(declared, 'a') !; - expect(evaluator.evaluateNode(aDecl.type !)).toEqual({ + const declared = program.getSourceFile('declared.ts')!; + const aDecl = findVar(declared, 'a')!; + expect(evaluator.evaluateNode(aDecl.type!)).toEqual({ __symbolic: 'select', expression: {__symbolic: 'reference', name: 'Foo'}, member: 'A' @@ -170,28 +169,28 @@ describe('Evaluator', () => { }); it('should return errors for unsupported expressions', () => { - const errors = program.getSourceFile('errors.ts') !; - const fDecl = findVar(errors, 'f') !; - expect(evaluator.evaluateNode(fDecl.initializer !)) + const errors = program.getSourceFile('errors.ts')!; + const fDecl = findVar(errors, 'f')!; + expect(evaluator.evaluateNode(fDecl.initializer!)) .toEqual({__symbolic: 'error', message: 'Lambda not supported', line: 1, character: 12}); - const eDecl = findVar(errors, 'e') !; - expect(evaluator.evaluateNode(eDecl.type !)).toEqual({ + const eDecl = findVar(errors, 'e')!; + expect(evaluator.evaluateNode(eDecl.type!)).toEqual({ __symbolic: 'error', message: 'Could not resolve type', line: 2, character: 11, context: {typeName: 'NotFound'} }); - const sDecl = findVar(errors, 's') !; - expect(evaluator.evaluateNode(sDecl.initializer !)).toEqual({ + const sDecl = findVar(errors, 's')!; + expect(evaluator.evaluateNode(sDecl.initializer!)).toEqual({ __symbolic: 'error', message: 'Name expected', line: 3, character: 14, context: {received: '1'} }); - const tDecl = findVar(errors, 't') !; - expect(evaluator.evaluateNode(tDecl.initializer !)).toEqual({ + const tDecl = findVar(errors, 't')!; + expect(evaluator.evaluateNode(tDecl.initializer!)).toEqual({ __symbolic: 'error', message: 'Expression form not supported', line: 4, @@ -200,16 +199,16 @@ describe('Evaluator', () => { }); it('should be able to fold an array spread', () => { - const expressions = program.getSourceFile('expressions.ts') !; + const expressions = program.getSourceFile('expressions.ts')!; symbols.define('arr', [1, 2, 3, 4]); - const arrSpread = findVar(expressions, 'arrSpread') !; - expect(evaluator.evaluateNode(arrSpread.initializer !)).toEqual([0, 1, 2, 3, 4, 5]); + const arrSpread = findVar(expressions, 'arrSpread')!; + expect(evaluator.evaluateNode(arrSpread.initializer!)).toEqual([0, 1, 2, 3, 4, 5]); }); it('should be able to produce a spread expression', () => { - const expressions = program.getSourceFile('expressions.ts') !; - const arrSpreadRef = findVar(expressions, 'arrSpreadRef') !; - expect(evaluator.evaluateNode(arrSpreadRef.initializer !)).toEqual([ + const expressions = program.getSourceFile('expressions.ts')!; + const arrSpreadRef = findVar(expressions, 'arrSpreadRef')!; + expect(evaluator.evaluateNode(arrSpreadRef.initializer!)).toEqual([ 0, {__symbolic: 'spread', expression: {__symbolic: 'reference', name: 'arrImport'}}, 5 ]); }); @@ -218,8 +217,8 @@ describe('Evaluator', () => { const source = sourceFileOf(` export var a = new f; `); - const expr = findVar(source, 'a') !; - expect(evaluator.evaluateNode(expr.initializer !)) + const expr = findVar(source, 'a')!; + expect(evaluator.evaluateNode(expr.initializer!)) .toEqual({__symbolic: 'new', expression: {__symbolic: 'reference', name: 'f'}}); }); @@ -244,7 +243,7 @@ describe('Evaluator', () => { export var a = () => b; `); const expr = findVar(source, 'a'); - expect(evaluator.evaluateNode(expr !.initializer !)) + expect(evaluator.evaluateNode(expr!.initializer!)) .toEqual({__symbolic: 'reference', name: lambdaTemp}); }); @@ -256,7 +255,7 @@ describe('Evaluator', () => { ]; `); const expr = findVar(source, 'a'); - expect(evaluator.evaluateNode(expr !.initializer !)).toEqual([ + expect(evaluator.evaluateNode(expr!.initializer!)).toEqual([ {provide: 'someValue', useFactory: {__symbolic: 'reference', name: lambdaTemp}} ]); }); diff --git a/packages/compiler-cli/test/metadata/symbols_spec.ts b/packages/compiler-cli/test/metadata/symbols_spec.ts index 8ea2e70edb..37c5a693fd 100644 --- a/packages/compiler-cli/test/metadata/symbols_spec.ts +++ b/packages/compiler-cli/test/metadata/symbols_spec.ts @@ -11,7 +11,7 @@ import * as ts from 'typescript'; import {isMetadataGlobalReferenceExpression} from '../../src/metadata/schema'; import {Symbols} from '../../src/metadata/symbols'; -import {Directory, Host, expectNoDiagnostics} from './typescript.mocks'; +import {Directory, expectNoDiagnostics, Host} from './typescript.mocks'; describe('Symbols', () => { let symbols: Symbols; @@ -42,9 +42,9 @@ describe('Symbols', () => { beforeEach(() => { host = new Host(FILES, ['consts.ts', 'expressions.ts', 'imports.ts']); service = ts.createLanguageService(host); - program = service.getProgram() !; - expressions = program.getSourceFile('expressions.ts') !; - imports = program.getSourceFile('imports.ts') !; + program = service.getProgram()!; + expressions = program.getSourceFile('expressions.ts')!; + imports = program.getSourceFile('imports.ts')!; }); it('should not have syntax errors in the test sources', () => { @@ -111,7 +111,7 @@ describe('Symbols', () => { } return false; }; - ts.forEachChild(core !, visit); + ts.forEachChild(core!, visit); }); }); diff --git a/packages/compiler-cli/test/metadata/typescript.mocks.ts b/packages/compiler-cli/test/metadata/typescript.mocks.ts index 44d3bb39fb..71d214406d 100644 --- a/packages/compiler-cli/test/metadata/typescript.mocks.ts +++ b/packages/compiler-cli/test/metadata/typescript.mocks.ts @@ -10,7 +10,9 @@ import * as fs from 'fs'; import * as path from 'path'; import * as ts from 'typescript'; -export interface Directory { [name: string]: (Directory|string); } +export interface Directory { + [name: string]: (Directory|string); +} export class Host implements ts.LanguageServiceHost { private overrides = new Map(); @@ -26,20 +28,30 @@ export class Host implements ts.LanguageServiceHost { }; } - getScriptFileNames(): string[] { return this.scripts; } + getScriptFileNames(): string[] { + return this.scripts; + } - getScriptVersion(fileName: string): string { return this.version.toString(); } + getScriptVersion(fileName: string): string { + return this.version.toString(); + } getScriptSnapshot(fileName: string): ts.IScriptSnapshot|undefined { const content = this.getFileContent(fileName); if (content) return ts.ScriptSnapshot.fromString(content); } - fileExists(fileName: string): boolean { return this.getFileContent(fileName) != null; } + fileExists(fileName: string): boolean { + return this.getFileContent(fileName) != null; + } - getCurrentDirectory(): string { return '/'; } + getCurrentDirectory(): string { + return '/'; + } - getDefaultLibFileName(options: ts.CompilerOptions): string { return 'lib.d.ts'; } + getDefaultLibFileName(options: ts.CompilerOptions): string { + return 'lib.d.ts'; + } overrideFile(fileName: string, content: string) { this.overrides.set(fileName, content); @@ -81,24 +93,52 @@ export function open(directory: Directory, fileName: string): Directory|string|u export class MockNode implements ts.Node { decorators?: ts.NodeArray; modifiers?: ts.NodeArray; - parent !: ts.Node; + parent!: ts.Node; constructor( public kind: ts.SyntaxKind = ts.SyntaxKind.Identifier, public flags: ts.NodeFlags = 0, public pos: number = 0, public end: number = 0) {} - getSourceFile(): ts.SourceFile { return null as any as ts.SourceFile; } - getChildCount(sourceFile?: ts.SourceFile): number { return 0; } - getChildAt(index: number, sourceFile?: ts.SourceFile): ts.Node { return null as any as ts.Node; } - getChildren(sourceFile?: ts.SourceFile): ts.Node[] { return []; } - getStart(sourceFile?: ts.SourceFile): number { return 0; } - getFullStart(): number { return 0; } - getEnd(): number { return 0; } - getWidth(sourceFile?: ts.SourceFile): number { return 0; } - getFullWidth(): number { return 0; } - getLeadingTriviaWidth(sourceFile?: ts.SourceFile): number { return 0; } - getFullText(sourceFile?: ts.SourceFile): string { return ''; } - getText(sourceFile?: ts.SourceFile): string { return ''; } - getFirstToken(sourceFile?: ts.SourceFile): ts.Node { return null as any as ts.Node; } - getLastToken(sourceFile?: ts.SourceFile): ts.Node { return null as any as ts.Node; } + getSourceFile(): ts.SourceFile { + return null as any as ts.SourceFile; + } + getChildCount(sourceFile?: ts.SourceFile): number { + return 0; + } + getChildAt(index: number, sourceFile?: ts.SourceFile): ts.Node { + return null as any as ts.Node; + } + getChildren(sourceFile?: ts.SourceFile): ts.Node[] { + return []; + } + getStart(sourceFile?: ts.SourceFile): number { + return 0; + } + getFullStart(): number { + return 0; + } + getEnd(): number { + return 0; + } + getWidth(sourceFile?: ts.SourceFile): number { + return 0; + } + getFullWidth(): number { + return 0; + } + getLeadingTriviaWidth(sourceFile?: ts.SourceFile): number { + return 0; + } + getFullText(sourceFile?: ts.SourceFile): string { + return ''; + } + getText(sourceFile?: ts.SourceFile): string { + return ''; + } + getFirstToken(sourceFile?: ts.SourceFile): ts.Node { + return null as any as ts.Node; + } + getLastToken(sourceFile?: ts.SourceFile): ts.Node { + return null as any as ts.Node; + } forEachChild( cbNode: (node: ts.Node) => T | undefined, cbNodeArray?: (nodes: ts.NodeArray) => T | undefined): T|undefined { @@ -111,10 +151,10 @@ export class MockIdentifier extends MockNode implements ts.Identifier { isInJSDocNamespace?: boolean; decorators?: ts.NodeArray; modifiers?: ts.NodeArray; - parent !: ts.Node; + parent!: ts.Node; public text: string; // TODO(issue/24571): remove '!'. - public escapedText !: ts.__String; + public escapedText!: ts.__String; // tslint:disable public _declarationBrand: any; public _primaryExpressionBrand: any; @@ -135,7 +175,7 @@ export class MockIdentifier extends MockNode implements ts.Identifier { } export class MockVariableDeclaration extends MockNode implements ts.VariableDeclaration { - parent !: ts.VariableDeclarationList | ts.CatchClause; + parent!: ts.VariableDeclarationList|ts.CatchClause; exclamationToken?: ts.Token; type?: ts.TypeNode; initializer?: ts.Expression; @@ -151,32 +191,46 @@ export class MockVariableDeclaration extends MockNode implements ts.VariableDecl super(kind, flags, pos, end); } - static of (name: string): MockVariableDeclaration { + static of(name: string): MockVariableDeclaration { return new MockVariableDeclaration(new MockIdentifier(name)); } } export class MockSymbol implements ts.Symbol { - declarations !: ts.Declaration[]; - valueDeclaration !: ts.Declaration; + declarations!: ts.Declaration[]; + valueDeclaration!: ts.Declaration; members?: ts.UnderscoreEscapedMap; exports?: ts.UnderscoreEscapedMap; globalExports?: ts.UnderscoreEscapedMap; // TODO(issue/24571): remove '!'. - public escapedName !: ts.__String; + public escapedName!: ts.__String; constructor( public name: string, private node: ts.Declaration = MockVariableDeclaration.of(name), public flags: ts.SymbolFlags = 0) {} - getFlags(): ts.SymbolFlags { return this.flags; } - getName(): string { return this.name; } - getEscapedName(): ts.__String { return this.escapedName; } - getDeclarations(): ts.Declaration[] { return [this.node]; } - getDocumentationComment(): ts.SymbolDisplayPart[] { return []; } + getFlags(): ts.SymbolFlags { + return this.flags; + } + getName(): string { + return this.name; + } + getEscapedName(): ts.__String { + return this.escapedName; + } + getDeclarations(): ts.Declaration[] { + return [this.node]; + } + getDocumentationComment(): ts.SymbolDisplayPart[] { + return []; + } // TODO(vicb): removed in TS 2.2 - getJsDocTags(): any[] { return []; } + getJsDocTags(): any[] { + return []; + } - static of (name: string): MockSymbol { return new MockSymbol(name); } + static of(name: string): MockSymbol { + return new MockSymbol(name); + } } export function expectNoDiagnostics(diagnostics: ts.Diagnostic[]) { @@ -219,14 +273,14 @@ export function findVar(sourceFile: ts.SourceFile, name: string): ts.VariableDec export function findVarInitializer(sourceFile: ts.SourceFile, name: string): ts.Expression { const v = findVar(sourceFile, name); expect(v && v.initializer).toBeDefined(); - return v !.initializer !; + return v!.initializer!; } export function isClass(node: ts.Node): node is ts.ClassDeclaration { return node.kind === ts.SyntaxKind.ClassDeclaration; } -export function isNamed(node: ts.Node | undefined, name: string): node is ts.Identifier { +export function isNamed(node: ts.Node|undefined, name: string): node is ts.Identifier { return !!node && node.kind === ts.SyntaxKind.Identifier && (node).text === name; } diff --git a/packages/compiler-cli/test/mocks.ts b/packages/compiler-cli/test/mocks.ts index a1ac68edd5..7d8d083d3e 100644 --- a/packages/compiler-cli/test/mocks.ts +++ b/packages/compiler-cli/test/mocks.ts @@ -8,16 +8,22 @@ import * as ts from 'typescript'; -export type Entry = string | Directory; +export type Entry = string|Directory; -export interface Directory { [name: string]: Entry; } +export interface Directory { + [name: string]: Entry; +} export class MockAotContext { private files: Entry[]; - constructor(public currentDirectory: string, ...files: Entry[]) { this.files = files; } + constructor(public currentDirectory: string, ...files: Entry[]) { + this.files = files; + } - fileExists(fileName: string): boolean { return typeof this.getEntry(fileName) === 'string'; } + fileExists(fileName: string): boolean { + return typeof this.getEntry(fileName) === 'string'; + } directoryExists(path: string): boolean { return path === this.currentDirectory || typeof this.getEntry(path) === 'object'; @@ -28,7 +34,7 @@ export class MockAotContext { if (typeof data === 'string') { return data; } - return undefined !; + return undefined!; } readResource(fileName: string): Promise { @@ -41,14 +47,16 @@ export class MockAotContext { writeFile(fileName: string, data: string): void { const parts = fileName.split('/'); - const name = parts.pop() !; + const name = parts.pop()!; const entry = this.getEntry(parts); if (entry && typeof entry !== 'string') { entry[name] = data; } } - assumeFileExists(fileName: string): void { this.writeFile(fileName, ''); } + assumeFileExists(fileName: string): void { + this.writeFile(fileName, ''); + } getEntry(fileName: string|string[]): Entry|undefined { let parts = typeof fileName === 'string' ? fileName.split('/') : fileName; @@ -69,7 +77,9 @@ export class MockAotContext { } } - override(files: Entry) { return new MockAotContext(this.currentDirectory, files, ...this.files); } + override(files: Entry) { + return new MockAotContext(this.currentDirectory, files, ...this.files); + } } function first(a: T[], cb: (value: T) => T | undefined): T|undefined { @@ -82,7 +92,7 @@ function first(a: T[], cb: (value: T) => T | undefined): T|undefined { function getEntryFromFiles(parts: string[], files: Entry) { let current = files; while (parts.length) { - const part = parts.shift() !; + const part = parts.shift()!; if (typeof current === 'string') { return undefined; } @@ -98,7 +108,7 @@ function getEntryFromFiles(parts: string[], files: Entry) { function normalize(parts: string[]): string[] { const result: string[] = []; while (parts.length) { - const part = parts.shift() !; + const part = parts.shift()!; switch (part) { case '.': break; @@ -115,9 +125,13 @@ function normalize(parts: string[]): string[] { export class MockCompilerHost implements ts.CompilerHost { constructor(private context: MockAotContext) {} - fileExists(fileName: string): boolean { return this.context.fileExists(fileName); } + fileExists(fileName: string): boolean { + return this.context.fileExists(fileName); + } - readFile(fileName: string): string { return this.context.readFile(fileName); } + readFile(fileName: string): string { + return this.context.readFile(fileName); + } directoryExists(directoryName: string): boolean { return this.context.directoryExists(directoryName); @@ -130,7 +144,7 @@ export class MockCompilerHost implements ts.CompilerHost { if (sourceText != null) { return ts.createSourceFile(fileName, sourceText, languageVersion); } else { - return undefined !; + return undefined!; } } @@ -138,15 +152,28 @@ export class MockCompilerHost implements ts.CompilerHost { return ts.getDefaultLibFileName(options); } - writeFile: ts.WriteFileCallback = (fileName, text) => { this.context.writeFile(fileName, text); }; + writeFile: ts.WriteFileCallback = + (fileName, text) => { + this.context.writeFile(fileName, text); + } - getCurrentDirectory(): string { return this.context.currentDirectory; } + getCurrentDirectory(): string { + return this.context.currentDirectory; + } - getCanonicalFileName(fileName: string): string { return fileName; } + getCanonicalFileName(fileName: string): string { + return fileName; + } - useCaseSensitiveFileNames(): boolean { return false; } + useCaseSensitiveFileNames(): boolean { + return false; + } - getNewLine(): string { return '\n'; } + getNewLine(): string { + return '\n'; + } - getDirectories(path: string): string[] { return this.context.getDirectories(path); } + getDirectories(path: string): string[] { + return this.context.getDirectories(path); + } } diff --git a/packages/compiler-cli/test/ngtsc/component_indexing_spec.ts b/packages/compiler-cli/test/ngtsc/component_indexing_spec.ts index ff05d00593..a1f9e9a989 100644 --- a/packages/compiler-cli/test/ngtsc/component_indexing_spec.ts +++ b/packages/compiler-cli/test/ngtsc/component_indexing_spec.ts @@ -14,7 +14,7 @@ import {NgtscTestEnvironment} from './env'; runInEachFileSystem(() => { describe('ngtsc component indexing', () => { - let env !: NgtscTestEnvironment; + let env!: NgtscTestEnvironment; let testSourceFile: AbsoluteFsPath; let testTemplateFile: AbsoluteFsPath; @@ -177,10 +177,10 @@ runInEachFileSystem(() => { expect(testComp).toBeDefined(); expect(testImportComp).toBeDefined(); - expect(testComp !.template.usedComponents.size).toBe(0); - expect(testImportComp !.template.usedComponents.size).toBe(1); + expect(testComp!.template.usedComponents.size).toBe(0); + expect(testImportComp!.template.usedComponents.size).toBe(1); - const [usedComp] = Array.from(testImportComp !.template.usedComponents); + const [usedComp] = Array.from(testImportComp!.template.usedComponents); expect(indexed.get(usedComp)).toEqual(testComp); }); }); diff --git a/packages/compiler-cli/test/ngtsc/env.ts b/packages/compiler-cli/test/ngtsc/env.ts index d8c63fb1fa..1d5a2deb6a 100644 --- a/packages/compiler-cli/test/ngtsc/env.ts +++ b/packages/compiler-cli/test/ngtsc/env.ts @@ -6,13 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import {CustomTransformers, Program, defaultGatherDiagnostics} from '@angular/compiler-cli'; +import {CustomTransformers, defaultGatherDiagnostics, Program} from '@angular/compiler-cli'; import * as api from '@angular/compiler-cli/src/transformers/api'; import * as ts from 'typescript'; import {createCompilerHost, createProgram} from '../../index'; import {main, mainDiagnosticsForTest, readNgcCommandLineAndConfiguration} from '../../src/main'; -import {AbsoluteFsPath, FileSystem, NgtscCompilerHost, absoluteFrom, getFileSystem} from '../../src/ngtsc/file_system'; +import {absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, NgtscCompilerHost} from '../../src/ngtsc/file_system'; import {Folder, MockFileSystem} from '../../src/ngtsc/file_system/testing'; import {IndexedComponent} from '../../src/ngtsc/indexer'; import {NgtscProgram} from '../../src/ngtsc/program'; @@ -115,7 +115,7 @@ export class NgtscTestEnvironment { if (this.multiCompileHostExt === null) { throw new Error(`Not tracking written files - call enableMultipleCompilations()`); } - this.changedResources !.clear(); + this.changedResources!.clear(); this.multiCompileHostExt.flushWrittenFileTracking(); } @@ -123,7 +123,9 @@ export class NgtscTestEnvironment { * Older versions of the CLI do not provide the `CompilerHost.getModifiedResourceFiles()` method. * This results in the `changedResources` set being `null`. */ - simulateLegacyCLICompilerHost() { this.changedResources = null; } + simulateLegacyCLICompilerHost() { + this.changedResources = null; + } getFilesWrittenSinceLastFlush(): Set { if (this.multiCompileHostExt === null) { @@ -142,7 +144,7 @@ export class NgtscTestEnvironment { const absFilePath = this.fs.resolve(this.basePath, fileName); if (this.multiCompileHostExt !== null) { this.multiCompileHostExt.invalidate(absFilePath); - this.changedResources !.add(absFilePath); + this.changedResources!.add(absFilePath); } this.fs.ensureDir(this.fs.dirname(absFilePath)); this.fs.writeFile(absFilePath, content); @@ -156,8 +158,7 @@ export class NgtscTestEnvironment { this.multiCompileHostExt.invalidate(absFilePath); } - tsconfig(extraOpts: {[key: string]: string | boolean | null} = {}, extraRootDirs?: string[]): - void { + tsconfig(extraOpts: {[key: string]: string|boolean|null} = {}, extraRootDirs?: string[]): void { const tsconfig: {[key: string]: any} = { extends: './tsconfig-base.json', angularCompilerOptions: {...extraOpts, enableIvy: true}, @@ -179,7 +180,7 @@ export class NgtscTestEnvironment { */ driveMain(customTransformers?: CustomTransformers): void { const errorSpy = jasmine.createSpy('consoleError').and.callFake(console.error); - let reuseProgram: {program: Program | undefined}|undefined = undefined; + let reuseProgram: {program: Program|undefined}|undefined = undefined; if (this.multiCompileHostExt !== null) { reuseProgram = { program: this.oldProgram || undefined, @@ -191,7 +192,7 @@ export class NgtscTestEnvironment { expect(errorSpy).not.toHaveBeenCalled(); expect(exitCode).toBe(0); if (this.multiCompileHostExt !== null) { - this.oldProgram = reuseProgram !.program !; + this.oldProgram = reuseProgram!.program!; } } @@ -200,7 +201,7 @@ export class NgtscTestEnvironment { */ driveDiagnostics(): ReadonlyArray { // ngtsc only produces ts.Diagnostic messages. - let reuseProgram: {program: Program | undefined}|undefined = undefined; + let reuseProgram: {program: Program|undefined}|undefined = undefined; if (this.multiCompileHostExt !== null) { reuseProgram = { program: this.oldProgram || undefined, @@ -212,7 +213,7 @@ export class NgtscTestEnvironment { if (this.multiCompileHostExt !== null) { - this.oldProgram = reuseProgram !.program !; + this.oldProgram = reuseProgram!.program!; } // In ngtsc, only `ts.Diagnostic`s are produced. @@ -245,7 +246,7 @@ export class NgtscTestEnvironment { } class AugmentedCompilerHost extends NgtscCompilerHost { - delegate !: ts.CompilerHost; + delegate!: ts.CompilerHost; } const ROOT_PREFIX = 'root/'; @@ -283,7 +284,7 @@ class MultiCompileHostExt extends AugmentedCompilerHost implements Partial void, shouldCreateNewSourceFile?: boolean): ts.SourceFile|undefined { if (this.cache.has(fileName)) { - return this.cache.get(fileName) !; + return this.cache.get(fileName)!; } const sf = super.getSourceFile(fileName, languageVersion); if (sf !== undefined) { @@ -292,7 +293,9 @@ class MultiCompileHostExt extends AugmentedCompilerHost implements Partial { return this.writtenFiles; } + getFilesWrittenSinceLastFlush(): Set { + return this.writtenFiles; + } - invalidate(fileName: string): void { this.cache.delete(fileName); } + invalidate(fileName: string): void { + this.cache.delete(fileName); + } } class ResourceLoadingCompileHost extends AugmentedCompilerHost implements api.CompilerHost { @@ -323,7 +330,7 @@ function makeWrapHost(wrapped: AugmentedCompilerHost): (host: ts.CompilerHost) = return new Proxy(delegate, { get: (target: ts.CompilerHost, name: string): any => { if ((wrapped as any)[name] !== undefined) { - return (wrapped as any)[name] !.bind(wrapped); + return (wrapped as any)[name]!.bind(wrapped); } return (target as any)[name]; } diff --git a/packages/compiler-cli/test/ngtsc/fake_core/index.ts b/packages/compiler-cli/test/ngtsc/fake_core/index.ts index 17ae37d6bc..b1c7451d13 100644 --- a/packages/compiler-cli/test/ngtsc/fake_core/index.ts +++ b/packages/compiler-cli/test/ngtsc/fake_core/index.ts @@ -8,19 +8,19 @@ interface FnWithArg { (...args: any[]): T; - new (...args: any[]): T; + new(...args: any[]): T; } function callableClassDecorator(): FnWithArg<(clazz: any) => any> { - return null !; + return null!; } function callableParamDecorator(): FnWithArg<(a: any, b: any, c: any) => void> { - return null !; + return null!; } function callablePropDecorator(): FnWithArg<(a: any, b: any) => any> { - return null !; + return null!; } export const Component = callableClassDecorator(); @@ -66,7 +66,9 @@ export function forwardRef(fn: () => T): T { return fn(); } -export interface SimpleChanges { [propName: string]: any; } +export interface SimpleChanges { + [propName: string]: any; +} export type ɵɵNgModuleDefWithMeta = any; export type ɵɵDirectiveDefWithMeta< @@ -89,11 +91,15 @@ export const CUSTOM_ELEMENTS_SCHEMA: any = false; export const NO_ERRORS_SCHEMA: any = false; export class EventEmitter { - subscribe(generatorOrNext?: any, error?: any, complete?: any): unknown { return null; } + subscribe(generatorOrNext?: any, error?: any, complete?: any): unknown { + return null; + } } -export interface QueryList/* implements Iterable */ { [Symbol.iterator]: () => Iterator; } +export interface QueryList/* implements Iterable */ { + [Symbol.iterator]: () => Iterator; +} -export type NgIterable = Array| Iterable; +export type NgIterable = Array|Iterable; export class NgZone {} diff --git a/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts b/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts index 16a51005c3..c850b74c7f 100644 --- a/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts +++ b/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts @@ -16,7 +16,7 @@ const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc incremental compilation with errors', () => { - let env !: NgtscTestEnvironment; + let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); @@ -66,7 +66,7 @@ runInEachFileSystem(() => { `); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); - expect(diags[0].file !.fileName).toBe(_('/other.ts')); + expect(diags[0].file!.fileName).toBe(_('/other.ts')); expectToHaveWritten([]); // Remove the error. /other.js should now be emitted again. @@ -92,7 +92,7 @@ runInEachFileSystem(() => { const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); - expect(diags[0].file !.fileName).toBe(_('/other.ts')); + expect(diags[0].file!.fileName).toBe(_('/other.ts')); expectToHaveWritten([]); // Remove the error. All files should be emitted. @@ -128,7 +128,7 @@ runInEachFileSystem(() => { const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); - expect(diags[0].file !.fileName).toBe(_('/other.ts')); + expect(diags[0].file!.fileName).toBe(_('/other.ts')); expectToHaveWritten([]); // Remove the error. All files should be emitted. @@ -175,7 +175,7 @@ runInEachFileSystem(() => { const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); - expect(diags[0].file !.fileName).toBe(_('/other.ts')); + expect(diags[0].file!.fileName).toBe(_('/other.ts')); expectToHaveWritten([]); // Remove the error. All files should be emitted. diff --git a/packages/compiler-cli/test/ngtsc/incremental_spec.ts b/packages/compiler-cli/test/ngtsc/incremental_spec.ts index f8842baae6..6cf7f99343 100644 --- a/packages/compiler-cli/test/ngtsc/incremental_spec.ts +++ b/packages/compiler-cli/test/ngtsc/incremental_spec.ts @@ -15,7 +15,7 @@ const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc incremental compilation', () => { - let env !: NgtscTestEnvironment; + let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); diff --git a/packages/compiler-cli/test/ngtsc/modulewithproviders_spec.ts b/packages/compiler-cli/test/ngtsc/modulewithproviders_spec.ts index 3035661e28..59663f0f5a 100644 --- a/packages/compiler-cli/test/ngtsc/modulewithproviders_spec.ts +++ b/packages/compiler-cli/test/ngtsc/modulewithproviders_spec.ts @@ -17,7 +17,7 @@ const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ModuleWithProviders generic type transform', () => { - let env !: NgtscTestEnvironment; + let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); diff --git a/packages/compiler-cli/test/ngtsc/monorepo_spec.ts b/packages/compiler-cli/test/ngtsc/monorepo_spec.ts index ac90576641..f6b0666a9b 100644 --- a/packages/compiler-cli/test/ngtsc/monorepo_spec.ts +++ b/packages/compiler-cli/test/ngtsc/monorepo_spec.ts @@ -16,7 +16,7 @@ const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('monorepos', () => { - let env !: NgtscTestEnvironment; + let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles, absoluteFrom('/app')); diff --git a/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts b/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts index 6131de87df..288d9c4c04 100644 --- a/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts +++ b/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts @@ -38,12 +38,12 @@ const setClassMetadataRegExp = (expectedType: string): RegExp => const testFiles = loadStandardTestFiles(); function getDiagnosticSourceCode(diag: ts.Diagnostic): string { - return diag.file !.text.substr(diag.start !, diag.length !); + return diag.file!.text.substr(diag.start!, diag.length!); } runInEachFileSystem(os => { describe('ngtsc behavioral tests', () => { - let env !: NgtscTestEnvironment; + let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); @@ -369,7 +369,6 @@ runInEachFileSystem(os => { // that start with `C:`. if (os !== 'Windows' || platform() === 'win32') { describe('when closure annotations are requested', () => { - it('should add @nocollapse to static fields', () => { env.tsconfig({ 'annotateForClosureCompiler': true, @@ -531,7 +530,6 @@ runInEachFileSystem(os => { verifyOutput(env.getContents('test.js')); }); }); - }); } @@ -1714,7 +1712,8 @@ runInEachFileSystem(os => { }); ['ContentChild', 'ContentChildren'].forEach(decorator => { - it(`should throw if \`descendants\` field of @${decorator}'s options argument has wrong type`, + it(`should throw if \`descendants\` field of @${ + decorator}'s options argument has wrong type`, () => { env.tsconfig({}); env.write('test.ts', ` @@ -2148,7 +2147,6 @@ runInEachFileSystem(os => { expect(jsContents) .toContain('Test.ɵfac = function Test_Factory(t) { i0.ɵɵinvalidFactory()'); }); - }); }); @@ -3466,7 +3464,9 @@ runInEachFileSystem(os => { }); describe('ngfactory shims', () => { - beforeEach(() => { env.tsconfig({'generateNgFactoryShims': true}); }); + beforeEach(() => { + env.tsconfig({'generateNgFactoryShims': true}); + }); it('should generate correct type annotation for NgModuleFactory calls in ngfactories', () => { env.write('test.ts', ` @@ -3568,7 +3568,9 @@ runInEachFileSystem(os => { describe('ngsummary shim generation', () => { - beforeEach(() => { env.tsconfig({'generateNgSummaryShims': true}); }); + beforeEach(() => { + env.tsconfig({'generateNgSummaryShims': true}); + }); it('should generate a summary stub for decorated classes in the input file only', () => { env.write('test.ts', ` @@ -3792,7 +3794,6 @@ runInEachFileSystem(os => { }); it('should use imported types in setClassMetadata if they can be represented as values', () => { - env.write(`types.ts`, ` export class MyTypeA {} export class MyTypeB {} @@ -3824,7 +3825,6 @@ runInEachFileSystem(os => { it('should use imported types in setClassMetadata if they can be represented as values and imported as `* as foo`', () => { - env.write(`types.ts`, ` export class MyTypeA {} export class MyTypeB {} @@ -3855,7 +3855,6 @@ runInEachFileSystem(os => { }); it('should use default-imported types if they can be represented as values', () => { - env.write(`types.ts`, ` export default class Default {} export class Other {} @@ -3883,7 +3882,6 @@ runInEachFileSystem(os => { it('should use `undefined` in setClassMetadata if types can\'t be represented as values', () => { - env.write(`types.ts`, ` export type MyType = Map; `); @@ -4059,7 +4057,6 @@ runInEachFileSystem(os => { it('should not generate an error when a local ref is unresolved' + ' (outside of template type-checking)', () => { - env.write('test.ts', ` import {Component} from '@angular/core'; @@ -4347,7 +4344,7 @@ runInEachFileSystem(os => { } }); - it('should throw if @Component is missing a template', async() => { + it('should throw if @Component is missing a template', async () => { env.write('test.ts', ` import {Component} from '@angular/core'; @@ -4359,10 +4356,10 @@ runInEachFileSystem(os => { const diags = await driveDiagnostics(); expect(diags[0].messageText).toBe('component is missing a template'); - expect(diags[0].file !.fileName).toBe(absoluteFrom('/test.ts')); + expect(diags[0].file!.fileName).toBe(absoluteFrom('/test.ts')); }); - it('should throw if `styleUrls` is defined incorrectly in @Component', async() => { + it('should throw if `styleUrls` is defined incorrectly in @Component', async () => { env.write('test.ts', ` import {Component} from '@angular/core'; @@ -4376,7 +4373,7 @@ runInEachFileSystem(os => { const diags = await driveDiagnostics(); expect(diags[0].messageText).toBe('styleUrls must be an array of strings'); - expect(diags[0].file !.fileName).toBe(absoluteFrom('/test.ts')); + expect(diags[0].file!.fileName).toBe(absoluteFrom('/test.ts')); }); }); }); @@ -4497,7 +4494,7 @@ runInEachFileSystem(os => { // Verify that the error is for the correct class. const error = errors[0] as ts.Diagnostic; - const id = expectTokenAtPosition(error.file !, error.start !, ts.isIdentifier); + const id = expectTokenAtPosition(error.file!, error.start!, ts.isIdentifier); expect(id.text).toBe('Dir'); expect(ts.isClassDeclaration(id.parent)).toBe(true); }); @@ -4804,7 +4801,7 @@ runInEachFileSystem(os => { const diag = env.driveDiagnostics(); expect(diag.length).toBe(1); - expect(diag[0] !.code).toEqual(ngErrorCode(ErrorCode.NGMODULE_REEXPORT_NAME_COLLISION)); + expect(diag[0]!.code).toEqual(ngErrorCode(ErrorCode.NGMODULE_REEXPORT_NAME_COLLISION)); }); it('should not error when two directives with the same declared name are exported from the same NgModule, but one is exported from the file directly', @@ -6701,9 +6698,7 @@ export const Foo = Foo__PRE_R3__; const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); - }); - }); function expectTokenAtPosition( @@ -6714,5 +6709,7 @@ export const Foo = Foo__PRE_R3__; return node as T; } - function normalize(input: string): string { return input.replace(/\s+/g, ' ').trim(); } + function normalize(input: string): string { + return input.replace(/\s+/g, ' ').trim(); + } }); diff --git a/packages/compiler-cli/test/ngtsc/scope_spec.ts b/packages/compiler-cli/test/ngtsc/scope_spec.ts index 9165104706..904bedd75f 100644 --- a/packages/compiler-cli/test/ngtsc/scope_spec.ts +++ b/packages/compiler-cli/test/ngtsc/scope_spec.ts @@ -20,7 +20,7 @@ const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc module scopes', () => { - let env !: NgtscTestEnvironment; + let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); @@ -92,11 +92,11 @@ runInEachFileSystem(() => { const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); const node = findContainingClass(diagnosticToNode(diags[0], ts.isIdentifier)); - expect(node.name !.text).toEqual('TestDir'); + expect(node.name!.text).toEqual('TestDir'); - const relatedNodes = new Set(diags[0].relatedInformation !.map( + const relatedNodes = new Set(diags[0].relatedInformation!.map( related => - findContainingClass(diagnosticToNode(related, ts.isIdentifier)).name !.text)); + findContainingClass(diagnosticToNode(related, ts.isIdentifier)).name!.text)); expect(relatedNodes).toContain('ModuleA'); expect(relatedNodes).toContain('ModuleB'); expect(relatedNodes.size).toBe(2); @@ -141,11 +141,11 @@ runInEachFileSystem(() => { const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); const node = findContainingClass(diagnosticToNode(diags[0], ts.isIdentifier)); - expect(node.name !.text).toEqual('TestDir'); + expect(node.name!.text).toEqual('TestDir'); - const relatedNodes = new Set(diags[0].relatedInformation !.map( + const relatedNodes = new Set(diags[0].relatedInformation!.map( related => - findContainingClass(diagnosticToNode(related, ts.isIdentifier)).name !.text)); + findContainingClass(diagnosticToNode(related, ts.isIdentifier)).name!.text)); expect(relatedNodes).toContain('ModuleA'); expect(relatedNodes).toContain('ModuleB'); expect(relatedNodes.size).toBe(2); @@ -386,13 +386,13 @@ runInEachFileSystem(() => { }); function diagnosticToNode( - diagnostic: ts.Diagnostic | Diagnostic | ts.DiagnosticRelatedInformation, + diagnostic: ts.Diagnostic|Diagnostic|ts.DiagnosticRelatedInformation, guard: (node: ts.Node) => node is T): T { const diag = diagnostic as ts.Diagnostic | ts.DiagnosticRelatedInformation; if (diag.file === undefined) { throw new Error(`Expected ts.Diagnostic to have a file source`); } - const node = getTokenAtPosition(diag.file, diag.start !); + const node = getTokenAtPosition(diag.file, diag.start!); expect(guard(node)).toBe(true); return node as T; } diff --git a/packages/compiler-cli/test/ngtsc/sourcemap_utils.ts b/packages/compiler-cli/test/ngtsc/sourcemap_utils.ts index 2dbd7df542..dff529f602 100644 --- a/packages/compiler-cli/test/ngtsc/sourcemap_utils.ts +++ b/packages/compiler-cli/test/ngtsc/sourcemap_utils.ts @@ -85,7 +85,7 @@ export function getMappedSegments( while (currentMapping) { const nextMapping = mappings.shift(); if (nextMapping) { - const source = sources.get(currentMapping.source) !; + const source = sources.get(currentMapping.source)!; const segment = { generated: generated.getSegment('generated', currentMapping, nextMapping), source: source.getSegment('original', currentMapping, nextMapping), diff --git a/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts b/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts index 5c51defba1..aed02b33a4 100644 --- a/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts +++ b/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts @@ -14,13 +14,13 @@ import {tsSourceMapBug29300Fixed} from '../../src/ngtsc/util/src/ts_source_map_b import {loadStandardTestFiles} from '../helpers/src/mock_file_loading'; import {NgtscTestEnvironment} from './env'; -import {SegmentMapping, getMappedSegments} from './sourcemap_utils'; +import {getMappedSegments, SegmentMapping} from './sourcemap_utils'; const testFiles = loadStandardTestFiles(); runInEachFileSystem((os) => { describe('template source-mapping', () => { - let env !: NgtscTestEnvironment; + let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); @@ -323,7 +323,6 @@ runInEachFileSystem((os) => { expect(mappings).toContain( {source: '
', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts'}); - }); it('should map ng-template [ngFor] scenario', () => { @@ -518,7 +517,7 @@ runInEachFileSystem((os) => { }); } - function compileAndMap(template: string, templateUrl: string | null = null) { + function compileAndMap(template: string, templateUrl: string|null = null) { const templateConfig = templateUrl ? `templateUrl: '${templateUrl}'` : ('template: `' + template.replace(/`/g, '\\`') + '`'); env.tsconfig({sourceMap: true}); diff --git a/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts b/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts index 4d3aaafd78..e77209c7e0 100644 --- a/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts +++ b/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts @@ -19,7 +19,7 @@ const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc type checking', () => { - let env !: NgtscTestEnvironment; + let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); @@ -1502,8 +1502,9 @@ export declare class AnimationEvent { }); describe('legacy schema checking with the DOM schema', () => { - beforeEach( - () => { env.tsconfig({ivyTemplateTypeCheck: true, fullTemplateTypeCheck: false}); }); + beforeEach(() => { + env.tsconfig({ivyTemplateTypeCheck: true, fullTemplateTypeCheck: false}); + }); it('should check for unknown elements', () => { env.write('test.ts', ` @@ -1734,7 +1735,7 @@ export declare class AnimationEvent { } }); - it('should be correct for direct templates', async() => { + it('should be correct for direct templates', async () => { env.write('test.ts', ` import {Component, NgModule} from '@angular/core'; @@ -1750,11 +1751,11 @@ export declare class AnimationEvent { const diags = await driveDiagnostics(); expect(diags.length).toBe(1); - expect(diags[0].file !.fileName).toBe(_('/test.ts')); + expect(diags[0].file!.fileName).toBe(_('/test.ts')); expect(getSourceCodeForDiagnostic(diags[0])).toBe('user.does_not_exist'); }); - it('should be correct for indirect templates', async() => { + it('should be correct for indirect templates', async () => { env.write('test.ts', ` import {Component, NgModule} from '@angular/core'; @@ -1772,12 +1773,12 @@ export declare class AnimationEvent { const diags = await driveDiagnostics(); expect(diags.length).toBe(1); - expect(diags[0].file !.fileName).toBe(_('/test.ts') + ' (TestCmp template)'); + expect(diags[0].file!.fileName).toBe(_('/test.ts') + ' (TestCmp template)'); expect(getSourceCodeForDiagnostic(diags[0])).toBe('user.does_not_exist'); - expect(getSourceCodeForDiagnostic(diags[0].relatedInformation ![0])).toBe('TEMPLATE'); + expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])).toBe('TEMPLATE'); }); - it('should be correct for external templates', async() => { + it('should be correct for external templates', async () => { env.write('template.html', `

{{user.does_not_exist}}

`); @@ -1795,9 +1796,9 @@ export declare class AnimationEvent { const diags = await driveDiagnostics(); expect(diags.length).toBe(1); - expect(diags[0].file !.fileName).toBe(_('/template.html')); + expect(diags[0].file!.fileName).toBe(_('/template.html')); expect(getSourceCodeForDiagnostic(diags[0])).toBe('user.does_not_exist'); - expect(getSourceCodeForDiagnostic(diags[0].relatedInformation ![0])) + expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])) .toBe(`'./template.html'`); }); }); @@ -1841,6 +1842,6 @@ export declare class AnimationEvent { }); function getSourceCodeForDiagnostic(diag: ts.Diagnostic): string { - const text = diag.file !.text; - return text.substr(diag.start !, diag.length !); + const text = diag.file!.text; + return text.substr(diag.start!, diag.length!); } diff --git a/packages/compiler-cli/test/perform_compile_spec.ts b/packages/compiler-cli/test/perform_compile_spec.ts index 8696ab1955..d3e2517216 100644 --- a/packages/compiler-cli/test/perform_compile_spec.ts +++ b/packages/compiler-cli/test/perform_compile_spec.ts @@ -10,7 +10,7 @@ import * as path from 'path'; import {readConfiguration} from '../src/perform_compile'; -import {TestSupport, setup} from './test_support'; +import {setup, TestSupport} from './test_support'; describe('perform_compile', () => { let support: TestSupport; diff --git a/packages/compiler-cli/test/perform_watch_spec.ts b/packages/compiler-cli/test/perform_watch_spec.ts index 1ce31d7ac6..6cc620ca77 100644 --- a/packages/compiler-cli/test/perform_watch_spec.ts +++ b/packages/compiler-cli/test/perform_watch_spec.ts @@ -14,7 +14,7 @@ import * as ts from 'typescript'; import * as ng from '../index'; import {FileChangeEvent, performWatchCompilation} from '../src/perform_watch'; -import {TestSupport, expectNoDiagnostics, setup} from './test_support'; +import {expectNoDiagnostics, setup, TestSupport} from './test_support'; describe('perform watch', () => { let testSupport: TestSupport; @@ -105,23 +105,23 @@ describe('perform watch', () => { performWatchCompilation(host); expect(fs.existsSync(mainNgFactory)).toBe(true); - expect(fileExistsSpy !).toHaveBeenCalledWith(mainTsPath); - expect(fileExistsSpy !).toHaveBeenCalledWith(utilTsPath); - expect(getSourceFileSpy !).toHaveBeenCalledWith(mainTsPath, ts.ScriptTarget.ES5); - expect(getSourceFileSpy !).toHaveBeenCalledWith(utilTsPath, ts.ScriptTarget.ES5); + expect(fileExistsSpy!).toHaveBeenCalledWith(mainTsPath); + expect(fileExistsSpy!).toHaveBeenCalledWith(utilTsPath); + expect(getSourceFileSpy!).toHaveBeenCalledWith(mainTsPath, ts.ScriptTarget.ES5); + expect(getSourceFileSpy!).toHaveBeenCalledWith(utilTsPath, ts.ScriptTarget.ES5); - fileExistsSpy !.calls.reset(); - getSourceFileSpy !.calls.reset(); + fileExistsSpy!.calls.reset(); + getSourceFileSpy!.calls.reset(); // trigger a single file change // -> all other files should be cached host.triggerFileChange(FileChangeEvent.Change, utilTsPath); expectNoDiagnostics(config.options, host.diagnostics); - expect(fileExistsSpy !).not.toHaveBeenCalledWith(mainTsPath); - expect(fileExistsSpy !).toHaveBeenCalledWith(utilTsPath); - expect(getSourceFileSpy !).not.toHaveBeenCalledWith(mainTsPath, ts.ScriptTarget.ES5); - expect(getSourceFileSpy !).toHaveBeenCalledWith(utilTsPath, ts.ScriptTarget.ES5); + expect(fileExistsSpy!).not.toHaveBeenCalledWith(mainTsPath); + expect(fileExistsSpy!).toHaveBeenCalledWith(utilTsPath); + expect(getSourceFileSpy!).not.toHaveBeenCalledWith(mainTsPath, ts.ScriptTarget.ES5); + expect(getSourceFileSpy!).toHaveBeenCalledWith(utilTsPath, ts.ScriptTarget.ES5); // trigger a folder change // -> nothing should be cached @@ -129,10 +129,10 @@ describe('perform watch', () => { FileChangeEvent.CreateDeleteDir, path.resolve(testSupport.basePath, 'src')); expectNoDiagnostics(config.options, host.diagnostics); - expect(fileExistsSpy !).toHaveBeenCalledWith(mainTsPath); - expect(fileExistsSpy !).toHaveBeenCalledWith(utilTsPath); - expect(getSourceFileSpy !).toHaveBeenCalledWith(mainTsPath, ts.ScriptTarget.ES5); - expect(getSourceFileSpy !).toHaveBeenCalledWith(utilTsPath, ts.ScriptTarget.ES5); + expect(fileExistsSpy!).toHaveBeenCalledWith(mainTsPath); + expect(fileExistsSpy!).toHaveBeenCalledWith(utilTsPath); + expect(getSourceFileSpy!).toHaveBeenCalledWith(mainTsPath, ts.ScriptTarget.ES5); + expect(getSourceFileSpy!).toHaveBeenCalledWith(utilTsPath, ts.ScriptTarget.ES5); }); // https://github.com/angular/angular/pull/26036 @@ -239,10 +239,18 @@ class MockWatchHost { diagnostics: ng.Diagnostic[] = []; constructor(public config: ng.ParsedConfiguration) {} - reportDiagnostics(diags: ng.Diagnostics) { this.diagnostics.push(...(diags as ng.Diagnostic[])); } - readConfiguration() { return this.config; } - createCompilerHost(options: ng.CompilerOptions) { return ng.createCompilerHost({options}); } - createEmitCallback() { return undefined; } + reportDiagnostics(diags: ng.Diagnostics) { + this.diagnostics.push(...(diags as ng.Diagnostic[])); + } + readConfiguration() { + return this.config; + } + createCompilerHost(options: ng.CompilerOptions) { + return ng.createCompilerHost({options}); + } + createEmitCallback() { + return undefined; + } onFileChange( options: ng.CompilerOptions, listener: (event: FileChangeEvent, fileName: string) => void, ready: () => void) { @@ -258,7 +266,9 @@ class MockWatchHost { this.timeoutListeners[id] = callback; return id; } - clearTimeout(timeoutId: any): void { delete this.timeoutListeners[timeoutId]; } + clearTimeout(timeoutId: any): void { + delete this.timeoutListeners[timeoutId]; + } flushTimeouts() { const listeners = this.timeoutListeners; this.timeoutListeners = {}; diff --git a/packages/compiler-cli/test/test_support.ts b/packages/compiler-cli/test/test_support.ts index 84f07874af..5d337d4def 100644 --- a/packages/compiler-cli/test/test_support.ts +++ b/packages/compiler-cli/test/test_support.ts @@ -15,7 +15,7 @@ import {NodeJSFileSystem, setFileSystem} from '../src/ngtsc/file_system'; import {getAngularPackagesFromRunfiles, resolveNpmTreeArtifact} from '../test/helpers'; // TEST_TMPDIR is always set by Bazel. -const tmpdir = process.env.TEST_TMPDIR !; +const tmpdir = process.env.TEST_TMPDIR!; export function makeTempDir(): string { let dir: string; @@ -97,8 +97,11 @@ function createTestSupportFor(basePath: string) { } function writeFiles(...mockDirs: {[fileName: string]: string}[]) { - mockDirs.forEach( - (dir) => { Object.keys(dir).forEach((fileName) => { write(fileName, dir[fileName]); }); }); + mockDirs.forEach((dir) => { + Object.keys(dir).forEach((fileName) => { + write(fileName, dir[fileName]); + }); + }); } function createCompilerOptions(overrideOptions: ng.CompilerOptions = {}): ng.CompilerOptions { diff --git a/packages/compiler-cli/test/transformers/compiler_host_spec.ts b/packages/compiler-cli/test/transformers/compiler_host_spec.ts index 9a43783b54..123306c2ca 100644 --- a/packages/compiler-cli/test/transformers/compiler_host_spec.ts +++ b/packages/compiler-cli/test/transformers/compiler_host_spec.ts @@ -11,7 +11,7 @@ import * as ts from 'typescript'; import {MetadataCollector} from '../../src/metadata/collector'; import {CompilerHost, CompilerOptions, LibrarySummary} from '../../src/transformers/api'; -import {TsCompilerAotCompilerTypeCheckHostAdapter, createCompilerHost} from '../../src/transformers/compiler_host'; +import {createCompilerHost, TsCompilerAotCompilerTypeCheckHostAdapter} from '../../src/transformers/compiler_host'; import {Directory, Entry, MockAotContext, MockCompilerHost} from '../mocks'; const dummyModule = 'export let foo: any[];'; @@ -53,12 +53,15 @@ describe('NgCompilerHost', () => { } = {}) { return new TsCompilerAotCompilerTypeCheckHostAdapter( rootNames, options, ngHost, new MetadataCollector(), codeGenerator, - new Map(librarySummaries.map(entry => [entry.fileName, entry] as[string, LibrarySummary]))); + new Map( + librarySummaries.map(entry => [entry.fileName, entry] as [string, LibrarySummary]))); } describe('fileNameToModuleName', () => { let host: TsCompilerAotCompilerTypeCheckHostAdapter; - beforeEach(() => { host = createHost(); }); + beforeEach(() => { + host = createHost(); + }); it('should use a package import when accessing a package from a source file', () => { expect(host.fileNameToModuleName('/tmp/node_modules/@angular/core.d.ts', '/tmp/main.ts')) @@ -239,9 +242,8 @@ describe('NgCompilerHost', () => { it('should not get tripped on nested node_modules', () => { const genSf = generate('/tmp/node_modules/lib1/node_modules/lib2/thing', { - 'tmp': { - 'node_modules': {'lib1': {'node_modules': {'lib2': {'thing.ts': `// some content`}}}} - } + 'tmp': + {'node_modules': {'lib1': {'node_modules': {'lib2': {'thing.ts': `// some content`}}}}} }); expect(genSf.moduleName).toBe('lib2/thing.ngfactory'); }); @@ -387,8 +389,9 @@ describe('NgCompilerHost', () => { () => host.updateGeneratedFile(new compiler.GeneratedFile( '/tmp/src/index.ts', '/tmp/src/index.ngfactory.ts', [new compiler.DeclareVarStmt( - 'x', new compiler.ExternalExpr( - new compiler.ExternalReference('otherModule', 'aName')))]))) + 'x', + new compiler.ExternalExpr( + new compiler.ExternalReference('otherModule', 'aName')))]))) .toThrowError([ `Illegal State: external references changed in /tmp/src/index.ngfactory.ts.`, `Old: aModule.`, `New: otherModule` diff --git a/packages/compiler-cli/test/transformers/inline_resources_spec.ts b/packages/compiler-cli/test/transformers/inline_resources_spec.ts index 290dbb4929..3dbe49afea 100644 --- a/packages/compiler-cli/test/transformers/inline_resources_spec.ts +++ b/packages/compiler-cli/test/transformers/inline_resources_spec.ts @@ -8,8 +8,8 @@ import * as ts from 'typescript'; -import {MetadataCollector, isClassMetadata} from '../../src/metadata/index'; -import {InlineResourcesMetadataTransformer, getInlineResourcesTransformFactory} from '../../src/transformers/inline_resources'; +import {isClassMetadata, MetadataCollector} from '../../src/metadata/index'; +import {getInlineResourcesTransformFactory, InlineResourcesMetadataTransformer} from '../../src/transformers/inline_resources'; import {MetadataCache} from '../../src/transformers/metadata_cache'; import {MockAotContext, MockCompilerHost} from '../mocks'; diff --git a/packages/compiler-cli/test/transformers/lower_expressions_spec.ts b/packages/compiler-cli/test/transformers/lower_expressions_spec.ts index da873f8f0b..99b7e45725 100644 --- a/packages/compiler-cli/test/transformers/lower_expressions_spec.ts +++ b/packages/compiler-cli/test/transformers/lower_expressions_spec.ts @@ -9,7 +9,7 @@ import * as ts from 'typescript'; import {MetadataCollector, ModuleMetadata} from '../../src/metadata/index'; -import {LowerMetadataTransform, LoweringRequest, RequestLocationMap, getExpressionLoweringTransformFactory} from '../../src/transformers/lower_expressions'; +import {getExpressionLoweringTransformFactory, LoweringRequest, LowerMetadataTransform, RequestLocationMap} from '../../src/transformers/lower_expressions'; import {MetadataCache} from '../../src/transformers/metadata_cache'; import {Directory, MockAotContext, MockCompilerHost} from '../mocks'; @@ -196,14 +196,16 @@ function convert(annotatedSource: string) { const program = ts.createProgram( [fileName], {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2017}, host); - const moduleSourceFile = program.getSourceFile(fileName) !; + const moduleSourceFile = program.getSourceFile(fileName)!; const transformers: ts.CustomTransformers = { before: [getExpressionLoweringTransformFactory( { - getRequests(sourceFile: ts.SourceFile): RequestLocationMap{ + getRequests(sourceFile: ts.SourceFile): RequestLocationMap { if (sourceFile.fileName == moduleSourceFile.fileName) { return requests; - } else {return new Map();} + } else { + return new Map(); + } } }, program)] @@ -254,6 +256,7 @@ function collect(annotatedSource: string) { 'someName.ts', unannotatedSource, ts.ScriptTarget.Latest, /* setParentNodes */ true); return { metadata: cache.getMetadata(sourceFile), - requests: transformer.getRequests(sourceFile), annotations + requests: transformer.getRequests(sourceFile), + annotations }; } \ No newline at end of file diff --git a/packages/compiler-cli/test/transformers/metadata_reader_spec.ts b/packages/compiler-cli/test/transformers/metadata_reader_spec.ts index 306c215483..13437c54ec 100644 --- a/packages/compiler-cli/test/transformers/metadata_reader_spec.ts +++ b/packages/compiler-cli/test/transformers/metadata_reader_spec.ts @@ -23,10 +23,9 @@ describe('metadata reader', () => { readFile: (fileName) => context.readFile(fileName), getSourceFileMetadata: (fileName) => { const sourceText = context.readFile(fileName); - return sourceText != null ? - metadataCollector.getMetadata( - ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.Latest)) : - undefined; + return sourceText != null ? metadataCollector.getMetadata(ts.createSourceFile( + fileName, sourceText, ts.ScriptTarget.Latest)) : + undefined; }, }; }); @@ -42,11 +41,13 @@ describe('metadata reader', () => { expect(readMetadata('node_modules/@angular/unused.d.ts', host)).toEqual([dummyMetadata]); }); - it('should be able to read empty metadata ', - () => { expect(readMetadata('node_modules/@angular/empty.d.ts', host)).toEqual([]); }); + it('should be able to read empty metadata ', () => { + expect(readMetadata('node_modules/@angular/empty.d.ts', host)).toEqual([]); + }); - it('should return undefined for missing modules', - () => { expect(readMetadata('node_modules/@angular/missing.d.ts', host)).toBeUndefined(); }); + it('should return undefined for missing modules', () => { + expect(readMetadata('node_modules/@angular/missing.d.ts', host)).toBeUndefined(); + }); it(`should add missing v${METADATA_VERSION} metadata from v1 metadata and .d.ts files`, () => { expect(readMetadata('metadata_versions/v1.d.ts', host)).toEqual([ @@ -117,8 +118,8 @@ const FILES: Entry = { 'node_modules': { '@angular': { 'core.d.ts': dummyModule, - 'core.metadata.json': - `{"__symbolic":"module", "version": ${METADATA_VERSION}, "metadata": {"foo": {"__symbolic": "class"}}}`, + 'core.metadata.json': `{"__symbolic":"module", "version": ${ + METADATA_VERSION}, "metadata": {"foo": {"__symbolic": "class"}}}`, 'router': {'index.d.ts': dummyModule, 'src': {'providers.d.ts': dummyModule}}, 'unused.d.ts': dummyModule, 'empty.d.ts': 'export declare var a: string;', diff --git a/packages/compiler-cli/test/transformers/node_emitter_spec.ts b/packages/compiler-cli/test/transformers/node_emitter_spec.ts index c5e3ce09cb..0b53d4b380 100644 --- a/packages/compiler-cli/test/transformers/node_emitter_spec.ts +++ b/packages/compiler-cli/test/transformers/node_emitter_spec.ts @@ -38,7 +38,7 @@ describe('TypeScriptNodeEmitter', () => { }); function emitStmt( - stmt: o.Statement | o.Statement[], format: Format = Format.Flat, preamble?: string): string { + stmt: o.Statement|o.Statement[], format: Format = Format.Flat, preamble?: string): string { const stmts = Array.isArray(stmt) ? stmt : [stmt]; const program = ts.createProgram( @@ -246,8 +246,8 @@ describe('TypeScriptNodeEmitter', () => { expect(emitStmt(new o.DeclareFunctionStmt( 'someFn', [], [new o.ReturnStatement(o.literal(1))], o.INT_TYPE))) .toEqual(`function someFn() { return 1; }`); - expect(emitStmt(new o.DeclareFunctionStmt('someFn', [new o.FnParam('param1', o.INT_TYPE)], [ - ]))).toEqual(`function someFn(param1) { }`); + expect(emitStmt(new o.DeclareFunctionStmt('someFn', [new o.FnParam('param1', o.INT_TYPE)], []))) + .toEqual(`function someFn(param1) { }`); }); describe('comments', () => { @@ -256,8 +256,9 @@ describe('TypeScriptNodeEmitter', () => { .toBe('/* SomePreamble */ a;'); }); - it('should support singleline comments', - () => { expect(emitStmt(new o.CommentStmt('Simple comment'))).toBe('// Simple comment'); }); + it('should support singleline comments', () => { + expect(emitStmt(new o.CommentStmt('Simple comment'))).toBe('// Simple comment'); + }); it('should support multiline comments', () => { expect(emitStmt(new o.CommentStmt('Multiline comment', true))) @@ -314,86 +315,90 @@ describe('TypeScriptNodeEmitter', () => { `try { body(); } catch (error) { var stack = error.stack; catchFn(error, stack); }`); }); - it('should support support throwing', - () => { expect(emitStmt(new o.ThrowStmt(someVar))).toEqual('throw someVar;'); }); + it('should support support throwing', () => { + expect(emitStmt(new o.ThrowStmt(someVar))).toEqual('throw someVar;'); + }); describe('classes', () => { let callSomeMethod: o.Statement; - beforeEach(() => { callSomeMethod = o.THIS_EXPR.callMethod('someMethod', []).toStmt(); }); + beforeEach(() => { + callSomeMethod = o.THIS_EXPR.callMethod('someMethod', []).toStmt(); + }); it('should support declaring classes', () => { - expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [ - ]))).toEqual('class SomeClass { }'); - expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [], [ + expect(emitStmt(new o.ClassStmt('SomeClass', null!, [], [], null!, []))) + .toEqual('class SomeClass { }'); + expect(emitStmt(new o.ClassStmt('SomeClass', null!, [], [], null!, [], [ o.StmtModifier.Exported ]))).toEqual('class SomeClass { } exports.SomeClass = SomeClass;'); - expect(emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null !, [ - ]))).toEqual('class SomeClass extends SomeSuperClass { }'); + expect( + emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null!, []))) + .toEqual('class SomeClass extends SomeSuperClass { }'); }); it('should support declaring constructors', () => { const superCall = o.SUPER_EXPR.callFn([o.variable('someParam')]).toStmt(); - expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, [], [], new o.ClassMethod(null !, [], []), []))) + expect(emitStmt( + new o.ClassStmt('SomeClass', null!, [], [], new o.ClassMethod(null!, [], []), []))) .toEqual(`class SomeClass { constructor() { } }`); expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, [], [], - new o.ClassMethod(null !, [new o.FnParam('someParam', o.INT_TYPE)], []), []))) + 'SomeClass', null!, [], [], + new o.ClassMethod(null!, [new o.FnParam('someParam', o.INT_TYPE)], []), []))) .toEqual(`class SomeClass { constructor(someParam) { } }`); expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, [], [], new o.ClassMethod(null !, [], [superCall]), []))) + 'SomeClass', null!, [], [], new o.ClassMethod(null!, [], [superCall]), []))) .toEqual(`class SomeClass { constructor() { super(someParam); } }`); expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, [], [], new o.ClassMethod(null !, [], [callSomeMethod]), []))) + 'SomeClass', null!, [], [], new o.ClassMethod(null!, [], [callSomeMethod]), []))) .toEqual(`class SomeClass { constructor() { this.someMethod(); } }`); }); it('should support declaring fields', () => { expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, [new o.ClassField('someField')], [], null !, []))) + 'SomeClass', null!, [new o.ClassField('someField')], [], null!, []))) .toEqual(`class SomeClass { constructor() { this.someField = null; } }`); expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, [new o.ClassField('someField', o.INT_TYPE)], [], null !, []))) + 'SomeClass', null!, [new o.ClassField('someField', o.INT_TYPE)], [], null!, []))) .toEqual(`class SomeClass { constructor() { this.someField = null; } }`); expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, - [new o.ClassField('someField', o.INT_TYPE, [o.StmtModifier.Private])], [], null !, + 'SomeClass', null!, + [new o.ClassField('someField', o.INT_TYPE, [o.StmtModifier.Private])], [], null!, []))) .toEqual(`class SomeClass { constructor() { this.someField = null; } }`); }); it('should support declaring getters', () => { expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, [], [new o.ClassGetter('someGetter', [])], null !, []))) + 'SomeClass', null!, [], [new o.ClassGetter('someGetter', [])], null!, []))) .toEqual(`class SomeClass { get someGetter() { } }`); expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, [], [new o.ClassGetter('someGetter', [], o.INT_TYPE)], null !, + 'SomeClass', null!, [], [new o.ClassGetter('someGetter', [], o.INT_TYPE)], null!, []))) .toEqual(`class SomeClass { get someGetter() { } }`); expect(emitStmt(new o.ClassStmt( - 'SomeClass', null !, [], [new o.ClassGetter('someGetter', [callSomeMethod])], - null !, []))) + 'SomeClass', null!, [], [new o.ClassGetter('someGetter', [callSomeMethod])], null!, + []))) .toEqual(`class SomeClass { get someGetter() { this.someMethod(); } }`); expect( emitStmt(new o.ClassStmt( - 'SomeClass', null !, [], - [new o.ClassGetter('someGetter', [], null !, [o.StmtModifier.Private])], null !, []))) + 'SomeClass', null!, [], + [new o.ClassGetter('someGetter', [], null!, [o.StmtModifier.Private])], null!, []))) .toEqual(`class SomeClass { get someGetter() { } }`); }); it('should support methods', () => { - expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [ + expect(emitStmt(new o.ClassStmt('SomeClass', null!, [], [], null!, [ new o.ClassMethod('someMethod', [], []) ]))).toEqual(`class SomeClass { someMethod() { } }`); - expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [ + expect(emitStmt(new o.ClassStmt('SomeClass', null!, [], [], null!, [ new o.ClassMethod('someMethod', [], [], o.INT_TYPE) ]))).toEqual(`class SomeClass { someMethod() { } }`); - expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [ + expect(emitStmt(new o.ClassStmt('SomeClass', null!, [], [], null!, [ new o.ClassMethod('someMethod', [new o.FnParam('someParam', o.INT_TYPE)], []) ]))).toEqual(`class SomeClass { someMethod(someParam) { } }`); - expect(emitStmt(new o.ClassStmt('SomeClass', null !, [], [], null !, [ + expect(emitStmt(new o.ClassStmt('SomeClass', null!, [], [], null!, [ new o.ClassMethod('someMethod', [], [callSomeMethod]) ]))).toEqual(`class SomeClass { someMethod() { this.someMethod(); } }`); }); @@ -431,7 +436,7 @@ describe('TypeScriptNodeEmitter', () => { it('should support combined types', () => { const writeVarExpr = o.variable('a').set(o.NULL_EXPR); - expect(emitStmt(writeVarExpr.toDeclStmt(new o.ArrayType(null !)))).toEqual('var a = null;'); + expect(emitStmt(writeVarExpr.toDeclStmt(new o.ArrayType(null!)))).toEqual('var a = null;'); expect(emitStmt(writeVarExpr.toDeclStmt(new o.ArrayType(o.INT_TYPE)))).toEqual('var a = null;'); expect(emitStmt(writeVarExpr.toDeclStmt(new o.MapType(null)))).toEqual('var a = null;'); @@ -439,7 +444,7 @@ describe('TypeScriptNodeEmitter', () => { }); describe('source maps', () => { - function emitStmt(stmt: o.Statement | o.Statement[], preamble?: string): string { + function emitStmt(stmt: o.Statement|o.Statement[], preamble?: string): string { const stmts = Array.isArray(stmt) ? stmt : [stmt]; const program = ts.createProgram( @@ -473,13 +478,15 @@ describe('TypeScriptNodeEmitter', () => { function mappingItemsOf(text: string) { // find the source map: const sourceMapMatch = /sourceMappingURL\=data\:application\/json;base64,(.*)$/.exec(text); - const sourceMapBase64 = sourceMapMatch ![1]; + const sourceMapBase64 = sourceMapMatch![1]; const sourceMapBuffer = Buffer.from(sourceMapBase64, 'base64'); const sourceMapText = sourceMapBuffer.toString('utf8'); const sourceMapParsed = JSON.parse(sourceMapText); const consumer = new sourceMap.SourceMapConsumer(sourceMapParsed); const mappings: any[] = []; - consumer.eachMapping((mapping: any) => { mappings.push(mapping); }); + consumer.eachMapping((mapping: any) => { + mappings.push(mapping); + }); return mappings; } @@ -503,7 +510,7 @@ describe('TypeScriptNodeEmitter', () => { generatedColumn: 0, originalLine: 1, originalColumn: 0, - name: null ! // TODO: Review use of `!` here (#19904) + name: null! // TODO: Review use of `!` here (#19904) }, { source: sourceUrl, @@ -511,7 +518,7 @@ describe('TypeScriptNodeEmitter', () => { generatedColumn: 16, originalLine: 1, originalColumn: 26, - name: null ! // TODO: Review use of `!` here (#19904) + name: null! // TODO: Review use of `!` here (#19904) } ]); }); @@ -558,7 +565,10 @@ const FILES: Directory = { somePackage: {'someGenFile.ts': `export var a: number;`} }; -const enum Format { Raw, Flat } +const enum Format { + Raw, + Flat +} function normalizeResult(result: string, format: Format): string { // Remove TypeScript prefixes diff --git a/packages/compiler-cli/test/transformers/program_spec.ts b/packages/compiler-cli/test/transformers/program_spec.ts index a701354005..8f3dc5ccdd 100644 --- a/packages/compiler-cli/test/transformers/program_spec.ts +++ b/packages/compiler-cli/test/transformers/program_spec.ts @@ -10,11 +10,12 @@ import * as ng from '@angular/compiler-cli'; import * as fs from 'fs'; import * as path from 'path'; import * as ts from 'typescript'; + import {formatDiagnostics} from '../../src/perform_compile'; import {CompilerHost, EmitFlags, LazyRoute} from '../../src/transformers/api'; import {createSrcToOutPathMapper} from '../../src/transformers/program'; import {StructureIsReused, tsStructureIsReused} from '../../src/transformers/util'; -import {TestSupport, expectNoDiagnosticsInProgram, setup, stripAnsi} from '../test_support'; +import {expectNoDiagnosticsInProgram, setup, stripAnsi, TestSupport} from '../test_support'; describe('ng program', () => { let testSupport: TestSupport; @@ -83,21 +84,21 @@ describe('ng program', () => { const originalGetSourceFile = host.getSourceFile; const cache = new Map(); - host.getSourceFile = function( - fileName: string, languageVersion: ts.ScriptTarget): ts.SourceFile | - undefined { - const sf = originalGetSourceFile.call(host, fileName, languageVersion); - if (sf) { - if (cache.has(sf.fileName)) { - const oldSf = cache.get(sf.fileName) !; - if (oldSf.getFullText() === sf.getFullText()) { - return oldSf; - } - } - cache.set(sf.fileName, sf); - } - return sf; - }; + host.getSourceFile = function(fileName: string, languageVersion: ts.ScriptTarget): + ts.SourceFile| + undefined { + const sf = originalGetSourceFile.call(host, fileName, languageVersion); + if (sf) { + if (cache.has(sf.fileName)) { + const oldSf = cache.get(sf.fileName)!; + if (oldSf.getFullText() === sf.getFullText()) { + return oldSf; + } + } + cache.set(sf.fileName, sf); + } + return sf; + }; return host; } @@ -248,7 +249,8 @@ describe('ng program', () => { fileCache.delete(path.posix.join(testSupport.basePath, 'src/index.ts')); const p6 = ng.createProgram({ rootNames: [path.posix.join(testSupport.basePath, 'src/index.ts')], - options: testSupport.createCompilerOptions(options), host, + options: testSupport.createCompilerOptions(options), + host, oldProgram: p5 }); const p7 = compile(p6, options, undefined, host).program; @@ -295,7 +297,6 @@ describe('ng program', () => { describe( 'verify that program structure is reused within tsc in order to speed up incremental compilation', () => { - it('should reuse the old ts program completely if nothing changed', () => { testSupport.writeFiles({'src/index.ts': createModuleAndCompSource('main')}); const host = createWatchModeHost(); @@ -351,7 +352,6 @@ describe('ng program', () => { expect(tsStructureIsReused(p2.getTsProgram())).toBe(StructureIsReused.SafeModules); }); }); - }); it('should not typecheck templates if skipTemplateCodegen is set but fullTemplateTypeCheck is not', @@ -473,7 +473,7 @@ describe('ng program', () => { host.writeFile = (fileName: string, data: string, writeByteOrderMark: boolean, - onError: ((message: string) => void) | undefined, + onError: ((message: string) => void)|undefined, sourceFiles?: ReadonlyArray) => { written.set(fileName, {original: sourceFiles, data}); }; @@ -487,19 +487,19 @@ describe('ng program', () => { const writeData = written.get(path.posix.join(testSupport.basePath, fileName)); expect(writeData).toBeTruthy(); expect( - writeData !.original !.some( + writeData!.original!.some( sf => sf.fileName === path.posix.join(testSupport.basePath, checks.originalFileName))) .toBe(true); switch (checks.shouldBe) { case ShouldBe.Empty: - expect(writeData !.data).toMatch(/^(\s*\/\*([^*]|\*[^/])*\*\/\s*)?$/); + expect(writeData!.data).toMatch(/^(\s*\/\*([^*]|\*[^/])*\*\/\s*)?$/); break; case ShouldBe.EmptyExport: - expect(writeData !.data) + expect(writeData!.data) .toMatch(/^((\s*\/\*([^*]|\*[^/])*\*\/\s*)|(\s*export\s*{\s*}\s*;\s*)|())$/); break; case ShouldBe.NoneEmpty: - expect(writeData !.data).not.toBe(''); + expect(writeData!.data).not.toBe(''); break; } } @@ -1099,15 +1099,15 @@ describe('ng program', () => { }); const host = ng.createCompilerHost({options}); const originalGetSourceFile = host.getSourceFile; - host.getSourceFile = (fileName: string, languageVersion: ts.ScriptTarget, - onError?: ((message: string) => void) | undefined): ts.SourceFile | - undefined => { - // We should never try to load .ngfactory.ts files - if (fileName.match(/\.ngfactory\.ts$/)) { - throw new Error(`Non existent ngfactory file: ` + fileName); - } - return originalGetSourceFile.call(host, fileName, languageVersion, onError); - }; + host.getSourceFile = + (fileName: string, languageVersion: ts.ScriptTarget, + onError?: ((message: string) => void)|undefined): ts.SourceFile|undefined => { + // We should never try to load .ngfactory.ts files + if (fileName.match(/\.ngfactory\.ts$/)) { + throw new Error(`Non existent ngfactory file: ` + fileName); + } + return originalGetSourceFile.call(host, fileName, languageVersion, onError); + }; const program = ng.createProgram({rootNames: allRootNames, options, host}); const structuralErrors = program.getNgStructuralDiagnostics(); expect(structuralErrors.length).toBe(1); @@ -1115,5 +1115,4 @@ describe('ng program', () => { .toContain('Function expressions are not supported'); }); }); - }); diff --git a/packages/compiler-cli/test/transformers/r3_metadata_transform_spec.ts b/packages/compiler-cli/test/transformers/r3_metadata_transform_spec.ts index 47b1d23dfb..7ab230c0e6 100644 --- a/packages/compiler-cli/test/transformers/r3_metadata_transform_spec.ts +++ b/packages/compiler-cli/test/transformers/r3_metadata_transform_spec.ts @@ -9,12 +9,11 @@ import {ClassField, ClassMethod, ClassStmt, PartialModule, Statement, StmtModifier} from '@angular/compiler'; import * as ts from 'typescript'; -import {MetadataCollector, isClassMetadata} from '../../src/metadata/index'; +import {isClassMetadata, MetadataCollector} from '../../src/metadata/index'; import {MetadataCache} from '../../src/transformers/metadata_cache'; import {PartialModuleMetadataTransformer} from '../../src/transformers/r3_metadata_transform'; describe('r3_transform_spec', () => { - it('should add a static method to collected metadata', () => { const fileName = '/some/directory/someFileName.ts'; const className = 'SomeClass'; diff --git a/packages/compiler-cli/test/transformers/r3_transform_spec.ts b/packages/compiler-cli/test/transformers/r3_transform_spec.ts index 5b893cf6de..adf93e26b6 100644 --- a/packages/compiler-cli/test/transformers/r3_transform_spec.ts +++ b/packages/compiler-cli/test/transformers/r3_transform_spec.ts @@ -30,8 +30,9 @@ describe('r3_transform_spec', () => { .toContain('static someMethod(v) { return v; }'); }); - it('should be able to generate a static field declaration', - () => { expect(emitStaticField(o.literal(10))).toContain('SomeClass.someField = 10'); }); + it('should be able to generate a static field declaration', () => { + expect(emitStaticField(o.literal(10))).toContain('SomeClass.someField = 10'); + }); it('should be able to import a symbol', () => { expect(emitStaticMethod(new o.ReturnStatement( @@ -90,8 +91,8 @@ describe('r3_transform_spec', () => { } function emitStaticMethod( - stmt: o.Statement | o.Statement[], parameters: string[] = [], - methodName: string = 'someMethod', className: string = 'SomeClass'): string { + stmt: o.Statement|o.Statement[], parameters: string[] = [], methodName: string = 'someMethod', + className: string = 'SomeClass'): string { const module: PartialModule = { fileName: someGenFileName, statements: [classMethod(stmt, parameters, methodName, className)] @@ -122,7 +123,7 @@ const FILES: Directory = { }; function classMethod( - stmt: o.Statement | o.Statement[], parameters: string[] = [], methodName: string = 'someMethod', + stmt: o.Statement|o.Statement[], parameters: string[] = [], methodName: string = 'someMethod', className: string = 'SomeClass'): o.ClassStmt { const statements = Array.isArray(stmt) ? stmt : [stmt]; return new o.ClassStmt( diff --git a/packages/compiler-cli/test/typescript_support_spec.ts b/packages/compiler-cli/test/typescript_support_spec.ts index 6a6c03c34a..0995ac5238 100644 --- a/packages/compiler-cli/test/typescript_support_spec.ts +++ b/packages/compiler-cli/test/typescript_support_spec.ts @@ -11,8 +11,8 @@ describe('checkVersion', () => { const MIN_TS_VERSION = '2.7.2'; const MAX_TS_VERSION = '2.8.0'; - const versionError = (version: string) => - `The Angular Compiler requires TypeScript >=${MIN_TS_VERSION} and <${MAX_TS_VERSION} but ${version} was found instead.`; + const versionError = (version: string) => `The Angular Compiler requires TypeScript >=${ + MIN_TS_VERSION} and <${MAX_TS_VERSION} but ${version} was found instead.`; it('should not throw when a supported TypeScript version is used', () => { expect(() => checkVersion('2.7.2', MIN_TS_VERSION, MAX_TS_VERSION)).not.toThrow();