build: upgrade to TypeScript 2.6 (#21144)

Fixes #20653

PR Close #21144
This commit is contained in:
Chuck Jazdzewski 2017-12-22 09:36:47 -08:00 committed by Igor Minar
parent 83c1383701
commit 83d207d0a7
45 changed files with 331 additions and 215 deletions

View File

@ -16,7 +16,8 @@ node_repositories(package_json = ["//:package.json"])
git_repository( git_repository(
name = "build_bazel_rules_typescript", name = "build_bazel_rules_typescript",
remote = "https://github.com/bazelbuild/rules_typescript.git", remote = "https://github.com/bazelbuild/rules_typescript.git",
tag = "0.7.1", # tag = "0.7.1+",
commit = "89d2c75066bea3d9c942f29dd1d2ea543c58d6d5"
) )
load("@build_bazel_rules_typescript//:setup.bzl", "ts_setup_workspace") load("@build_bazel_rules_typescript//:setup.bzl", "ts_setup_workspace")

View File

@ -1,4 +1,4 @@
{ {
"cli-hello-world":{"master":{"gzip7":{"inline":847,"main":42533,"polyfills":20207},"gzip9":{"inline":847,"main":42483,"polyfills":20204},"uncompressed":{"inline":1447,"main":154295,"polyfills":61254}}}, "cli-hello-world":{"master":{"gzip7":{"inline":847,"main":42533,"polyfills":20207},"gzip9":{"inline":847,"main":42483,"polyfills":20204},"uncompressed":{"inline":1447,"main":151954,"polyfills":61254}}},
"hello_world__closure":{"master":{"gzip7":{"bundle":32793},"gzip9":{"bundle":32758},"uncompressed":{"bundle":100661}}} "hello_world__closure":{"master":{"gzip7":{"bundle":32793},"gzip9":{"bundle":32758},"uncompressed":{"bundle":100661}}}
} }

View File

@ -14,12 +14,13 @@ node_repositories(package_json = ["//:package.json"])
git_repository( git_repository(
name = "build_bazel_rules_typescript", name = "build_bazel_rules_typescript",
remote = "https://github.com/bazelbuild/rules_typescript.git", remote = "https://github.com/bazelbuild/rules_typescript.git",
tag = "0.6.0", # tag = "0.6.0",
commit = "89d2c75066bea3d9c942f29dd1d2ea543c58d6d5"
) )
load("@build_bazel_rules_typescript//:defs.bzl", "ts_repositories") load("@build_bazel_rules_typescript//:setup.bzl", "ts_setup_workspace")
ts_repositories() ts_setup_workspace()
local_repository( local_repository(
name = "angular", name = "angular",

View File

@ -5,7 +5,7 @@
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"postinstall": "webdriver-manager update --gecko false --standalone false $CHROMEDRIVER_VERSION_ARG", "postinstall": "webdriver-manager update --gecko false --standalone false $CHROMEDRIVER_VERSION_ARG",
"test": "concurrently \"npm run serve\" \"npm run protractor\" --kill-others --success first", "test": "concurrently \"yarn serve\" \"yarn protractor\" --kill-others --success first",
"serve": "lite-server -c bs-config.e2e.json", "serve": "lite-server -c bs-config.e2e.json",
"preprotractor": "tsc -p e2e", "preprotractor": "tsc -p e2e",
"protractor": "protractor protractor.config.js" "protractor": "protractor protractor.config.js"
@ -17,7 +17,7 @@
"@angular/platform-browser": "file:../../dist/packages-dist/platform-browser", "@angular/platform-browser": "file:../../dist/packages-dist/platform-browser",
"@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic", "@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic",
"core-js": "2.4.1", "core-js": "2.4.1",
"plugin-typescript": "6.0.4", "plugin-typescript": "8.0.0",
"rxjs": "file:../../node_modules/rxjs", "rxjs": "file:../../node_modules/rxjs",
"systemjs": "0.20.2", "systemjs": "0.20.2",
"typescript": "file:../../node_modules/typescript", "typescript": "file:../../node_modules/typescript",

View File

@ -13,13 +13,16 @@ import * as coreTesting from '@angular/core/testing';
import * as forms from '@angular/forms'; import * as forms from '@angular/forms';
import * as http from '@angular/http'; import * as http from '@angular/http';
import * as httpTesting from '@angular/http/testing'; import * as httpTesting from '@angular/http/testing';
import * as platformBrowserDynamic from '@angular/platform-browser-dynamic';
import * as platformBrowser from '@angular/platform-browser'; import * as platformBrowser from '@angular/platform-browser';
import * as platformBrowserTesting from '@angular/platform-browser/testing'; import * as platformBrowserTesting from '@angular/platform-browser/testing';
import * as platformBrowserDynamic from '@angular/platform-browser-dynamic';
import * as platformServer from '@angular/platform-server'; import * as platformServer from '@angular/platform-server';
import * as platformServerTesting from '@angular/platform-server/testing'; import * as platformServerTesting from '@angular/platform-server/testing';
import * as platformWebworker from '@angular/platform-webworker';
import * as platformWebworkerDynamic from '@angular/platform-webworker-dynamic';
import * as router from '@angular/router'; import * as router from '@angular/router';
import * as routerTesting from '@angular/router/testing'; import * as routerTesting from '@angular/router/testing';
import * as serviceWorker from '@angular/service-worker';
import * as upgrade from '@angular/upgrade'; import * as upgrade from '@angular/upgrade';
export default { export default {
@ -35,7 +38,10 @@ export default {
platformBrowserDynamic, platformBrowserDynamic,
platformServer, platformServer,
platformServerTesting, platformServerTesting,
platformWebworker,
platformWebworkerDynamic,
router, router,
routerTesting, routerTesting,
upgrade serviceWorker,
upgrade,
}; };

View File

@ -14,7 +14,10 @@
"@angular/platform-browser": "file:../../dist/packages-dist/platform-browser", "@angular/platform-browser": "file:../../dist/packages-dist/platform-browser",
"@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic", "@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic",
"@angular/platform-server": "file:../../dist/packages-dist/platform-server", "@angular/platform-server": "file:../../dist/packages-dist/platform-server",
"@angular/platform-webworker": "file:../../dist/packages-dist/platform-webworker",
"@angular/platform-webworker-dynamic": "file:../../dist/packages-dist/platform-webworker-dynamic",
"@angular/router": "file:../../dist/packages-dist/router", "@angular/router": "file:../../dist/packages-dist/router",
"@angular/service-worker": "file:../../dist/packages-dist/service-worker",
"@angular/upgrade": "file:../../dist/packages-dist/upgrade", "@angular/upgrade": "file:../../dist/packages-dist/upgrade",
"@types/jasmine": "2.5.41", "@types/jasmine": "2.5.41",
"rxjs": "file:../../node_modules/rxjs", "rxjs": "file:../../node_modules/rxjs",

View File

@ -13,13 +13,16 @@ import * as coreTesting from '@angular/core/testing';
import * as forms from '@angular/forms'; import * as forms from '@angular/forms';
import * as http from '@angular/http'; import * as http from '@angular/http';
import * as httpTesting from '@angular/http/testing'; import * as httpTesting from '@angular/http/testing';
import * as platformBrowserDynamic from '@angular/platform-browser-dynamic';
import * as platformBrowser from '@angular/platform-browser'; import * as platformBrowser from '@angular/platform-browser';
import * as platformBrowserTesting from '@angular/platform-browser/testing'; import * as platformBrowserTesting from '@angular/platform-browser/testing';
import * as platformBrowserDynamic from '@angular/platform-browser-dynamic';
import * as platformServer from '@angular/platform-server'; import * as platformServer from '@angular/platform-server';
import * as platformServerTesting from '@angular/platform-server/testing'; import * as platformServerTesting from '@angular/platform-server/testing';
import * as platformWebworker from '@angular/platform-webworker';
import * as platformWebworkerDynamic from '@angular/platform-webworker-dynamic';
import * as router from '@angular/router'; import * as router from '@angular/router';
import * as routerTesting from '@angular/router/testing'; import * as routerTesting from '@angular/router/testing';
import * as serviceWorker from '@angular/service-worker';
import * as upgrade from '@angular/upgrade'; import * as upgrade from '@angular/upgrade';
export default { export default {
@ -35,7 +38,10 @@ export default {
platformBrowserDynamic, platformBrowserDynamic,
platformServer, platformServer,
platformServerTesting, platformServerTesting,
platformWebworker,
platformWebworkerDynamic,
router, router,
routerTesting, routerTesting,
upgrade serviceWorker,
upgrade,
}; };

View File

@ -14,7 +14,10 @@
"@angular/platform-browser": "file:../../dist/packages-dist/platform-browser", "@angular/platform-browser": "file:../../dist/packages-dist/platform-browser",
"@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic", "@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic",
"@angular/platform-server": "file:../../dist/packages-dist/platform-server", "@angular/platform-server": "file:../../dist/packages-dist/platform-server",
"@angular/platform-webworker": "file:../../dist/packages-dist/platform-webworker",
"@angular/platform-webworker-dynamic": "file:../../dist/packages-dist/platform-webworker-dynamic",
"@angular/router": "file:../../dist/packages-dist/router", "@angular/router": "file:../../dist/packages-dist/router",
"@angular/service-worker": "file:../../dist/packages-dist/service-worker",
"@angular/upgrade": "file:../../dist/packages-dist/upgrade", "@angular/upgrade": "file:../../dist/packages-dist/upgrade",
"@types/jasmine": "2.5.41", "@types/jasmine": "2.5.41",
"rxjs": "file:../../node_modules/rxjs", "rxjs": "file:../../node_modules/rxjs",

View File

@ -0,0 +1,47 @@
/**
* @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 compiler from '@angular/compiler';
import * as compilerTesting from '@angular/compiler/testing';
import * as core from '@angular/core';
import * as coreTesting from '@angular/core/testing';
import * as forms from '@angular/forms';
import * as http from '@angular/http';
import * as httpTesting from '@angular/http/testing';
import * as platformBrowser from '@angular/platform-browser';
import * as platformBrowserTesting from '@angular/platform-browser/testing';
import * as platformBrowserDynamic from '@angular/platform-browser-dynamic';
import * as platformServer from '@angular/platform-server';
import * as platformServerTesting from '@angular/platform-server/testing';
import * as platformWebworker from '@angular/platform-webworker';
import * as platformWebworkerDynamic from '@angular/platform-webworker-dynamic';
import * as router from '@angular/router';
import * as routerTesting from '@angular/router/testing';
import * as serviceWorker from '@angular/service-worker';
import * as upgrade from '@angular/upgrade';
export default {
compiler,
compilerTesting,
core,
coreTesting,
forms,
http,
httpTesting,
platformBrowser,
platformBrowserTesting,
platformBrowserDynamic,
platformServer,
platformServerTesting,
platformWebworker,
platformWebworkerDynamic,
router,
routerTesting,
serviceWorker,
upgrade,
};

View File

@ -0,0 +1,30 @@
{
"name": "angular-integration",
"description": "Assert that users with TypeScript 2.6 can type-check an Angular application",
"version": "0.0.0",
"license": "MIT",
"dependencies": {
"@angular/animations": "file:../../dist/packages-dist/animations",
"@angular/common": "file:../../dist/packages-dist/common",
"@angular/compiler": "file:../../dist/packages-dist/compiler",
"@angular/compiler-cli": "file:../../dist/packages-dist/compiler-cli",
"@angular/core": "file:../../dist/packages-dist/core",
"@angular/forms": "file:../../dist/packages-dist/forms",
"@angular/http": "file:../../dist/packages-dist/http",
"@angular/platform-browser": "file:../../dist/packages-dist/platform-browser",
"@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic",
"@angular/platform-server": "file:../../dist/packages-dist/platform-server",
"@angular/platform-webworker": "file:../../dist/packages-dist/platform-webworker",
"@angular/platform-webworker-dynamic": "file:../../dist/packages-dist/platform-webworker-dynamic",
"@angular/router": "file:../../dist/packages-dist/router",
"@angular/service-worker": "file:../../dist/packages-dist/service-worker",
"@angular/upgrade": "file:../../dist/packages-dist/upgrade",
"@types/jasmine": "2.5.41",
"rxjs": "file:../../node_modules/rxjs",
"typescript": "2.6.x",
"zone.js": "file:../../node_modules/zone.js"
},
"scripts": {
"test": "tsc"
}
}

View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"outDir": "../../dist/typings_test_ts26/",
"rootDir": ".",
"target": "es5",
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.iterable",
"es2015.promise"
],
"types": [],
"strictNullChecks": true
},
"files": [
"include-all.ts",
"node_modules/@types/jasmine/index.d.ts"
]
}

View File

@ -96,11 +96,11 @@
"source-map-support": "0.4.18", "source-map-support": "0.4.18",
"systemjs": "0.18.10", "systemjs": "0.18.10",
"ts-api-guardian": "0.2.2", "ts-api-guardian": "0.2.2",
"tsickle": "0.25.5", "tsickle": "0.26.0",
"tslint": "5.7.0", "tslint": "5.7.0",
"tslint-eslint-rules": "4.1.1", "tslint-eslint-rules": "4.1.1",
"tsutils": "2.12.1", "tsutils": "2.12.1",
"typescript": "2.5.x", "typescript": "2.6.x",
"uglify-js": "2.8.29", "uglify-js": "2.8.29",
"universal-analytics": "0.4.15", "universal-analytics": "0.4.15",
"vlq": "0.2.2", "vlq": "0.2.2",

View File

@ -6,7 +6,7 @@
"license": "MIT", "license": "MIT",
"peerDependencies": { "peerDependencies": {
"@angular/compiler-cli": "0.0.0-PLACEHOLDER", "@angular/compiler-cli": "0.0.0-PLACEHOLDER",
"typescript": ">=2.4.2 <2.6" "typescript": ">=2.4.2 <2.7"
}, },
"dependencies": { "dependencies": {
"@types/node": "6.0.84" "@types/node": "6.0.84"

View File

@ -9,6 +9,13 @@
// THIS CODE IS GENERATED - DO NOT MODIFY // THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js // See angular/tools/gulp-tasks/cldr/extract.js
function converter(n: number): number {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
export default [ export default [
'en', 'en',
[ [
@ -42,11 +49,5 @@ export default [
'{1} \'at\' {0}', '{1} \'at\' {0}',
], ],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], '$', 'US Dollar', ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], '$', 'US Dollar', converter
function(n: number):
number {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
]; ];

View File

@ -11,11 +11,11 @@
"dependencies": { "dependencies": {
"reflect-metadata": "^0.1.2", "reflect-metadata": "^0.1.2",
"minimist": "^1.2.0", "minimist": "^1.2.0",
"tsickle": "^0.25.5", "tsickle": "^0.26.0",
"chokidar": "^1.4.2" "chokidar": "^1.4.2"
}, },
"peerDependencies": { "peerDependencies": {
"typescript": ">=2.4.2 <2.6", "typescript": ">=2.4.2 <2.7",
"@angular/compiler": "0.0.0-PLACEHOLDER" "@angular/compiler": "0.0.0-PLACEHOLDER"
}, },
"repository": { "repository": {

View File

@ -16,7 +16,8 @@ export interface TypeCheckHost {
parseSourceSpanOf(fileName: string, line: number, character: number): ParseSourceSpan|null; parseSourceSpanOf(fileName: string, line: number, character: number): ParseSourceSpan|null;
} }
export function translateDiagnostics(host: TypeCheckHost, untranslatedDiagnostics: ts.Diagnostic[]): export function translateDiagnostics(
host: TypeCheckHost, untranslatedDiagnostics: ReadonlyArray<ts.Diagnostic>):
{ts: ts.Diagnostic[], ng: Diagnostic[]} { {ts: ts.Diagnostic[], ng: Diagnostic[]} {
const ts: ts.Diagnostic[] = []; const ts: ts.Diagnostic[] = [];
const ng: Diagnostic[] = []; const ng: Diagnostic[] = [];

View File

@ -38,6 +38,7 @@ export function main(
return reportErrorsAndExit(compileDiags, options, consoleError); return reportErrorsAndExit(compileDiags, options, consoleError);
} }
function createEmitCallback(options: api.CompilerOptions): api.TsEmitCallback|undefined { function createEmitCallback(options: api.CompilerOptions): api.TsEmitCallback|undefined {
const transformDecorators = options.annotationsAs !== 'decorators'; const transformDecorators = options.annotationsAs !== 'decorators';
const transformTypesToClosure = options.annotateForClosureCompiler; const transformTypesToClosure = options.annotateForClosureCompiler;
@ -50,7 +51,10 @@ function createEmitCallback(options: api.CompilerOptions): api.TsEmitCallback|un
// as TypeScript elided the import. // as TypeScript elided the import.
options.emitDecoratorMetadata = true; options.emitDecoratorMetadata = true;
} }
const tsickleHost: tsickle.TsickleHost = { const tsickleHost: Pick<
tsickle.TsickleHost, 'shouldSkipTsickleProcessing'|'pathToModuleName'|
'shouldIgnoreWarningsForPath'|'fileNameToModuleId'|'googmodule'|'untyped'|
'convertIndexImportShorthand'|'transformDecorators'|'transformTypesToClosure'> = {
shouldSkipTsickleProcessing: (fileName) => shouldSkipTsickleProcessing: (fileName) =>
/\.d\.ts$/.test(fileName) || GENERATED_FILES.test(fileName), /\.d\.ts$/.test(fileName) || GENERATED_FILES.test(fileName),
pathToModuleName: (context, importPath) => '', pathToModuleName: (context, importPath) => '',
@ -72,8 +76,8 @@ function createEmitCallback(options: api.CompilerOptions): api.TsEmitCallback|un
options options
}) => }) =>
tsickle.emitWithTsickle( tsickle.emitWithTsickle(
program, tsickleHost, host, options, targetSourceFile, writeFile, program, {...tsickleHost, options, host}, host, options, targetSourceFile,
cancellationToken, emitOnlyDtsFiles, { writeFile, cancellationToken, emitOnlyDtsFiles, {
beforeTs: customTransformers.before, beforeTs: customTransformers.before,
afterTs: customTransformers.after, afterTs: customTransformers.after,
}); });

View File

@ -44,7 +44,8 @@ function createSyntheticIndexHost<H extends ts.CompilerHost>(
newHost.writeFile = newHost.writeFile =
(fileName: string, data: string, writeByteOrderMark: boolean, (fileName: string, data: string, writeByteOrderMark: boolean,
onError?: (message: string) => void, sourceFiles?: ts.SourceFile[]) => { onError: ((message: string) => void) | undefined,
sourceFiles: Readonly<ts.SourceFile>[]) => {
delegate.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); delegate.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
if (fileName.match(DTS) && sourceFiles && sourceFiles.length == 1 && if (fileName.match(DTS) && sourceFiles && sourceFiles.length == 1 &&
path.normalize(sourceFiles[0].fileName) == normalSyntheticIndexName) { path.normalize(sourceFiles[0].fileName) == normalSyntheticIndexName) {
@ -57,7 +58,7 @@ function createSyntheticIndexHost<H extends ts.CompilerHost>(
} }
export function createBundleIndexHost<H extends ts.CompilerHost>( export function createBundleIndexHost<H extends ts.CompilerHost>(
ngOptions: CompilerOptions, rootFiles: string[], ngOptions: CompilerOptions, rootFiles: ReadonlyArray<string>,
host: H): {host: H, indexName?: string, errors?: ts.Diagnostic[]} { host: H): {host: H, indexName?: string, errors?: ts.Diagnostic[]} {
const files = rootFiles.filter(f => !DTS.test(f)); const files = rootFiles.filter(f => !DTS.test(f));
if (files.length != 1) { if (files.length != 1) {
@ -86,4 +87,4 @@ export function createBundleIndexHost<H extends ts.CompilerHost>(
const content = privateEntriesToIndex(libraryIndex, metadataBundle.privates); const content = privateEntriesToIndex(libraryIndex, metadataBundle.privates);
host = createSyntheticIndexHost(host, {name, content, metadata}); host = createSyntheticIndexHost(host, {name, content, metadata});
return {host, indexName: name}; return {host, indexName: name};
} }

View File

@ -563,7 +563,7 @@ export class MetadataBundler {
private convertExpressionNode(moduleName: string, value: MetadataSymbolicExpression): private convertExpressionNode(moduleName: string, value: MetadataSymbolicExpression):
MetadataSymbolicExpression { MetadataSymbolicExpression {
const result: MetadataSymbolicExpression = {__symbolic: value.__symbolic}; const result: MetadataSymbolicExpression = { __symbolic: value.__symbolic } as any;
for (const key in value) { for (const key in value) {
(result as any)[key] = this.convertValue(moduleName, (value as any)[key]); (result as any)[key] = this.convertValue(moduleName, (value as any)[key]);
} }
@ -598,7 +598,7 @@ export class CompilerHostAdapter implements MetadataBundlerHost {
getMetadataFor(fileName: string): ModuleMetadata|undefined { getMetadataFor(fileName: string): ModuleMetadata|undefined {
const sourceFile = this.host.getSourceFile(fileName + '.ts', ts.ScriptTarget.Latest); const sourceFile = this.host.getSourceFile(fileName + '.ts', ts.ScriptTarget.Latest);
return this.collector.getMetadata(sourceFile); return sourceFile && this.collector.getMetadata(sourceFile);
} }
} }

View File

@ -99,15 +99,24 @@ export function isFunctionMetadata(value: any): value is FunctionMetadata {
} }
export type MetadataValue = string | number | boolean | undefined | null | MetadataObject | export type MetadataValue = string | number | boolean | undefined | null | MetadataObject |
MetadataArray | MetadataSymbolicExpression | MetadataError; 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 interface MetadataSymbolicExpression { export type MetadataSymbolicExpression = MetadataSymbolicBinaryExpression |
__symbolic: 'binary'|'call'|'index'|'new'|'pre'|'reference'|'select'|'spread'|'if'; MetadataSymbolicIndexExpression | MetadataSymbolicIndexExpression |
} MetadataSymbolicCallExpression | MetadataSymbolicCallExpression |
MetadataSymbolicPrefixExpression | MetadataSymbolicIfExpression |
MetadataGlobalReferenceExpression | MetadataModuleReferenceExpression |
MetadataImportedSymbolReferenceExpression | MetadataImportedDefaultReferenceExpression |
MetadataSymbolicSelectExpression | MetadataSymbolicSpreadExpression;
export function isMetadataSymbolicExpression(value: any): value is MetadataSymbolicExpression { export function isMetadataSymbolicExpression(value: any): value is MetadataSymbolicExpression {
if (value) { if (value) {
switch (value.__symbolic) { switch (value.__symbolic) {
@ -126,7 +135,7 @@ export function isMetadataSymbolicExpression(value: any): value is MetadataSymbo
return false; return false;
} }
export interface MetadataSymbolicBinaryExpression extends MetadataSymbolicExpression { export interface MetadataSymbolicBinaryExpression {
__symbolic: 'binary'; __symbolic: 'binary';
operator: '&&'|'||'|'|'|'^'|'&'|'=='|'!='|'==='|'!=='|'<'|'>'|'<='|'>='|'instanceof'|'in'|'as'| operator: '&&'|'||'|'|'|'^'|'&'|'=='|'!='|'==='|'!=='|'<'|'>'|'<='|'>='|'instanceof'|'in'|'as'|
'<<'|'>>'|'>>>'|'+'|'-'|'*'|'/'|'%'|'**'; '<<'|'>>'|'>>>'|'+'|'-'|'*'|'/'|'%'|'**';
@ -138,7 +147,7 @@ export function isMetadataSymbolicBinaryExpression(value: any):
return value && value.__symbolic === 'binary'; return value && value.__symbolic === 'binary';
} }
export interface MetadataSymbolicIndexExpression extends MetadataSymbolicExpression { export interface MetadataSymbolicIndexExpression {
__symbolic: 'index'; __symbolic: 'index';
expression: MetadataValue; expression: MetadataValue;
index: MetadataValue; index: MetadataValue;
@ -148,7 +157,7 @@ export function isMetadataSymbolicIndexExpression(value: any):
return value && value.__symbolic === 'index'; return value && value.__symbolic === 'index';
} }
export interface MetadataSymbolicCallExpression extends MetadataSymbolicExpression { export interface MetadataSymbolicCallExpression {
__symbolic: 'call'|'new'; __symbolic: 'call'|'new';
expression: MetadataValue; expression: MetadataValue;
arguments?: MetadataValue[]; arguments?: MetadataValue[];
@ -158,7 +167,7 @@ export function isMetadataSymbolicCallExpression(value: any):
return value && (value.__symbolic === 'call' || value.__symbolic === 'new'); return value && (value.__symbolic === 'call' || value.__symbolic === 'new');
} }
export interface MetadataSymbolicPrefixExpression extends MetadataSymbolicExpression { export interface MetadataSymbolicPrefixExpression {
__symbolic: 'pre'; __symbolic: 'pre';
operator: '+'|'-'|'~'|'!'; operator: '+'|'-'|'~'|'!';
operand: MetadataValue; operand: MetadataValue;
@ -168,7 +177,7 @@ export function isMetadataSymbolicPrefixExpression(value: any):
return value && value.__symbolic === 'pre'; return value && value.__symbolic === 'pre';
} }
export interface MetadataSymbolicIfExpression extends MetadataSymbolicExpression { export interface MetadataSymbolicIfExpression {
__symbolic: 'if'; __symbolic: 'if';
condition: MetadataValue; condition: MetadataValue;
thenExpression: MetadataValue; thenExpression: MetadataValue;
@ -190,8 +199,7 @@ export interface MetadataSourceLocationInfo {
character?: number; character?: number;
} }
export interface MetadataGlobalReferenceExpression extends MetadataSymbolicExpression, export interface MetadataGlobalReferenceExpression extends MetadataSourceLocationInfo {
MetadataSourceLocationInfo {
__symbolic: 'reference'; __symbolic: 'reference';
name: string; name: string;
arguments?: MetadataValue[]; arguments?: MetadataValue[];
@ -201,8 +209,7 @@ export function isMetadataGlobalReferenceExpression(value: any):
return value && value.name && !value.module && isMetadataSymbolicReferenceExpression(value); return value && value.name && !value.module && isMetadataSymbolicReferenceExpression(value);
} }
export interface MetadataModuleReferenceExpression extends MetadataSymbolicExpression, export interface MetadataModuleReferenceExpression extends MetadataSourceLocationInfo {
MetadataSourceLocationInfo {
__symbolic: 'reference'; __symbolic: 'reference';
module: string; module: string;
} }
@ -212,8 +219,7 @@ export function isMetadataModuleReferenceExpression(value: any):
isMetadataSymbolicReferenceExpression(value); isMetadataSymbolicReferenceExpression(value);
} }
export interface MetadataImportedSymbolReferenceExpression extends MetadataSymbolicExpression, export interface MetadataImportedSymbolReferenceExpression extends MetadataSourceLocationInfo {
MetadataSourceLocationInfo {
__symbolic: 'reference'; __symbolic: 'reference';
module: string; module: string;
name: string; name: string;
@ -224,8 +230,7 @@ export function isMetadataImportedSymbolReferenceExpression(value: any):
return value && value.module && !!value.name && isMetadataSymbolicReferenceExpression(value); return value && value.module && !!value.name && isMetadataSymbolicReferenceExpression(value);
} }
export interface MetadataImportedDefaultReferenceExpression extends MetadataSymbolicExpression, export interface MetadataImportedDefaultReferenceExpression extends MetadataSourceLocationInfo {
MetadataSourceLocationInfo {
__symbolic: 'reference'; __symbolic: 'reference';
module: string; module: string;
default: default:
@ -245,17 +250,17 @@ export function isMetadataSymbolicReferenceExpression(value: any):
return value && value.__symbolic === 'reference'; return value && value.__symbolic === 'reference';
} }
export interface MetadataSymbolicSelectExpression extends MetadataSymbolicExpression { export interface MetadataSymbolicSelectExpression {
__symbolic: 'select'; __symbolic: 'select';
expression: MetadataValue; expression: MetadataValue;
name: string; member: string;
} }
export function isMetadataSymbolicSelectExpression(value: any): export function isMetadataSymbolicSelectExpression(value: any):
value is MetadataSymbolicSelectExpression { value is MetadataSymbolicSelectExpression {
return value && value.__symbolic === 'select'; return value && value.__symbolic === 'select';
} }
export interface MetadataSymbolicSpreadExpression extends MetadataSymbolicExpression { export interface MetadataSymbolicSpreadExpression {
__symbolic: 'spread'; __symbolic: 'spread';
expression: MetadataValue; expression: MetadataValue;
} }

View File

@ -108,15 +108,15 @@ export interface LazyRoute {
export interface Program { export interface Program {
getTsProgram(): ts.Program; getTsProgram(): ts.Program;
getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken): ts.Diagnostic[]; getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<ts.Diagnostic>;
getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken): Diagnostic[]; getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<Diagnostic>;
getTsSyntacticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken): getTsSyntacticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken):
ts.Diagnostic[]; ReadonlyArray<ts.Diagnostic>;
getNgStructuralDiagnostics(cancellationToken?: ts.CancellationToken): Diagnostic[]; getNgStructuralDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<Diagnostic>;
getTsSemanticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken): getTsSemanticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken):
ts.Diagnostic[]; ReadonlyArray<ts.Diagnostic>;
getNgSemanticDiagnostics(fileName?: string, cancellationToken?: ts.CancellationToken): getNgSemanticDiagnostics(fileName?: string, cancellationToken?: ts.CancellationToken):
Diagnostic[]; ReadonlyArray<Diagnostic>;
loadNgStructureAsync(): Promise<void>; loadNgStructureAsync(): Promise<void>;
listLazyRoutes(entryRoute?: string): LazyRoute[]; listLazyRoutes(entryRoute?: string): LazyRoute[];
emit({emitFlags, cancellationToken, customTransformers, emitCallback}: { emit({emitFlags, cancellationToken, customTransformers, emitCallback}: {
@ -132,7 +132,7 @@ export function createProgram(
{rootNames, options, host, oldProgram}: {rootNames, options, host, oldProgram}:
{rootNames: string[], options: CompilerOptions, host: CompilerHost, oldProgram?: Program}): {rootNames: string[], options: CompilerOptions, host: CompilerHost, oldProgram?: Program}):
Program { Program {
return createProgramOrig({rootNames, options, host, oldProgram: oldProgram as ProgramOrig}); return createProgramOrig({rootNames, options, host, oldProgram: oldProgram as any});
} }
// Wrapper for createCompilerHost. // Wrapper for createCompilerHost.
@ -143,7 +143,7 @@ export function createCompilerHost(
} }
// Wrapper for formatDiagnostics. // Wrapper for formatDiagnostics.
export type Diagnostics = Array<ts.Diagnostic|Diagnostic>; export type Diagnostics = ReadonlyArray<ts.Diagnostic|Diagnostic>;
export function formatDiagnostics(diags: Diagnostics): string { export function formatDiagnostics(diags: Diagnostics): string {
return formatDiagnosticsOrig(diags); return formatDiagnosticsOrig(diags);
} }

View File

@ -17,7 +17,7 @@ import {createMessageDiagnostic} from './transformers/util';
const TS_EXT = /\.ts$/; const TS_EXT = /\.ts$/;
export type Diagnostics = Array<ts.Diagnostic|api.Diagnostic>; export type Diagnostics = ReadonlyArray<ts.Diagnostic|api.Diagnostic>;
export function filterErrorsAndWarnings(diagnostics: Diagnostics): Diagnostics { export function filterErrorsAndWarnings(diagnostics: Diagnostics): Diagnostics {
return diagnostics.filter(d => d.category !== ts.DiagnosticCategory.Message); return diagnostics.filter(d => d.category !== ts.DiagnosticCategory.Message);
@ -199,7 +199,7 @@ export function performCompilation({rootNames, options, host, oldProgram, emitCa
}): PerformCompilationResult { }): PerformCompilationResult {
let program: api.Program|undefined; let program: api.Program|undefined;
let emitResult: ts.EmitResult|undefined; let emitResult: ts.EmitResult|undefined;
let allDiagnostics: Diagnostics = []; let allDiagnostics: Array<ts.Diagnostic|api.Diagnostic> = [];
try { try {
if (!host) { if (!host) {
host = ng.createCompilerHost({options}); host = ng.createCompilerHost({options});
@ -240,7 +240,7 @@ export function performCompilation({rootNames, options, host, oldProgram, emitCa
} }
} }
function defaultGatherDiagnostics(program: api.Program): Diagnostics { function defaultGatherDiagnostics(program: api.Program): Diagnostics {
const allDiagnostics: Diagnostics = []; const allDiagnostics: Array<ts.Diagnostic|api.Diagnostic> = [];
function checkDiagnostics(diags: Diagnostics | undefined) { function checkDiagnostics(diags: Diagnostics | undefined) {
if (diags) { if (diags) {
@ -257,7 +257,7 @@ function defaultGatherDiagnostics(program: api.Program): Diagnostics {
// Check syntactic diagnostics // Check syntactic diagnostics
checkOtherDiagnostics = checkOtherDiagnostics =
checkOtherDiagnostics && checkDiagnostics(program.getTsSyntacticDiagnostics()); checkOtherDiagnostics && checkDiagnostics(program.getTsSyntacticDiagnostics() as Diagnostics);
// Check TypeScript semantic and Angular structure diagnostics // Check TypeScript semantic and Angular structure diagnostics
checkOtherDiagnostics = checkOtherDiagnostics =
@ -267,7 +267,7 @@ function defaultGatherDiagnostics(program: api.Program): Diagnostics {
// Check Angular semantic diagnostics // Check Angular semantic diagnostics
checkOtherDiagnostics = checkOtherDiagnostics =
checkOtherDiagnostics && checkDiagnostics(program.getNgSemanticDiagnostics()); checkOtherDiagnostics && checkDiagnostics(program.getNgSemanticDiagnostics() as Diagnostics);
return allDiagnostics; return allDiagnostics;
} }

View File

@ -161,7 +161,7 @@ export function performWatchCompilation(host: PerformWatchHost):
const originalWriteFileCallback = cachedCompilerHost.writeFile; const originalWriteFileCallback = cachedCompilerHost.writeFile;
cachedCompilerHost.writeFile = function( cachedCompilerHost.writeFile = function(
fileName: string, data: string, writeByteOrderMark: boolean, fileName: string, data: string, writeByteOrderMark: boolean,
onError?: (message: string) => void, sourceFiles?: ts.SourceFile[]) { onError?: (message: string) => void, sourceFiles: ReadonlyArray<ts.SourceFile> = []) {
ingoreFilesForWatch.add(path.normalize(fileName)); ingoreFilesForWatch.add(path.normalize(fileName));
return originalWriteFileCallback(fileName, data, writeByteOrderMark, onError, sourceFiles); return originalWriteFileCallback(fileName, data, writeByteOrderMark, onError, sourceFiles);
}; };
@ -275,4 +275,4 @@ export function performWatchCompilation(host: PerformWatchHost):
[createMessageDiagnostic('File change detected. Starting incremental compilation.')]); [createMessageDiagnostic('File change detected. Starting incremental compilation.')]);
doCompilation(); doCompilation();
} }
} }

View File

@ -266,12 +266,12 @@ export interface Program {
* faster than calling `getTsProgram().getOptionsDiagnostics()` since it does not need to * faster than calling `getTsProgram().getOptionsDiagnostics()` since it does not need to
* collect Angular structural information to produce the errors. * collect Angular structural information to produce the errors.
*/ */
getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken): ts.Diagnostic[]; getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<ts.Diagnostic>;
/** /**
* Retrieve options diagnostics for the Angular options used to create the program. * Retrieve options diagnostics for the Angular options used to create the program.
*/ */
getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken): Diagnostic[]; getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<Diagnostic>;
/** /**
* Retrieve the syntax diagnostics from TypeScript. This is faster than calling * Retrieve the syntax diagnostics from TypeScript. This is faster than calling
@ -279,7 +279,7 @@ export interface Program {
* information to produce the errors. * information to produce the errors.
*/ */
getTsSyntacticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken): getTsSyntacticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken):
ts.Diagnostic[]; ReadonlyArray<ts.Diagnostic>;
/** /**
* Retrieve the diagnostics for the structure of an Angular application is correctly formed. * Retrieve the diagnostics for the structure of an Angular application is correctly formed.
@ -292,14 +292,14 @@ export interface Program {
* *
* Angular structural information is required to produce these diagnostics. * Angular structural information is required to produce these diagnostics.
*/ */
getNgStructuralDiagnostics(cancellationToken?: ts.CancellationToken): Diagnostic[]; getNgStructuralDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<Diagnostic>;
/** /**
* Retrieve the semantic diagnostics from TypeScript. This is equivilent to calling * Retrieve the semantic diagnostics from TypeScript. This is equivilent to calling
* `getTsProgram().getSemanticDiagnostics()` directly and is included for completeness. * `getTsProgram().getSemanticDiagnostics()` directly and is included for completeness.
*/ */
getTsSemanticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken): getTsSemanticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken):
ts.Diagnostic[]; ReadonlyArray<ts.Diagnostic>;
/** /**
* Retrieve the Angular semantic diagnostics. * Retrieve the Angular semantic diagnostics.
@ -307,7 +307,7 @@ export interface Program {
* Angular structural information is required to produce these diagnostics. * Angular structural information is required to produce these diagnostics.
*/ */
getNgSemanticDiagnostics(fileName?: string, cancellationToken?: ts.CancellationToken): getNgSemanticDiagnostics(fileName?: string, cancellationToken?: ts.CancellationToken):
Diagnostic[]; ReadonlyArray<Diagnostic>;
/** /**
* Load Angular structural information asynchronously. If this method is not called then the * Load Angular structural information asynchronously. If this method is not called then the

View File

@ -62,7 +62,7 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos
private flatModuleIndexRedirectNames = new Set<string>(); private flatModuleIndexRedirectNames = new Set<string>();
private rootDirs: string[]; private rootDirs: string[];
private moduleResolutionCache: ts.ModuleResolutionCache; private moduleResolutionCache: ts.ModuleResolutionCache;
private originalSourceFiles = new Map<string, ts.SourceFile|undefined>(); private originalSourceFiles = new Map<string, ts.SourceFile|null>();
private originalFileExistsCache = new Map<string, boolean>(); private originalFileExistsCache = new Map<string, boolean>();
private generatedSourceFiles = new Map<string, GenSourceFile>(); private generatedSourceFiles = new Map<string, GenSourceFile>();
private generatedCodeFor = new Map<string, string[]>(); private generatedCodeFor = new Map<string, string[]>();
@ -76,8 +76,9 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos
directoryExists?: (directoryName: string) => boolean; directoryExists?: (directoryName: string) => boolean;
constructor( constructor(
private rootFiles: string[], private options: CompilerOptions, private context: CompilerHost, private rootFiles: ReadonlyArray<string>, private options: CompilerOptions,
private metadataProvider: MetadataProvider, private codeGenerator: CodeGenerator, private context: CompilerHost, private metadataProvider: MetadataProvider,
private codeGenerator: CodeGenerator,
private librarySummaries = new Map<string, LibrarySummary>()) { private librarySummaries = new Map<string, LibrarySummary>()) {
this.moduleResolutionCache = ts.createModuleResolutionCache( this.moduleResolutionCache = ts.createModuleResolutionCache(
this.context.getCurrentDirectory !(), this.context.getCanonicalFileName.bind(this.context)); this.context.getCurrentDirectory !(), this.context.getCanonicalFileName.bind(this.context));
@ -565,7 +566,8 @@ function addReferencesToSourceFile(sf: ts.SourceFile, genFileNames: string[]) {
// value for `referencedFiles` around in cache the original host is caching ts.SourceFiles. // value for `referencedFiles` around in cache the original host is caching ts.SourceFiles.
// Note: cloning the ts.SourceFile is expensive as the nodes in have parent pointers, // Note: cloning the ts.SourceFile is expensive as the nodes in have parent pointers,
// i.e. we would also need to clone and adjust all nodes. // i.e. we would also need to clone and adjust all nodes.
let originalReferencedFiles: ts.FileReference[]|undefined = (sf as any).originalReferencedFiles; let originalReferencedFiles: ReadonlyArray<ts.FileReference> =
(sf as any).originalReferencedFiles;
if (!originalReferencedFiles) { if (!originalReferencedFiles) {
originalReferencedFiles = sf.referencedFiles; originalReferencedFiles = sf.referencedFiles;
(sf as any).originalReferencedFiles = originalReferencedFiles; (sf as any).originalReferencedFiles = originalReferencedFiles;

View File

@ -40,6 +40,7 @@ const defaultEmitCallback: TsEmitCallback =
targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
class AngularCompilerProgram implements Program { class AngularCompilerProgram implements Program {
private rootNames: string[];
private metadataCache: LowerMetadataCache; private metadataCache: LowerMetadataCache;
private oldProgramLibrarySummaries: Map<string, LibrarySummary>|undefined; private oldProgramLibrarySummaries: Map<string, LibrarySummary>|undefined;
private oldProgramEmittedGeneratedFiles: Map<string, GeneratedFile>|undefined; private oldProgramEmittedGeneratedFiles: Map<string, GeneratedFile>|undefined;
@ -60,8 +61,9 @@ class AngularCompilerProgram implements Program {
private _optionsDiagnostics: Diagnostic[] = []; private _optionsDiagnostics: Diagnostic[] = [];
constructor( constructor(
private rootNames: string[], private options: CompilerOptions, private host: CompilerHost, rootNames: ReadonlyArray<string>, private options: CompilerOptions,
oldProgram?: Program) { private host: CompilerHost, oldProgram?: Program) {
this.rootNames = [...rootNames];
const [major, minor] = ts.version.split('.'); const [major, minor] = ts.version.split('.');
if (Number(major) < 2 || (Number(major) === 2 && Number(minor) < 4)) { if (Number(major) < 2 || (Number(major) === 2 && Number(minor) < 4)) {
throw new Error('The Angular Compiler requires TypeScript >= 2.4.'); throw new Error('The Angular Compiler requires TypeScript >= 2.4.');
@ -74,7 +76,8 @@ class AngularCompilerProgram implements Program {
} }
if (options.flatModuleOutFile) { if (options.flatModuleOutFile) {
const {host: bundleHost, indexName, errors} = createBundleIndexHost(options, rootNames, host); const {host: bundleHost, indexName, errors} =
createBundleIndexHost(options, this.rootNames, host);
if (errors) { if (errors) {
// TODO(tbosch): once we move MetadataBundler from tsc_wrapped into compiler_cli, // TODO(tbosch): once we move MetadataBundler from tsc_wrapped into compiler_cli,
// directly create ng.Diagnostic instead of using ts.Diagnostic here. // directly create ng.Diagnostic instead of using ts.Diagnostic here.
@ -85,7 +88,7 @@ class AngularCompilerProgram implements Program {
code: DEFAULT_ERROR_CODE code: DEFAULT_ERROR_CODE
}))); })));
} else { } else {
rootNames.push(indexName !); this.rootNames.push(indexName !);
this.host = bundleHost; this.host = bundleHost;
} }
} }
@ -133,21 +136,21 @@ class AngularCompilerProgram implements Program {
return this.tsProgram.getOptionsDiagnostics(cancellationToken); return this.tsProgram.getOptionsDiagnostics(cancellationToken);
} }
getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken): Diagnostic[] { getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<Diagnostic> {
return [...this._optionsDiagnostics, ...getNgOptionDiagnostics(this.options)]; return [...this._optionsDiagnostics, ...getNgOptionDiagnostics(this.options)];
} }
getTsSyntacticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken): getTsSyntacticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken):
ts.Diagnostic[] { ReadonlyArray<ts.Diagnostic> {
return this.tsProgram.getSyntacticDiagnostics(sourceFile, cancellationToken); return this.tsProgram.getSyntacticDiagnostics(sourceFile, cancellationToken);
} }
getNgStructuralDiagnostics(cancellationToken?: ts.CancellationToken): Diagnostic[] { getNgStructuralDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<Diagnostic> {
return this.structuralDiagnostics; return this.structuralDiagnostics;
} }
getTsSemanticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken): getTsSemanticDiagnostics(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken):
ts.Diagnostic[] { ReadonlyArray<ts.Diagnostic> {
const sourceFiles = sourceFile ? [sourceFile] : this.tsProgram.getSourceFiles(); const sourceFiles = sourceFile ? [sourceFile] : this.tsProgram.getSourceFiles();
let diags: ts.Diagnostic[] = []; let diags: ts.Diagnostic[] = [];
sourceFiles.forEach(sf => { sourceFiles.forEach(sf => {
@ -159,7 +162,7 @@ class AngularCompilerProgram implements Program {
} }
getNgSemanticDiagnostics(fileName?: string, cancellationToken?: ts.CancellationToken): getNgSemanticDiagnostics(fileName?: string, cancellationToken?: ts.CancellationToken):
Diagnostic[] { ReadonlyArray<Diagnostic> {
let diags: ts.Diagnostic[] = []; let diags: ts.Diagnostic[] = [];
this.tsProgram.getSourceFiles().forEach(sf => { this.tsProgram.getSourceFiles().forEach(sf => {
if (GENERATED_FILES.test(sf.fileName) && !sf.isDeclarationFile) { if (GENERATED_FILES.test(sf.fileName) && !sf.isDeclarationFile) {
@ -245,7 +248,7 @@ class AngularCompilerProgram implements Program {
const emitOnlyDtsFiles = (emitFlags & (EmitFlags.DTS | EmitFlags.JS)) == EmitFlags.DTS; const emitOnlyDtsFiles = (emitFlags & (EmitFlags.DTS | EmitFlags.JS)) == EmitFlags.DTS;
// Restore the original references before we emit so TypeScript doesn't emit // Restore the original references before we emit so TypeScript doesn't emit
// a reference to the .d.ts file. // a reference to the .d.ts file.
const augmentedReferences = new Map<ts.SourceFile, ts.FileReference[]>(); const augmentedReferences = new Map<ts.SourceFile, ReadonlyArray<ts.FileReference>>();
for (const sourceFile of this.tsProgram.getSourceFiles()) { for (const sourceFile of this.tsProgram.getSourceFiles()) {
const originalReferences = getOriginalReferences(sourceFile); const originalReferences = getOriginalReferences(sourceFile);
if (originalReferences) { if (originalReferences) {
@ -295,7 +298,8 @@ class AngularCompilerProgram implements Program {
// Restore the references back to the augmented value to ensure that the // Restore the references back to the augmented value to ensure that the
// checks that TypeScript makes for project structure reuse will succeed. // checks that TypeScript makes for project structure reuse will succeed.
for (const [sourceFile, references] of Array.from(augmentedReferences)) { for (const [sourceFile, references] of Array.from(augmentedReferences)) {
sourceFile.referencedFiles = references; // TODO(chuckj): Remove any cast after updating build to 2.6
(sourceFile as any).referencedFiles = references;
} }
} }
this.emittedSourceFiles = emittedSourceFiles; this.emittedSourceFiles = emittedSourceFiles;
@ -312,7 +316,8 @@ class AngularCompilerProgram implements Program {
if (!outSrcMapping.length) { if (!outSrcMapping.length) {
// if no files were emitted by TypeScript, also don't emit .json files // if no files were emitted by TypeScript, also don't emit .json files
emitResult.diagnostics.push(createMessageDiagnostic(`Emitted no files.`)); emitResult.diagnostics =
emitResult.diagnostics.concat([createMessageDiagnostic(`Emitted no files.`)]);
return emitResult; return emitResult;
} }
@ -346,12 +351,12 @@ class AngularCompilerProgram implements Program {
} }
const emitEnd = Date.now(); const emitEnd = Date.now();
if (this.options.diagnostics) { if (this.options.diagnostics) {
emitResult.diagnostics.push(createMessageDiagnostic([ emitResult.diagnostics = emitResult.diagnostics.concat([createMessageDiagnostic([
`Emitted in ${emitEnd - emitStart}ms`, `Emitted in ${emitEnd - emitStart}ms`,
`- ${emittedUserTsCount} user ts files`, `- ${emittedUserTsCount} user ts files`,
`- ${genTsFiles.length} generated ts files`, `- ${genTsFiles.length} generated ts files`,
`- ${genJsonFiles.length + metadataJsonCount} generated json files`, `- ${genJsonFiles.length + metadataJsonCount} generated json files`,
].join('\n'))); ].join('\n'))]);
} }
return emitResult; return emitResult;
} }
@ -378,7 +383,7 @@ class AngularCompilerProgram implements Program {
return this._analyzedModules !; return this._analyzedModules !;
} }
private get structuralDiagnostics(): Diagnostic[] { private get structuralDiagnostics(): ReadonlyArray<Diagnostic> {
let diagnostics = this._structuralDiagnostics; let diagnostics = this._structuralDiagnostics;
if (!diagnostics) { if (!diagnostics) {
this.initSync(); this.initSync();
@ -645,10 +650,11 @@ class AngularCompilerProgram implements Program {
} }
} }
export function createProgram( export function createProgram({rootNames, options, host, oldProgram}: {
{rootNames, options, host, oldProgram}: rootNames: ReadonlyArray<string>,
{rootNames: string[], options: CompilerOptions, host: CompilerHost, oldProgram?: Program}): options: CompilerOptions,
Program { host: CompilerHost, oldProgram?: Program
}): Program {
return new AngularCompilerProgram(rootNames, options, host, oldProgram); return new AngularCompilerProgram(rootNames, options, host, oldProgram);
} }
@ -689,7 +695,7 @@ function getAotCompilerOptions(options: CompilerOptions): AotCompilerOptions {
}; };
} }
function getNgOptionDiagnostics(options: CompilerOptions): Diagnostic[] { function getNgOptionDiagnostics(options: CompilerOptions): ReadonlyArray<Diagnostic> {
if (options.annotationsAs) { if (options.annotationsAs) {
switch (options.annotationsAs) { switch (options.annotationsAs) {
case 'decorators': case 'decorators':
@ -767,7 +773,7 @@ export function i18nExtract(
const content = i18nSerialize(bundle, formatName, options); const content = i18nSerialize(bundle, formatName, options);
const dstFile = outFile || `messages.${ext}`; 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); host.writeFile(dstPath, content, false, undefined, []);
return [dstPath]; return [dstPath];
} }

View File

@ -84,7 +84,7 @@ describe('ng type checker', () => {
}); });
describe('type narrowing', () => { describe('type narrowing', () => {
const a = (files: MockFiles, options: object = {}) => { const a = (files: MockFiles, options: ng.AngularCompilerOptions = {}) => {
accept(files, {fullTemplateTypeCheck: true, ...options}); accept(files, {fullTemplateTypeCheck: true, ...options});
}; };
@ -517,7 +517,7 @@ describe('ng type checker', () => {
}); });
describe('casting $any', () => { describe('casting $any', () => {
const a = (files: MockFiles, options: object = {}) => { const a = (files: MockFiles, options: ng.AngularCompilerOptions = {}) => {
accept( accept(
{'src/app.component.ts': '', 'src/lib.ts': '', ...files}, {'src/app.component.ts': '', 'src/lib.ts': '', ...files},
{fullTemplateTypeCheck: true, ...options}); {fullTemplateTypeCheck: true, ...options});
@ -525,7 +525,7 @@ describe('ng type checker', () => {
const r = const r =
(message: string | RegExp, location: RegExp | null, files: MockFiles, (message: string | RegExp, location: RegExp | null, files: MockFiles,
options: object = {}) => { options: ng.AngularCompilerOptions = {}) => {
reject( reject(
message, location, {'src/app.component.ts': '', 'src/lib.ts': '', ...files}, message, location, {'src/app.component.ts': '', 'src/lib.ts': '', ...files},
{fullTemplateTypeCheck: true, ...options}); {fullTemplateTypeCheck: true, ...options});
@ -621,7 +621,7 @@ describe('ng type checker', () => {
}); });
describe('regressions ', () => { describe('regressions ', () => {
const a = (files: MockFiles, options: object = {}) => { const a = (files: MockFiles, options: ng.AngularCompilerOptions = {}) => {
accept(files, {fullTemplateTypeCheck: true, ...options}); accept(files, {fullTemplateTypeCheck: true, ...options});
}; };

View File

@ -22,38 +22,21 @@ describe('Collector', () => {
beforeEach(() => { beforeEach(() => {
host = new Host(FILES, [ host = new Host(FILES, [
'/app/app.component.ts', '/app/app.component.ts', '/app/cases-data.ts',
'/app/cases-data.ts', '/app/error-cases.ts', '/promise.ts',
'/app/error-cases.ts', '/unsupported-1.ts', '/unsupported-2.ts',
'/promise.ts', '/unsupported-3.ts', 'class-arity.ts',
'/unsupported-1.ts', 'declarations.d.ts', 'import-star.ts',
'/unsupported-2.ts', 'exported-classes.ts', 'exported-functions.ts',
'/unsupported-3.ts', 'exported-enum.ts', 'exported-type.ts',
'class-arity.ts', 'exported-consts.ts', 'local-symbol-ref.ts',
'declarations.d.ts', 'local-function-ref.ts', 'local-symbol-ref-func.ts',
'import-star.ts', 'private-enum.ts', 're-exports.ts',
'exported-classes.ts', 're-exports-2.ts', 'export-as.d.ts',
'exported-functions.ts', 'named-module.d.ts', 'static-field-reference.ts',
'exported-enum.ts', 'static-method.ts', 'static-method-call.ts',
'exported-type.ts', 'static-method-with-if.ts', 'static-method-with-default.ts',
'exported-consts.ts', 'class-inheritance.ts', 'class-inheritance-parent.ts',
'local-symbol-ref.ts',
'local-function-ref.ts',
'local-symbol-ref-func.ts',
'local-symbol-ref-func-dynamic.ts',
'private-enum.ts',
're-exports.ts',
're-exports-2.ts',
'export-as.d.ts',
'named-module.d.ts',
'static-field-reference.ts',
'static-method.ts',
'static-method-call.ts',
'static-method-with-if.ts',
'static-method-with-default.ts',
'class-inheritance.ts',
'class-inheritance-parent.ts',
'class-inheritance-declarations.d.ts',
'interface-reference.ts' 'interface-reference.ts'
]); ]);
service = ts.createLanguageService(host, documentRegistry); service = ts.createLanguageService(host, documentRegistry);

View File

@ -91,7 +91,8 @@ describe('Symbols', () => {
}); });
it('should be able to resolve any symbol in core global scope', () => { it('should be able to resolve any symbol in core global scope', () => {
const core = program.getSourceFiles().find(source => source.fileName.endsWith('lib.d.ts')); const core = (program.getSourceFiles() as ts.SourceFile[])
.find(source => source.fileName.endsWith('lib.d.ts'));
expect(core).toBeDefined(); expect(core).toBeDefined();
const visit = (node: ts.Node): boolean => { const visit = (node: ts.Node): boolean => {
switch (node.kind) { switch (node.kind) {

View File

@ -161,6 +161,9 @@ export function expectNoDiagnostics(diagnostics: ts.Diagnostic[]) {
const {line, character} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); const {line, character} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
// tslint:disable-next-line:no-console // tslint:disable-next-line:no-console
console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
} else {
// tslint:disable-next-line:no-console
console.log(message);
} }
} }
expect(diagnostics.length).toBe(0); expect(diagnostics.length).toBe(0);

View File

@ -684,7 +684,7 @@ describe('ngc transformer command-line', () => {
expect(exitCode).toEqual(0); expect(exitCode).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js'); const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8'); const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain(`import { A } from "submodule"`); expect(mymoduleSource).toContain(`import { A } from 'submodule'`);
}); });
describe('expression lowering', () => { describe('expression lowering', () => {

View File

@ -166,10 +166,10 @@ class MockWatchHost {
nextTimeoutListenerId = 1; nextTimeoutListenerId = 1;
timeoutListeners: {[id: string]: (() => void)} = {}; timeoutListeners: {[id: string]: (() => void)} = {};
fileChangeListeners: Array<((event: FileChangeEvent, fileName: string) => void)|null> = []; fileChangeListeners: Array<((event: FileChangeEvent, fileName: string) => void)|null> = [];
diagnostics: ng.Diagnostics = []; diagnostics: ng.Diagnostic[] = [];
constructor(public config: ng.ParsedConfiguration) {} constructor(public config: ng.ParsedConfiguration) {}
reportDiagnostics(diags: ng.Diagnostics) { this.diagnostics.push(...diags); } reportDiagnostics(diags: ng.Diagnostics) { this.diagnostics.push(...(diags as ng.Diagnostic[])); }
readConfiguration() { return this.config; } readConfiguration() { return this.config; }
createCompilerHost(options: ng.CompilerOptions) { return ng.createCompilerHost({options}); } createCompilerHost(options: ng.CompilerOptions) { return ng.createCompilerHost({options}); }
createEmitCallback() { return undefined; } createEmitCallback() { return undefined; }

View File

@ -431,14 +431,15 @@ describe('ng program', () => {
}); });
const host = ng.createCompilerHost({options}); const host = ng.createCompilerHost({options});
const written = new Map < string, { const written = new Map < string, {
original: ts.SourceFile[]|undefined; original: ReadonlyArray<ts.SourceFile>|undefined;
data: string; data: string;
} }
> (); > ();
host.writeFile = host.writeFile =
(fileName: string, data: string, writeByteOrderMark: boolean, (fileName: string, data: string, writeByteOrderMark: boolean,
onError?: (message: string) => void, sourceFiles?: ts.SourceFile[]) => { onError: (message: string) => void|undefined,
sourceFiles: ReadonlyArray<ts.SourceFile>) => {
written.set(fileName, {original: sourceFiles, data}); written.set(fileName, {original: sourceFiles, data});
}; };
const program = ng.createProgram( const program = ng.createProgram(
@ -510,9 +511,9 @@ describe('ng program', () => {
const host = ng.createCompilerHost({options}); const host = ng.createCompilerHost({options});
const writtenFileNames: string[] = []; const writtenFileNames: string[] = [];
const oldWriteFile = host.writeFile; const oldWriteFile = host.writeFile;
host.writeFile = (fileName, data, writeByteOrderMark) => { host.writeFile = (fileName, data, writeByteOrderMark, onError, sourceFiles) => {
writtenFileNames.push(fileName); writtenFileNames.push(fileName);
oldWriteFile(fileName, data, writeByteOrderMark); oldWriteFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
}; };
compile(/*oldProgram*/ undefined, options, /*rootNames*/ undefined, host); compile(/*oldProgram*/ undefined, options, /*rootNames*/ undefined, host);

View File

@ -172,7 +172,7 @@ export class EmittingCompilerHost implements ts.CompilerHost {
writeFile: ts.WriteFileCallback = writeFile: ts.WriteFileCallback =
(fileName: string, data: string, writeByteOrderMark: boolean, (fileName: string, data: string, writeByteOrderMark: boolean,
onError?: (message: string) => void, sourceFiles?: ts.SourceFile[]) => { onError?: (message: string) => void, sourceFiles?: ReadonlyArray<ts.SourceFile>) => {
this.addWrittenFile(fileName, data); this.addWrittenFile(fileName, data);
if (this.options.emitMetadata && sourceFiles && sourceFiles.length && DTS.test(fileName)) { if (this.options.emitMetadata && sourceFiles && sourceFiles.length && DTS.test(fileName)) {
const metadataFilePath = fileName.replace(DTS, '.metadata.json'); const metadataFilePath = fileName.replace(DTS, '.metadata.json');
@ -430,7 +430,7 @@ export class MockMetadataBundlerHost implements MetadataBundlerHost {
getMetadataFor(moduleName: string): ModuleMetadata|undefined { getMetadataFor(moduleName: string): ModuleMetadata|undefined {
const source = this.host.getSourceFile(moduleName + '.ts', ts.ScriptTarget.Latest); const source = this.host.getSourceFile(moduleName + '.ts', ts.ScriptTarget.Latest);
return this.collector.getMetadata(source); return source && this.collector.getMetadata(source);
} }
} }
@ -603,7 +603,7 @@ export function expectNoDiagnostics(program: ts.Program) {
return ''; return '';
} }
function expectNoDiagnostics(diagnostics: ts.Diagnostic[]) { function expectNoDiagnostics(diagnostics: ReadonlyArray<ts.Diagnostic>) {
if (diagnostics && diagnostics.length) { if (diagnostics && diagnostics.length) {
throw new Error( throw new Error(
'Errors from TypeScript:\n' + 'Errors from TypeScript:\n' +

View File

@ -64,13 +64,15 @@ function angularOnlyFilter(ls: ts.LanguageService): ts.LanguageService {
getFormattingEditsAfterKeystroke: (fileName, position, key, options) => <ts.TextChange[]>[], getFormattingEditsAfterKeystroke: (fileName, position, key, options) => <ts.TextChange[]>[],
getDocCommentTemplateAtPosition: (fileName, position) => <ts.TextInsertion><any>undefined, getDocCommentTemplateAtPosition: (fileName, position) => <ts.TextInsertion><any>undefined,
isValidBraceCompletionAtPosition: (fileName, position, openingBrace) => <boolean><any>undefined, isValidBraceCompletionAtPosition: (fileName, position, openingBrace) => <boolean><any>undefined,
getSpanOfEnclosingComment: (fileName, position, onlyMultiLine) => <ts.TextSpan><any>undefined,
getCodeFixesAtPosition: (fileName, start, end, errorCodes) => <ts.CodeAction[]>[], getCodeFixesAtPosition: (fileName, start, end, errorCodes) => <ts.CodeAction[]>[],
applyCodeActionCommand: (action: any) => <any>Promise.resolve(undefined),
getEmitOutput: fileName => <ts.EmitOutput><any>undefined, getEmitOutput: fileName => <ts.EmitOutput><any>undefined,
getProgram: () => ls.getProgram(), getProgram: () => ls.getProgram(),
dispose: () => ls.dispose(), dispose: () => ls.dispose(),
getApplicableRefactors: (fileName, positionOrRaneg) => <ts.ApplicableRefactorInfo[]>[], getApplicableRefactors: (fileName, positionOrRaneg) => <ts.ApplicableRefactorInfo[]>[],
getEditsForRefactor: (fileName, formatOptions, positionOrRange, refactorName, actionName) => getEditsForRefactor: (fileName, formatOptions, positionOrRange, refactorName, actionName) =>
undefined, undefined
}; };
} }
@ -130,9 +132,9 @@ export function create(info: any /* ts.server.PluginCreateInfo */): ts.LanguageS
getSemanticClassifications: tryFilenameOneCall(ls.getSemanticClassifications), getSemanticClassifications: tryFilenameOneCall(ls.getSemanticClassifications),
getEncodedSyntacticClassifications: tryFilenameOneCall(ls.getEncodedSyntacticClassifications), getEncodedSyntacticClassifications: tryFilenameOneCall(ls.getEncodedSyntacticClassifications),
getEncodedSemanticClassifications: tryFilenameOneCall(ls.getEncodedSemanticClassifications), getEncodedSemanticClassifications: tryFilenameOneCall(ls.getEncodedSemanticClassifications),
getCompletionsAtPosition: tryFilenameOneCall(ls.getCompletionsAtPosition), getCompletionsAtPosition: tryFilenameTwoCall(ls.getCompletionsAtPosition),
getCompletionEntryDetails: tryFilenameTwoCall(ls.getCompletionEntryDetails), getCompletionEntryDetails: tryFilenameFourCall(ls.getCompletionEntryDetails),
getCompletionEntrySymbol: tryFilenameTwoCall(ls.getCompletionEntrySymbol), getCompletionEntrySymbol: tryFilenameThreeCall(ls.getCompletionEntrySymbol),
getQuickInfoAtPosition: tryFilenameOneCall(ls.getQuickInfoAtPosition), getQuickInfoAtPosition: tryFilenameOneCall(ls.getQuickInfoAtPosition),
getNameOrDottedNameSpan: tryFilenameTwoCall(ls.getNameOrDottedNameSpan), getNameOrDottedNameSpan: tryFilenameTwoCall(ls.getNameOrDottedNameSpan),
getBreakpointStatementAtPosition: tryFilenameOneCall(ls.getBreakpointStatementAtPosition), getBreakpointStatementAtPosition: tryFilenameOneCall(ls.getBreakpointStatementAtPosition),
@ -162,13 +164,15 @@ export function create(info: any /* ts.server.PluginCreateInfo */): ts.LanguageS
getFormattingEditsAfterKeystroke: tryFilenameThreeCall(ls.getFormattingEditsAfterKeystroke), getFormattingEditsAfterKeystroke: tryFilenameThreeCall(ls.getFormattingEditsAfterKeystroke),
getDocCommentTemplateAtPosition: tryFilenameOneCall(ls.getDocCommentTemplateAtPosition), getDocCommentTemplateAtPosition: tryFilenameOneCall(ls.getDocCommentTemplateAtPosition),
isValidBraceCompletionAtPosition: tryFilenameTwoCall(ls.isValidBraceCompletionAtPosition), isValidBraceCompletionAtPosition: tryFilenameTwoCall(ls.isValidBraceCompletionAtPosition),
getSpanOfEnclosingComment: tryFilenameTwoCall(ls.getSpanOfEnclosingComment),
getCodeFixesAtPosition: tryFilenameFourCall(ls.getCodeFixesAtPosition), getCodeFixesAtPosition: tryFilenameFourCall(ls.getCodeFixesAtPosition),
applyCodeActionCommand:
<any>((action: any) => tryCall(undefined, () => ls.applyCodeActionCommand(action))),
getEmitOutput: tryFilenameCall(ls.getEmitOutput), getEmitOutput: tryFilenameCall(ls.getEmitOutput),
getProgram: () => ls.getProgram(), getProgram: () => ls.getProgram(),
dispose: () => ls.dispose(), dispose: () => ls.dispose(),
getApplicableRefactors: (fileName, positionOrRaneg) => <ts.ApplicableRefactorInfo[]>[], getApplicableRefactors: tryFilenameOneCall(ls.getApplicableRefactors),
getEditsForRefactor: (fileName, formatOptions, positionOrRange, refactorName, actionName) => getEditsForRefactor: tryFilenameFourCall(ls.getEditsForRefactor)
undefined,
}; };
} }
@ -234,8 +238,9 @@ export function create(info: any /* ts.server.PluginCreateInfo */): ts.LanguageS
serviceHost.setSite(ls); serviceHost.setSite(ls);
projectHostMap.set(info.project, serviceHost); projectHostMap.set(info.project, serviceHost);
proxy.getCompletionsAtPosition = function(fileName: string, position: number) { proxy.getCompletionsAtPosition = function(
let base = oldLS.getCompletionsAtPosition(fileName, position) || { fileName: string, position: number, options: ts.GetCompletionsAtPositionOptions|undefined) {
let base = oldLS.getCompletionsAtPosition(fileName, position, options) || {
isGlobalCompletion: false, isGlobalCompletion: false,
isMemberCompletion: false, isMemberCompletion: false,
isNewIdentifierLocation: false, isNewIdentifierLocation: false,

View File

@ -203,12 +203,14 @@ describe('plugin', () => {
} }
function contains(fileName: string, locationMarker: string, ...names: string[]) { function contains(fileName: string, locationMarker: string, ...names: string[]) {
const location = getMarkerLocation(fileName, locationMarker); const location = getMarkerLocation(fileName, locationMarker);
expectEntries(locationMarker, plugin.getCompletionsAtPosition(fileName, location), ...names); expectEntries(
locationMarker, plugin.getCompletionsAtPosition(fileName, location, undefined), ...names);
} }
function expectEmpty(fileName: string, locationMarker: string) { function expectEmpty(fileName: string, locationMarker: string) {
const location = getMarkerLocation(fileName, locationMarker); const location = getMarkerLocation(fileName, locationMarker);
expect(plugin.getCompletionsAtPosition(fileName, location).entries || []).toEqual([]); expect(plugin.getCompletionsAtPosition(fileName, location, undefined).entries || []).toEqual([
]);
} }
function expectSemanticError(fileName: string, locationMarker: string, message: string) { function expectSemanticError(fileName: string, locationMarker: string, message: string) {

View File

@ -124,7 +124,7 @@ export class AppVersion implements UpdateSource {
// No response has been found yet. Maybe this group will have one. // No response has been found yet. Maybe this group will have one.
return group.handleFetch(req, context); return group.handleFetch(req, context);
}, Promise.resolve(null)); }, Promise.resolve<Response|null>(null));
// The result of the above is the asset response, if there is any, or null otherwise. Return the // The result of the above is the asset response, if there is any, or null otherwise. Return the
// asset // asset
@ -142,7 +142,7 @@ export class AppVersion implements UpdateSource {
} }
return group.handleFetch(req, context); return group.handleFetch(req, context);
}, Promise.resolve(null)); }, Promise.resolve<Response|null>(null));
// If the data caching group returned a response, go with it. // If the data caching group returned a response, go with it.
if (data !== null) { if (data !== null) {

View File

@ -276,6 +276,7 @@ export abstract class AssetGroup {
const cache = await this.cache; const cache = await this.cache;
// Start with the set of all cached URLs. // Start with the set of all cached URLs.
return (await cache.keys()) return (await cache.keys())
.map(request => request.url)
// Exclude the URLs which have hashes. // Exclude the URLs which have hashes.
.filter(url => !this.hashes.has(url)); .filter(url => !this.hashes.has(url));
} }
@ -608,4 +609,4 @@ export class LazyAssetGroup extends AssetGroup {
} }
}, Promise.resolve()); }, Promise.resolve());
} }
} }

View File

@ -51,7 +51,7 @@ export class CacheTable implements Table {
'delete'(key: string): Promise<boolean> { return this.cache.delete(this.request(key)); } 'delete'(key: string): Promise<boolean> { return this.cache.delete(this.request(key)); }
keys(): Promise<string[]> { keys(): Promise<string[]> {
return this.cache.keys().then(keys => keys.map(key => key.substr(1))); return this.cache.keys().then(requests => requests.map(req => req.url.substr(1)));
} }
read(key: string): Promise<any> { read(key: string): Promise<any> {
@ -66,4 +66,4 @@ export class CacheTable implements Table {
write(key: string, value: Object): Promise<void> { write(key: string, value: Object): Promise<void> {
return this.cache.put(this.request(key), this.adapter.newResponse(JSON.stringify(value))); return this.cache.put(this.request(key), this.adapter.newResponse(JSON.stringify(value)));
} }
} }

View File

@ -25,33 +25,6 @@ interface ExtendableEvent extends Event {
waitUntil(fn: Promise<any>): void; waitUntil(fn: Promise<any>): void;
} }
// CacheStorage API
interface Cache {
add(request: Request): Promise<void>;
addAll(requestArray: Array<Request>): Promise<void>;
'delete'(request: Request, options?: CacheStorageOptions): Promise<boolean>;
keys(request?: Request, options?: CacheStorageOptions): Promise<Array<string>>;
match(request: Request, options?: CacheStorageOptions): Promise<Response|undefined>;
matchAll(request: Request, options?: CacheStorageOptions): Promise<Array<Response>>;
put(request: Request|string, response: Response): Promise<void>;
}
interface CacheStorage {
'delete'(cacheName: string): Promise<boolean>;
has(cacheName: string): Promise<boolean>;
keys(): Promise<Array<string>>;
match(request: Request, options?: CacheStorageOptions): Promise<Response|undefined>;
open(cacheName: string): Promise<Cache>;
}
interface CacheStorageOptions {
cacheName?: string;
ignoreMethod?: boolean;
ignoreSearch?: boolean;
ignoreVary?: boolean;
}
// Client API // Client API
declare class Client { declare class Client {
@ -145,4 +118,4 @@ interface ServiceWorkerGlobalScope {
fetch(request: Request|string): Promise<Response>; fetch(request: Request|string): Promise<Response>;
skipWaiting(): Promise<void>; skipWaiting(): Promise<void>;
} }

View File

@ -41,7 +41,7 @@ export class MockCacheStorage implements CacheStorage {
if (!this.caches.has(name)) { if (!this.caches.has(name)) {
this.caches.set(name, new MockCache(this.origin)); this.caches.set(name, new MockCache(this.origin));
} }
return this.caches.get(name) !; return this.caches.get(name) as any;
} }
async match(req: Request): Promise<Response|undefined> { async match(req: Request): Promise<Response|undefined> {
@ -74,7 +74,7 @@ export class MockCacheStorage implements CacheStorage {
} }
} }
export class MockCache implements Cache { export class MockCache {
private cache = new Map<string, Response>(); private cache = new Map<string, Response>();
constructor(private origin: string, hydrated?: DehydratedCache) { constructor(private origin: string, hydrated?: DehydratedCache) {
@ -122,7 +122,6 @@ export class MockCache implements Cache {
return res !; return res !;
} }
async matchAll(request?: Request|string, options?: CacheQueryOptions): Promise<Response[]> { async matchAll(request?: Request|string, options?: CacheQueryOptions): Promise<Response[]> {
if (request === undefined) { if (request === undefined) {
return Array.from(this.cache.values()); return Array.from(this.cache.values());
@ -149,7 +148,7 @@ export class MockCache implements Cache {
dehydrate(): DehydratedCache { dehydrate(): DehydratedCache {
const dehydrated: DehydratedCache = {}; const dehydrated: DehydratedCache = {};
Array.from(this.cache.keys()).forEach(url => { Array.from(this.cache.keys()).forEach(url => {
const resp = this.cache.get(url) !as MockResponse; const resp = this.cache.get(url) as MockResponse;
const dehydratedResp = { const dehydratedResp = {
body: resp._body, body: resp._body,
status: resp.status, status: resp.status,
@ -163,4 +162,4 @@ export class MockCache implements Cache {
}); });
return dehydrated; return dehydrated;
} }
} }

View File

@ -57,17 +57,26 @@ export class MockBody implements Body {
export class MockHeaders implements Headers { export class MockHeaders implements Headers {
map = new Map<string, string>(); map = new Map<string, string>();
[Symbol.iterator]() { return this.map[Symbol.iterator](); }
append(name: string, value: string): void { this.map.set(name, value); } append(name: string, value: string): void { this.map.set(name, value); }
delete (name: string): void { this.map.delete(name); } delete (name: string): void { this.map.delete(name); }
entries() { return this.map.entries(); }
forEach(callback: Function): void { this.map.forEach(callback as any); } forEach(callback: Function): void { this.map.forEach(callback as any); }
get(name: string): string|null { return this.map.get(name) || null; } get(name: string): string|null { return this.map.get(name) || null; }
has(name: string): boolean { return this.map.has(name); } has(name: string): boolean { return this.map.has(name); }
keys() { return this.map.keys(); }
set(name: string, value: string): void { this.map.set(name, value); } set(name: string, value: string): void { this.map.set(name, value); }
values() { return this.map.values(); }
} }
export class MockRequest extends MockBody implements Request { export class MockRequest extends MockBody implements Request {
@ -91,13 +100,12 @@ export class MockRequest extends MockBody implements Request {
throw 'Not implemented'; throw 'Not implemented';
} }
this.url = input; this.url = input;
if (init.headers !== undefined) { const headers = init.headers as{[key: string]: string};
if (init.headers instanceof MockHeaders) { if (headers !== undefined) {
this.headers = init.headers; if (headers instanceof MockHeaders) {
this.headers = headers;
} else { } else {
Object.keys(init.headers).forEach(header => { Object.keys(headers).forEach(header => { this.headers.set(header, headers[header]); });
this.headers.set(header, init.headers[header]);
});
} }
} }
if (init.mode !== undefined) { if (init.mode !== undefined) {
@ -134,13 +142,12 @@ export class MockResponse extends MockBody implements Response {
super(typeof body === 'string' ? body : null); super(typeof body === 'string' ? body : null);
this.status = (init.status !== undefined) ? init.status : 200; this.status = (init.status !== undefined) ? init.status : 200;
this.statusText = init.statusText || 'OK'; this.statusText = init.statusText || 'OK';
if (init.headers !== undefined) { const headers = init.headers as{[key: string]: string};
if (init.headers instanceof MockHeaders) { if (headers !== undefined) {
this.headers = init.headers; if (headers instanceof MockHeaders) {
this.headers = headers;
} else { } else {
Object.keys(init.headers).forEach(header => { Object.keys(headers).forEach(header => { this.headers.set(header, headers[header]); });
this.headers.set(header, init.headers[header]);
});
} }
} }
if (init.type !== undefined) { if (init.type !== undefined) {

View File

@ -212,4 +212,4 @@ export function tmpHashTable(manifest: Manifest): Map<string, string> {
map.set(url, hash); map.set(url, hash);
}); });
return map; return map;
} }

View File

@ -42,7 +42,7 @@ setEnvVar CHROMIUM_VERSION 494239 # Chrome 62 linux stable, see https://www.chro
setEnvVar CHROMEDRIVER_VERSION_ARG "--versions.chrome 2.33" setEnvVar CHROMEDRIVER_VERSION_ARG "--versions.chrome 2.33"
setEnvVar BAZEL_VERSION 0.8.1 setEnvVar BAZEL_VERSION 0.8.1
setEnvVar SAUCE_CONNECT_VERSION 4.4.9 setEnvVar SAUCE_CONNECT_VERSION 4.4.9
setEnvVar ANGULAR_CLI_VERSION 1.5.0-rc.2 setEnvVar ANGULAR_CLI_VERSION 1.6.2
setEnvVar PROJECT_ROOT $(cd ${thisDir}/../..; pwd) setEnvVar PROJECT_ROOT $(cd ${thisDir}/../..; pwd)
if [[ ${TRAVIS:-} ]]; then if [[ ${TRAVIS:-} ]]; then

View File

@ -7083,9 +7083,9 @@ ts-api-guardian@0.2.2:
minimist "^1.2.0" minimist "^1.2.0"
typescript "2.0.10" typescript "2.0.10"
tsickle@0.25.5: tsickle@0.26.0:
version "0.25.5" version "0.26.0"
resolved "https://registry.yarnpkg.com/tsickle/-/tsickle-0.25.5.tgz#2891d29f97c4aab1306e06378d8496d1765a4bfe" resolved "https://registry.yarnpkg.com/tsickle/-/tsickle-0.26.0.tgz#40b30a2dd6abcb33b182e37596674bd1cfe4039c"
dependencies: dependencies:
minimist "^1.2.0" minimist "^1.2.0"
mkdirp "^0.5.1" mkdirp "^0.5.1"
@ -7186,9 +7186,9 @@ typescript@2.0.10:
version "2.0.10" version "2.0.10"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.0.10.tgz#ccdd4ed86fd5550a407101a0814012e1b3fac3dd" resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.0.10.tgz#ccdd4ed86fd5550a407101a0814012e1b3fac3dd"
typescript@2.5.x: typescript@2.6.x:
version "2.5.3" version "2.6.2"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.5.3.tgz#df3dcdc38f3beb800d4bc322646b04a3f6ca7f0d" resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.6.2.tgz#3c5b6fd7f6de0914269027f03c0946758f7673a4"
uglify-js@1.2.6, uglify-js@~1.2.5: uglify-js@1.2.6, uglify-js@~1.2.5:
version "1.2.6" version "1.2.6"