Merge branch 'master' into sourceMapGenerator

This commit is contained in:
Ron Buckton committed 2018-11-09 11:50:51 -08:00
commit 151dc074a8
1703 files changed
+92654 -54958

No files matched your search

+15 -13
View File
@@ -1,6 +1,6 @@
const fs = require("fs");
const path = require("path");
const del = require("del");
const fs: typeof import("fs") = require("fs");
const path: typeof import("path") = require("path");
const del: typeof import("del") = require("del");
interface ExecResult {
stdout: Buffer;
@@ -49,12 +49,9 @@ abstract class ExternalCompileRunnerBase extends RunnerBase {
let types: string[] | undefined;
if (fs.existsSync(path.join(cwd, "test.json"))) {
const submoduleDir = path.join(cwd, directoryName);
const reset = cp.spawnSync("git", ["reset", "HEAD", "--hard"], { cwd: submoduleDir, timeout, shell: true, stdio });
if (reset.status !== 0) throw new Error(`git reset for ${directoryName} failed: ${reset.stderr.toString()}`);
const clean = cp.spawnSync("git", ["clean", "-f"], { cwd: submoduleDir, timeout, shell: true, stdio });
if (clean.status !== 0) throw new Error(`git clean for ${directoryName} failed: ${clean.stderr.toString()}`);
const update = cp.spawnSync("git", ["submodule", "update", "--init", "--remote", "."], { cwd: submoduleDir, timeout, shell: true, stdio });
if (update.status !== 0) throw new Error(`git submodule update for ${directoryName} failed: ${update.stderr.toString()}`);
exec("git", ["reset", "HEAD", "--hard"], { cwd: submoduleDir });
exec("git", ["clean", "-f"], { cwd: submoduleDir });
exec("git", ["submodule", "update", "--init", "--remote", "."], { cwd: submoduleDir });
const config = JSON.parse(fs.readFileSync(path.join(cwd, "test.json"), { encoding: "utf8" })) as UserConfig;
ts.Debug.assert(!!config.types, "Bad format from test.json: Types field must be present.");
@@ -69,18 +66,23 @@ abstract class ExternalCompileRunnerBase extends RunnerBase {
if (fs.existsSync(path.join(cwd, "node_modules"))) {
del.sync(path.join(cwd, "node_modules"), { force: true });
}
const install = cp.spawnSync(`npm`, ["i", "--ignore-scripts"], { cwd, timeout: timeout / 2, shell: true, stdio }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure
if (install.status !== 0) throw new Error(`NPM Install for ${directoryName} failed: ${install.stderr.toString()}`);
exec("npm", ["i", "--ignore-scripts"], { cwd, timeout: timeout / 2 }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure
}
const args = [path.join(Harness.IO.getWorkspaceRoot(), "built/local/tsc.js")];
if (types) {
args.push("--types", types.join(","));
// Also actually install those types (for, eg, the js projects which need node)
const install = cp.spawnSync(`npm`, ["i", ...types.map(t => `@types/${t}`), "--no-save", "--ignore-scripts"], { cwd: originalCwd, timeout: timeout / 2, shell: true, stdio }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure
if (install.status !== 0) throw new Error(`NPM Install types for ${directoryName} failed: ${install.stderr.toString()}`);
exec("npm", ["i", ...types.map(t => `@types/${t}`), "--no-save", "--ignore-scripts"], { cwd: originalCwd, timeout: timeout / 2 }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure
}
args.push("--noEmit");
Harness.Baseline.runBaseline(`${cls.kind()}/${directoryName}.log`, cls.report(cp.spawnSync(`node`, args, { cwd, timeout, shell: true }), cwd));
function exec(command: string, args: string[], options: { cwd: string, timeout?: number }): void {
const res = cp.spawnSync(command, args, { timeout, shell: true, stdio, ...options });
if (res.status !== 0) {
throw new Error(`${command} ${args.join(" ")} for ${directoryName} failed: ${res.stderr && res.stderr.toString()}`);
}
}
});
});
}
+2 -4
View File
@@ -310,9 +310,7 @@ namespace project {
const program = ts.createProgram(getInputFiles(), compilerOptions, compilerHost);
const errors = ts.getPreEmitDiagnostics(program);
const emitResult = program.emit();
ts.addRange(errors, emitResult.diagnostics);
const sourceMapData = emitResult.sourceMaps;
const { sourceMaps: sourceMapData, diagnostics: emitDiagnostics } = program.emit();
// Clean up source map data that will be used in baselining
if (sourceMapData) {
@@ -329,7 +327,7 @@ namespace project {
configFileSourceFiles,
moduleKind,
program,
errors,
errors: ts.concatenate(errors, emitDiagnostics),
sourceMapData
};
}
+2
View File
@@ -65,6 +65,7 @@
"unittests/matchFiles.ts",
"unittests/moduleResolution.ts",
"unittests/organizeImports.ts",
"unittests/parsePseudoBigInt.ts",
"unittests/paths.ts",
"unittests/printer.ts",
"unittests/programMissingFiles.ts",
@@ -75,6 +76,7 @@
"unittests/reuseProgramStructure.ts",
"unittests/session.ts",
"unittests/semver.ts",
"unittests/showConfig.ts",
"unittests/symbolWalker.ts",
"unittests/telemetry.ts",
"unittests/textChanges.ts",
@@ -57,7 +57,7 @@ namespace ts {
assertParseResult(["--lib", "es5,invalidOption", "0.ts"],
{
errors: [{
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
file: undefined,
@@ -259,7 +259,7 @@ namespace ts {
assertParseResult(["--lib", "es5,", "es7", "0.ts"],
{
errors: [{
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
file: undefined,
@@ -278,7 +278,7 @@ namespace ts {
assertParseResult(["--lib", "es5, ", "es7", "0.ts"],
{
errors: [{
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
file: undefined,
@@ -4,6 +4,83 @@ namespace ts {
cwd,
files: {
[root]: {
"dev/node_modules/config-box/package.json": JSON.stringify({
name: "config-box",
version: "1.0.0",
tsconfig: "./strict.json"
}),
"dev/node_modules/config-box/strict.json": JSON.stringify({
compilerOptions: {
strict: true,
}
}),
"dev/node_modules/config-box/unstrict.json": JSON.stringify({
compilerOptions: {
strict: false,
}
}),
"dev/tsconfig.extendsBox.json": JSON.stringify({
extends: "config-box",
files: [
"main.ts",
]
}),
"dev/tsconfig.extendsStrict.json": JSON.stringify({
extends: "config-box/strict",
files: [
"main.ts",
]
}),
"dev/tsconfig.extendsUnStrict.json": JSON.stringify({
extends: "config-box/unstrict",
files: [
"main.ts",
]
}),
"dev/tsconfig.extendsStrictExtension.json": JSON.stringify({
extends: "config-box/strict.json",
files: [
"main.ts",
]
}),
"dev/node_modules/config-box-implied/package.json": JSON.stringify({
name: "config-box-implied",
version: "1.0.0",
}),
"dev/node_modules/config-box-implied/tsconfig.json": JSON.stringify({
compilerOptions: {
strict: true,
}
}),
"dev/node_modules/config-box-implied/unstrict/tsconfig.json": JSON.stringify({
compilerOptions: {
strict: false,
}
}),
"dev/tsconfig.extendsBoxImplied.json": JSON.stringify({
extends: "config-box-implied",
files: [
"main.ts",
]
}),
"dev/tsconfig.extendsBoxImpliedUnstrict.json": JSON.stringify({
extends: "config-box-implied/unstrict",
files: [
"main.ts",
]
}),
"dev/tsconfig.extendsBoxImpliedUnstrictExtension.json": JSON.stringify({
extends: "config-box-implied/unstrict/tsconfig",
files: [
"main.ts",
]
}),
"dev/tsconfig.extendsBoxImpliedPath.json": JSON.stringify({
extends: "config-box-implied/tsconfig.json",
files: [
"main.ts",
]
}),
"dev/tsconfig.json": JSON.stringify({
extends: "./configs/base",
files: [
@@ -226,12 +303,6 @@ namespace ts {
messageText: `Compiler option 'extends' requires a value of type string.`
}]);
testFailure("can error when 'extends' is neither relative nor rooted.", "extends2.json", [{
code: 18001,
category: DiagnosticCategory.Error,
messageText: `A path in an 'extends' option must be relative or rooted, but 'configs/base' is not.`
}]);
testSuccess("can overwrite compiler options using extended 'null'", "configs/third.json", {
allowJs: true,
noImplicitAny: true,
@@ -259,6 +330,17 @@ namespace ts {
combinePaths(basePath, "tests/utils.ts")
]);
describe("finding extended configs from node_modules", () => {
testSuccess("can lookup via tsconfig field", "tsconfig.extendsBox.json", { strict: true }, [combinePaths(basePath, "main.ts")]);
testSuccess("can lookup via package-relative path", "tsconfig.extendsStrict.json", { strict: true }, [combinePaths(basePath, "main.ts")]);
testSuccess("can lookup via non-redirected-to package-relative path", "tsconfig.extendsUnStrict.json", { strict: false }, [combinePaths(basePath, "main.ts")]);
testSuccess("can lookup via package-relative path with extension", "tsconfig.extendsStrictExtension.json", { strict: true }, [combinePaths(basePath, "main.ts")]);
testSuccess("can lookup via an implicit tsconfig", "tsconfig.extendsBoxImplied.json", { strict: true }, [combinePaths(basePath, "main.ts")]);
testSuccess("can lookup via an implicit tsconfig in a package-relative directory", "tsconfig.extendsBoxImpliedUnstrict.json", { strict: false }, [combinePaths(basePath, "main.ts")]);
testSuccess("can lookup via an implicit tsconfig in a package-relative directory with name", "tsconfig.extendsBoxImpliedUnstrictExtension.json", { strict: false }, [combinePaths(basePath, "main.ts")]);
testSuccess("can lookup via an implicit tsconfig in a package-relative directory with extension", "tsconfig.extendsBoxImpliedPath.json", { strict: true }, [combinePaths(basePath, "main.ts")]);
});
it("adds extendedSourceFiles only once", () => {
const sourceFile = readJsonConfigFile("configs/fourth.json", (path) => host.readFile(path));
const dir = combinePaths(basePath, "configs");
@@ -295,7 +295,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -326,7 +326,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -357,7 +357,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -388,7 +388,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -597,7 +597,7 @@ namespace ts {
compilerOptions: {
target: undefined,
module: ModuleKind.ESNext,
types: []
experimentalDecorators: true,
},
hasParseErrors: true
}
@@ -107,7 +107,7 @@ namespace ts {
};
const rangeToExtract = refactor.extractSymbol.getRangeToExtract(sourceFile, createTextSpanFromRange(selectionRange));
assert.equal(rangeToExtract.errors, undefined, rangeToExtract.errors && "Range error: " + rangeToExtract.errors[0].messageText);
const infos = refactor.extractSymbol.getAvailableActions(context)!;
const infos = refactor.extractSymbol.getAvailableActions(context);
const actions = find(infos, info => info.description === description.message)!.actions;
const data: string[] = [];
@@ -169,7 +169,7 @@ namespace ts {
};
const rangeToExtract = refactor.extractSymbol.getRangeToExtract(sourceFile, createTextSpanFromRange(selectionRange));
assert.isUndefined(rangeToExtract.errors, rangeToExtract.errors && "Range error: " + rangeToExtract.errors[0].messageText);
const infos = refactor.extractSymbol.getAvailableActions(context)!;
const infos = refactor.extractSymbol.getAvailableActions(context);
assert.isUndefined(find(infos, info => info.description === description.message));
});
}
@@ -757,6 +757,9 @@ import b = require("./moduleB");
],
"somefolder/*": [
"someanotherfolder/*"
],
"/rooted/*": [
"generated/*"
]
}
};
@@ -773,6 +776,7 @@ import b = require("./moduleB");
"/root/folder1/file2/index.d.ts",
// then first attempt on 'generated/*' was successful
]);
check("/rooted/folder1/file2", file2, []);
check("folder2/file3", file3, [
// first try '*'
"/root/folder2/file3.ts",
@@ -900,6 +904,9 @@ import b = require("./moduleB");
],
"somefolder/*": [
"someanotherfolder/*"
],
"/rooted/*": [
"generated/*"
]
}
};
@@ -911,6 +918,7 @@ import b = require("./moduleB");
"/root/folder1/file2.d.ts",
// success when using 'generated/*'
]);
check("/rooted/folder1/file2", file2, []);
check("folder1/file3", file3, [
// first try '*'
"/root/folder1/file3.ts",
@@ -0,0 +1,71 @@
namespace ts {
describe("BigInt literal base conversions", () => {
describe("parsePseudoBigInt", () => {
const testNumbers: number[] = [];
for (let i = 0; i < 1e3; i++) testNumbers.push(i);
for (let bits = 0; bits <= 52; bits++) {
testNumbers.push(2 ** bits, 2 ** bits - 1);
}
it("can strip base-10 strings", () => {
for (const testNumber of testNumbers) {
for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) {
assert.equal(
parsePseudoBigInt("0".repeat(leadingZeros) + testNumber + "n"),
String(testNumber)
);
}
}
});
it("can parse binary literals", () => {
for (const testNumber of testNumbers) {
for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) {
const binary = "0".repeat(leadingZeros) + testNumber.toString(2) + "n";
for (const prefix of ["0b", "0B"]) {
assert.equal(parsePseudoBigInt(prefix + binary), String(testNumber));
}
}
}
});
it("can parse octal literals", () => {
for (const testNumber of testNumbers) {
for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) {
const octal = "0".repeat(leadingZeros) + testNumber.toString(8) + "n";
for (const prefix of ["0o", "0O"]) {
assert.equal(parsePseudoBigInt(prefix + octal), String(testNumber));
}
}
}
});
it("can parse hex literals", () => {
for (const testNumber of testNumbers) {
for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) {
const hex = "0".repeat(leadingZeros) + testNumber.toString(16) + "n";
for (const prefix of ["0x", "0X"]) {
for (const hexCase of [hex.toLowerCase(), hex.toUpperCase()]) {
assert.equal(parsePseudoBigInt(prefix + hexCase), String(testNumber));
}
}
}
}
});
it("can parse large literals", () => {
assert.equal(
parsePseudoBigInt("123456789012345678901234567890n"),
"123456789012345678901234567890"
);
assert.equal(
parsePseudoBigInt("0b1100011101110100100001111111101101100001101110011111000001110111001001110001111110000101011010010n"),
"123456789012345678901234567890"
);
assert.equal(
parsePseudoBigInt("0o143564417755415637016711617605322n"),
"123456789012345678901234567890"
);
assert.equal(
parsePseudoBigInt("0x18ee90ff6c373e0ee4e3f0ad2n"),
"123456789012345678901234567890"
);
});
});
});
}
@@ -98,4 +98,38 @@ namespace ts {
]);
});
});
describe("Program.isSourceFileFromExternalLibrary", () => {
it("works on redirect files", () => {
// In this example '/node_modules/foo/index.d.ts' will redirect to '/node_modules/bar/node_modules/foo/index.d.ts'.
const a = new documents.TextDocument("/a.ts", 'import * as bar from "bar"; import * as foo from "foo";');
const bar = new documents.TextDocument("/node_modules/bar/index.d.ts", 'import * as foo from "foo";');
const fooPackageJsonText = '{ "name": "foo", "version": "1.2.3" }';
const fooIndexText = "export const x: number;";
const barFooPackage = new documents.TextDocument("/node_modules/bar/node_modules/foo/package.json", fooPackageJsonText);
const barFooIndex = new documents.TextDocument("/node_modules/bar/node_modules/foo/index.d.ts", fooIndexText);
const fooPackage = new documents.TextDocument("/node_modules/foo/package.json", fooPackageJsonText);
const fooIndex = new documents.TextDocument("/node_modules/foo/index.d.ts", fooIndexText);
const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [a, bar, barFooPackage, barFooIndex, fooPackage, fooIndex], cwd: "/" });
const program = createProgram(["/a.ts"], emptyOptions, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed }));
assertIsExternal(program, [a, bar, barFooIndex, fooIndex], f => f !== a);
});
it('works on `/// <reference types="" />`', () => {
const a = new documents.TextDocument("/a.ts", '/// <reference types="foo" />');
const fooIndex = new documents.TextDocument("/node_modules/foo/index.d.ts", "declare const foo: number;");
const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [a, fooIndex], cwd: "/" });
const program = createProgram(["/a.ts"], emptyOptions, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed }));
assertIsExternal(program, [a, fooIndex], f => f !== a);
});
function assertIsExternal(program: Program, files: ReadonlyArray<documents.TextDocument>, isExternalExpected: (file: documents.TextDocument) => boolean): void {
for (const file of files) {
const actual = program.isSourceFileFromExternalLibrary(program.getSourceFile(file.file)!);
const expected = isExternalExpected(file);
assert.equal(actual, expected, `Expected ${file.file} isSourceFileFromExternalLibrary to be ${expected}, got ${actual}`);
}
}
});
}
+25 -2
View File
@@ -147,7 +147,10 @@ namespace ts {
},
"/reference": {
files: { "/secondary/b.ts": moduleImporting("../primary/a") },
references: ["../primary"]
references: ["../primary"],
config: {
files: ["b.ts"]
}
}
};
testProjectReferences(spec, "/reference/tsconfig.json", program => {
@@ -156,6 +159,26 @@ namespace ts {
});
});
it("does not error when the referenced project doesn't have composite:true if its a container project", () => {
const spec: TestSpecification = {
"/primary": {
files: { "/primary/a.ts": emptyModule },
references: [],
options: {
composite: false
}
},
"/reference": {
files: { "/secondary/b.ts": moduleImporting("../primary/a") },
references: ["../primary"],
}
};
testProjectReferences(spec, "/reference/tsconfig.json", program => {
const errs = program.getOptionsDiagnostics();
assertNoErrors("Reports an error about 'composite' not being set", errs);
});
});
it("errors when the file list is not exhaustive", () => {
const spec: TestSpecification = {
"/primary": {
@@ -184,7 +207,7 @@ namespace ts {
};
testProjectReferences(spec, "/primary/tsconfig.json", program => {
const errs = program.getOptionsDiagnostics();
assertHasError("Reports an error about a missing file", errs, Diagnostics.File_0_does_not_exist);
assertHasError("Reports an error about a missing file", errs, Diagnostics.File_0_not_found);
});
});
+34
View File
@@ -0,0 +1,34 @@
namespace ts {
describe("showTSConfig", () => {
function showTSConfigCorrectly(name: string, commandLinesArgs: string[]) {
describe(name, () => {
const commandLine = parseCommandLine(commandLinesArgs);
const initResult = convertToTSConfig(commandLine, `/${name}/tsconfig.json`, { getCurrentDirectory() { return `/${name}`; }, useCaseSensitiveFileNames: true });
const outputFileName = `showConfig/${name.replace(/[^a-z0-9\-. ]/ig, "")}/tsconfig.json`;
it(`Correct output for ${outputFileName}`, () => {
// tslint:disable-next-line:no-null-keyword
Harness.Baseline.runBaseline(outputFileName, JSON.stringify(initResult, null, 4) + "\n");
});
});
}
showTSConfigCorrectly("Default initialized TSConfig", ["--showConfig"]);
showTSConfigCorrectly("Show TSConfig with files options", ["--showConfig", "file0.st", "file1.ts", "file2.ts"]);
showTSConfigCorrectly("Show TSConfig with boolean value compiler options", ["--showConfig", "--noUnusedLocals"]);
showTSConfigCorrectly("Show TSConfig with enum value compiler options", ["--showConfig", "--target", "es5", "--jsx", "react"]);
showTSConfigCorrectly("Show TSConfig with list compiler options", ["--showConfig", "--types", "jquery,mocha"]);
showTSConfigCorrectly("Show TSConfig with list compiler options with enum value", ["--showConfig", "--lib", "es5,es2015.core"]);
showTSConfigCorrectly("Show TSConfig with incorrect compiler option", ["--showConfig", "--someNonExistOption"]);
showTSConfigCorrectly("Show TSConfig with incorrect compiler option value", ["--showConfig", "--lib", "nonExistLib,es5,es2015.promise"]);
showTSConfigCorrectly("Show TSConfig with advanced options", ["--showConfig", "--declaration", "--declarationDir", "lib", "--skipLibCheck", "--noErrorTruncation"]);
});
}
+22
View File
@@ -40,6 +40,16 @@ namespace ts {
return (file: SourceFile) => file;
}
function replaceIdentifiersNamedOldNameWithNewName2(context: TransformationContext) {
const visitor: Visitor = (node) => {
if (isIdentifier(node) && node.text === "oldName") {
return createIdentifier("newName");
}
return visitEachChild(node, visitor, context);
};
return (node: SourceFile) => visitNode(node, visitor);
}
function transformSourceFile(sourceText: string, transformers: TransformerFactory<SourceFile>[]) {
const transformed = transform(createSourceFile("source.ts", sourceText, ScriptTarget.ES2015), transformers);
const printer = createPrinter({ newLine: NewLineKind.CarriageReturnLineFeed }, {
@@ -81,6 +91,18 @@ namespace ts {
}).outputText;
});
testBaseline("issue27854", () => {
return transpileModule(`oldName<{ a: string; }>\` ... \`;`, {
transformers: {
before: [replaceIdentifiersNamedOldNameWithNewName2]
},
compilerOptions: {
newLine: NewLineKind.CarriageReturnLineFeed,
target: ScriptTarget.Latest
}
}).outputText;
});
testBaseline("rewrittenNamespace", () => {
return transpileModule(`namespace Reflect { const x = 1; }`, {
transformers: {
+99 -10
View File
@@ -276,6 +276,10 @@ export class cNew {}`);
function verifyProjectWithResolveJsonModule(configFile: string, ...expectedDiagnosticMessages: DiagnosticMessage[]) {
const fs = projFs.shadow();
verifyProjectWithResolveJsonModuleWithFs(fs, configFile, allExpectedOutputs, ...expectedDiagnosticMessages);
}
function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: ReadonlyArray<string>, ...expectedDiagnosticMessages: DiagnosticMessage[]) {
const host = new fakes.SolutionBuilderHost(fs);
const builder = createSolutionBuilder(host, [configFile], { dry: false, force: false, verbose: false });
builder.buildAllProjects();
@@ -292,6 +296,21 @@ export class cNew {}`);
verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withInclude.json", Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern);
});
it("with resolveJsonModule and include of *.json along with other include", () => {
verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeOfJson.json");
});
it("with resolveJsonModule and include of *.json along with other include and file name matches ts file", () => {
const fs = projFs.shadow();
fs.rimrafSync("/src/tests/src/hello.json");
fs.writeFileSync("/src/tests/src/index.json", JSON.stringify({ hello: "world" }));
fs.writeFileSync("/src/tests/src/index.ts", `import hello from "./index.json"
export default hello.hello`);
const allExpectedOutputs = ["/src/tests/dist/src/index.js", "/src/tests/dist/src/index.d.ts", "/src/tests/dist/src/index.json"];
verifyProjectWithResolveJsonModuleWithFs(fs, "/src/tests/tsconfig_withIncludeOfJson.json", allExpectedOutputs);
});
it("with resolveJsonModule and files containing json file", () => {
verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withFiles.json");
});
@@ -321,16 +340,6 @@ export class cNew {}`);
"/src/tests/index.ts"
]);
function getLibs() {
return [
"/lib/lib.d.ts",
"/lib/lib.es5.d.ts",
"/lib/lib.dom.d.ts",
"/lib/lib.webworker.importscripts.d.ts",
"/lib/lib.scripthost.d.ts"
];
}
function getCoreOutputs() {
return [
"/src/core/index.d.ts",
@@ -347,8 +356,10 @@ export class cNew {}`);
assert.deepEqual(host.traces, [
"TSFILE: /src/core/anotherModule.js",
"TSFILE: /src/core/anotherModule.d.ts",
"TSFILE: /src/core/anotherModule.d.ts.map",
"TSFILE: /src/core/index.js",
"TSFILE: /src/core/index.d.ts",
"TSFILE: /src/core/index.d.ts.map",
"TSFILE: /src/logic/index.js",
"TSFILE: /src/logic/index.js.map",
"TSFILE: /src/logic/index.d.ts",
@@ -376,6 +387,74 @@ export class cNew {}`);
}
});
});
describe("tsbuild - when project reference is referenced transitively", () => {
const projFs = loadProjectFromDisk("tests/projects/transitiveReferences");
const allExpectedOutputs = [
"/src/a.js", "/src/a.d.ts",
"/src/b.js", "/src/b.d.ts",
"/src/c.js"
];
const expectedFileTraces = [
...getLibs(),
"/src/a.ts",
...getLibs(),
"/src/a.d.ts",
"/src/b.ts",
...getLibs(),
"/src/a.d.ts",
"/src/b.d.ts",
"/src/refs/a.d.ts",
"/src/c.ts"
];
function verifyBuild(modifyDiskLayout: (fs: vfs.FileSystem) => void, allExpectedOutputs: ReadonlyArray<string>, expectedDiagnostics: DiagnosticMessage[], expectedFileTraces: ReadonlyArray<string>) {
const fs = projFs.shadow();
const host = new fakes.SolutionBuilderHost(fs);
modifyDiskLayout(fs);
const builder = createSolutionBuilder(host, ["/src/tsconfig.c.json"], { listFiles: true });
builder.buildAllProjects();
host.assertDiagnosticMessages(...expectedDiagnostics);
for (const output of allExpectedOutputs) {
assert(fs.existsSync(output), `Expect file ${output} to exist`);
}
assert.deepEqual(host.traces, expectedFileTraces);
}
function modifyFsBTsToNonRelativeImport(fs: vfs.FileSystem, moduleResolution: "node" | "classic") {
fs.writeFileSync("/src/b.ts", `import {A} from 'a';
export const b = new A();`);
fs.writeFileSync("/src/tsconfig.b.json", JSON.stringify({
compilerOptions: {
composite: true,
moduleResolution
},
files: ["b.ts"],
references: [{ path: "tsconfig.a.json" }]
}));
}
it("verify that it builds correctly", () => {
verifyBuild(noop, allExpectedOutputs, emptyArray, expectedFileTraces);
});
it("verify that it builds correctly when the referenced project uses different module resolution", () => {
verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "classic"), allExpectedOutputs, emptyArray, expectedFileTraces);
});
it("verify that it build reports error about module not found with node resolution with external module name", () => {
// Error in b build only a
const allExpectedOutputs = ["/src/a.js", "/src/a.d.ts"];
const expectedFileTraces = [
...getLibs(),
"/src/a.ts",
];
verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "node"),
allExpectedOutputs,
[Diagnostics.Cannot_find_module_0],
expectedFileTraces);
});
});
}
export namespace OutFile {
@@ -584,4 +663,14 @@ export class cNew {}`);
fs.makeReadonly();
return fs;
}
function getLibs() {
return [
"/lib/lib.d.ts",
"/lib/lib.es5.d.ts",
"/lib/lib.dom.d.ts",
"/lib/lib.webworker.importscripts.d.ts",
"/lib/lib.scripthost.d.ts"
];
}
}
+594 -91
View File
@@ -1,6 +1,9 @@
namespace ts.tscWatch {
export import libFile = TestFSWithWatch.libFile;
function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray<string>, defaultOptions?: BuildOptions) {
import projectsLocation = TestFSWithWatch.tsbuildProjectsLocation;
import getFilePathInProject = TestFSWithWatch.getTsBuildProjectFilePath;
import getFileFromProject = TestFSWithWatch.getTsBuildProjectFile;
export function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray<string>, defaultOptions?: BuildOptions) {
const host = createSolutionBuilderWithWatchHost(system);
return ts.createSolutionBuilder(host, rootNames, defaultOptions || { watch: true });
}
@@ -13,7 +16,6 @@ namespace ts.tscWatch {
}
describe("tsbuild-watch program updates", () => {
const projectsLocation = "/user/username/projects";
const project = "sample1";
const enum SubProject {
core = "core",
@@ -24,10 +26,12 @@ namespace ts.tscWatch {
type ReadonlyFile = Readonly<File>;
/** [tsconfig, index] | [tsconfig, index, anotherModule, someDecl] */
type SubProjectFiles = [ReadonlyFile, ReadonlyFile] | [ReadonlyFile, ReadonlyFile, ReadonlyFile, ReadonlyFile];
const root = Harness.IO.getWorkspaceRoot();
function getProjectPath(project: string) {
return `${projectsLocation}/${project}`;
}
function projectPath(subProject: SubProject) {
return `${projectsLocation}/${project}/${subProject}`;
return getFilePathInProject(project, subProject);
}
function projectFilePath(subProject: SubProject, baseFileName: string) {
@@ -39,10 +43,7 @@ namespace ts.tscWatch {
}
function projectFile(subProject: SubProject, baseFileName: string): File {
return {
path: projectFilePath(subProject, baseFileName),
content: Harness.IO.readFile(`${root}/tests/projects/${project}/${subProject}/${baseFileName}`)!
};
return getFileFromProject(project, `${subProject}/${baseFileName}`);
}
function subProjectFiles(subProject: SubProject, anotherModuleAndSomeDecl?: true): SubProjectFiles {
@@ -97,7 +98,7 @@ namespace ts.tscWatch {
const tests = subProjectFiles(SubProject.tests);
const ui = subProjectFiles(SubProject.ui);
const allFiles: ReadonlyArray<File> = [libFile, ...core, ...logic, ...tests, ...ui];
const testProjectExpectedWatchedFiles = [core[0], core[1], core[2], ...logic, ...tests].map(f => f.path);
const testProjectExpectedWatchedFiles = [core[0], core[1], core[2]!, ...logic, ...tests].map(f => f.path.toLowerCase()); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary)
const testProjectExpectedWatchedDirectoriesRecursive = [projectPath(SubProject.core), projectPath(SubProject.logic)];
function createSolutionInWatchMode(allFiles: ReadonlyArray<File>, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) {
@@ -244,7 +245,7 @@ export class someClass2 { }`);
const allFiles = [libFile, ...core, logic[1], ...tests];
const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation });
createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]);
checkWatchedFiles(host, [core[0], core[1], core[2], logic[0], ...tests].map(f => f.path));
checkWatchedFiles(host, [core[0], core[1], core[2]!, logic[0], ...tests].map(f => f.path.toLowerCase())); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary)
checkWatchedDirectories(host, emptyArray, /*recursive*/ false);
checkWatchedDirectories(host, [projectPath(SubProject.core)], /*recursive*/ true);
checkOutputErrorsInitial(host, [
@@ -356,6 +357,58 @@ function myFunc() { return 100; }`);
}
});
it("when referenced project change introduces error in the down stream project and then fixes it", () => {
const subProjectLibrary = `${projectsLocation}/${project}/Library`;
const libraryTs: File = {
path: `${subProjectLibrary}/library.ts`,
content: `
interface SomeObject
{
message: string;
}
export function createSomeObject(): SomeObject
{
return {
message: "new Object"
};
}`
};
const libraryTsconfig: File = {
path: `${subProjectLibrary}/tsconfig.json`,
content: JSON.stringify({ compilerOptions: { composite: true } })
};
const subProjectApp = `${projectsLocation}/${project}/App`;
const appTs: File = {
path: `${subProjectApp}/app.ts`,
content: `import { createSomeObject } from "../Library/library";
createSomeObject().message;`
};
const appTsconfig: File = {
path: `${subProjectApp}/tsconfig.json`,
content: JSON.stringify({ references: [{ path: "../Library" }] })
};
const files = [libFile, libraryTs, libraryTsconfig, appTs, appTsconfig];
const host = createWatchedSystem(files, { currentDirectory: `${projectsLocation}/${project}` });
createSolutionBuilderWithWatch(host, ["App"]);
checkOutputErrorsInitial(host, emptyArray);
// Change message in library to message2
host.writeFile(libraryTs.path, libraryTs.content.replace(/message/g, "message2"));
host.checkTimeoutQueueLengthAndRun(1); // Build library
host.checkTimeoutQueueLengthAndRun(1); // Build App
checkOutputErrorsIncremental(host, [
"App/app.ts(2,20): error TS2551: Property 'message' does not exist on type 'SomeObject'. Did you mean 'message2'?\n"
]);
// Revert library changes
host.writeFile(libraryTs.path, libraryTs.content);
host.checkTimeoutQueueLengthAndRun(1); // Build library
host.checkTimeoutQueueLengthAndRun(1); // Build App
checkOutputErrorsIncremental(host, emptyArray);
});
describe("reports errors in all projects on incremental compile", () => {
function verifyIncrementalErrors(defaultBuildOptions?: BuildOptions, disabledConsoleClear?: boolean) {
const host = createSolutionInWatchMode(allFiles, defaultBuildOptions, disabledConsoleClear);
@@ -394,100 +447,550 @@ let x: string = 10;`);
});
});
describe("tsc-watch works with project references", () => {
const coreIndexDts = projectFileName(SubProject.core, "index.d.ts");
const coreAnotherModuleDts = projectFileName(SubProject.core, "anotherModule.d.ts");
const logicIndexDts = projectFileName(SubProject.logic, "index.d.ts");
const expectedWatchedFiles = [core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase()));
const expectedWatchedDirectoriesRecursive = projectSystem.getTypeRootsFromLocation(projectPath(SubProject.tests));
function createSolution() {
const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation });
const solutionBuilder = createSolutionBuilder(host, [`${project}/${SubProject.tests}`], {});
return { host, solutionBuilder };
}
function createBuiltSolution() {
const result = createSolution();
const { host, solutionBuilder } = result;
solutionBuilder.buildAllProjects();
const outputFileStamps = getOutputFileStamps(host);
for (const stamp of outputFileStamps) {
assert.isDefined(stamp[1], `${stamp[0]} expected to be present`);
}
return result;
}
function verifyWatches(host: WatchedSystem) {
checkWatchedFilesDetailed(host, expectedWatchedFiles, 1);
checkWatchedDirectories(host, emptyArray, /*recursive*/ false);
checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true);
}
function createSolutionAndWatchMode() {
// Build the composite project
const { host, solutionBuilder } = createBuiltSolution();
// Build in watch mode
const watch = createWatchOfConfigFileReturningBuilder(tests[0].path, host);
checkOutputErrorsInitial(host, emptyArray);
return { host, solutionBuilder, watch };
}
function verifyDependencies(watch: () => BuilderProgram, filePath: string, expected: ReadonlyArray<string>) {
checkArray(`${filePath} dependencies`, watch().getAllDependencies(watch().getSourceFile(filePath)!), expected);
}
describe("tsc-watch and tsserver works with project references", () => {
describe("invoking when references are already built", () => {
it("verifies dependencies and watches", () => {
const { host, watch } = createSolutionAndWatchMode();
function verifyWatchesOfProject(host: WatchedSystem, expectedWatchedFiles: ReadonlyArray<string>, expectedWatchedDirectoriesRecursive: ReadonlyArray<string>, expectedWatchedDirectories?: ReadonlyArray<string>) {
checkWatchedFilesDetailed(host, expectedWatchedFiles, 1);
checkWatchedDirectoriesDetailed(host, expectedWatchedDirectories || emptyArray, 1, /*recursive*/ false);
checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true);
}
verifyWatches(host);
verifyDependencies(watch, coreIndexDts, [coreIndexDts]);
verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]);
verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]);
verifyDependencies(watch, tests[1].path, [tests[1].path, coreAnotherModuleDts, logicIndexDts, coreAnotherModuleDts]);
});
function createSolutionOfProject(allFiles: ReadonlyArray<File>,
currentDirectory: string,
solutionBuilderconfig: string,
getOutputFileStamps: (host: WatchedSystem) => ReadonlyArray<OutputFileStamp>) {
// Build the composite project
const host = createWatchedSystem(allFiles, { currentDirectory });
const solutionBuilder = createSolutionBuilder(host, [solutionBuilderconfig], {});
solutionBuilder.buildAllProjects();
const outputFileStamps = getOutputFileStamps(host);
for (const stamp of outputFileStamps) {
assert.isDefined(stamp[1], `${stamp[0]} expected to be present`);
}
return { host, solutionBuilder };
}
it("local edit in ts file, result in watch compilation because logic.d.ts is written", () => {
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
host.writeFile(logic[1].path, `${logic[1].content}
function createSolutionAndWatchModeOfProject(
allFiles: ReadonlyArray<File>,
currentDirectory: string,
solutionBuilderconfig: string,
watchConfig: string,
getOutputFileStamps: (host: WatchedSystem) => ReadonlyArray<OutputFileStamp>) {
// Build the composite project
const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps);
// Build in watch mode
const watch = createWatchOfConfigFileReturningBuilder(watchConfig, host);
checkOutputErrorsInitial(host, emptyArray);
return { host, solutionBuilder, watch };
}
function createSolutionAndServiceOfProject(allFiles: ReadonlyArray<File>,
currentDirectory: string,
solutionBuilderconfig: string,
openFileName: string,
getOutputFileStamps: (host: WatchedSystem) => ReadonlyArray<OutputFileStamp>) {
// Build the composite project
const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps);
// service
const service = projectSystem.createProjectService(host);
service.openClientFile(openFileName);
return { host, solutionBuilder, service };
}
function checkProjectActualFiles(service: projectSystem.TestProjectService, configFile: string, expectedFiles: ReadonlyArray<string>) {
projectSystem.checkNumberOfProjects(service, { configuredProjects: 1 });
projectSystem.checkProjectActualFiles(service.configuredProjects.get(configFile.toLowerCase())!, expectedFiles);
}
type Watch = () => BuilderProgram;
function verifyDependencies(watch: Watch, filePath: string, expected: ReadonlyArray<string>) {
checkArray(`${filePath} dependencies`, watch().getAllDependencies(watch().getSourceFile(filePath)!), expected);
}
describe("on sample project", () => {
const coreIndexDts = projectFileName(SubProject.core, "index.d.ts");
const coreAnotherModuleDts = projectFileName(SubProject.core, "anotherModule.d.ts");
const logicIndexDts = projectFileName(SubProject.logic, "index.d.ts");
const expectedWatchedFiles = [core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase()));
const expectedWatchedDirectoriesRecursive = projectSystem.getTypeRootsFromLocation(projectPath(SubProject.tests));
const expectedProgramFiles = [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts];
function createSolutionAndWatchMode() {
return createSolutionAndWatchModeOfProject(allFiles, projectsLocation, `${project}/${SubProject.tests}`, tests[0].path, getOutputFileStamps);
}
function createSolutionAndService() {
return createSolutionAndServiceOfProject(allFiles, projectsLocation, `${project}/${SubProject.tests}`, tests[1].path, getOutputFileStamps);
}
function verifyWatches(host: WatchedSystem, withTsserver?: boolean) {
verifyWatchesOfProject(host, withTsserver ? expectedWatchedFiles.filter(f => f !== tests[1].path.toLowerCase()) : expectedWatchedFiles, expectedWatchedDirectoriesRecursive);
}
function verifyScenario(
edit: (host: WatchedSystem, solutionBuilder: SolutionBuilder) => void,
expectedFilesAfterEdit: ReadonlyArray<string>
) {
it("with tsc-watch", () => {
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
edit(host, solutionBuilder);
host.checkTimeoutQueueLengthAndRun(1);
checkOutputErrorsIncremental(host, emptyArray);
checkProgramActualFiles(watch().getProgram(), expectedFilesAfterEdit);
});
it("with tsserver", () => {
const { host, solutionBuilder, service } = createSolutionAndService();
edit(host, solutionBuilder);
host.checkTimeoutQueueLengthAndRun(2);
checkProjectActualFiles(service, tests[0].path, [tests[0].path, ...expectedFilesAfterEdit]);
});
}
describe("verifies dependencies and watches", () => {
it("with tsc-watch", () => {
const { host, watch } = createSolutionAndWatchMode();
verifyWatches(host);
verifyDependencies(watch, coreIndexDts, [coreIndexDts]);
verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]);
verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]);
verifyDependencies(watch, tests[1].path, expectedProgramFiles.filter(f => f !== libFile.path));
});
it("with tsserver", () => {
const { host } = createSolutionAndService();
verifyWatches(host, /*withTsserver*/ true);
});
});
describe("local edit in ts file, result in watch compilation because logic.d.ts is written", () => {
verifyScenario((host, solutionBuilder) => {
host.writeFile(logic[1].path, `${logic[1].content}
function foo() {
}`);
solutionBuilder.invalidateProject(`${project}/${SubProject.logic}`);
solutionBuilder.buildInvalidatedProject();
solutionBuilder.invalidateProject(`${project}/${SubProject.logic}`);
solutionBuilder.buildInvalidatedProject();
host.checkTimeoutQueueLengthAndRun(1); // not ideal, but currently because of d.ts but no new file is written
checkOutputErrorsIncremental(host, emptyArray);
checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]);
});
// not ideal, but currently because of d.ts but no new file is written
// There will be timeout queued even though file contents are same
}, expectedProgramFiles);
});
it("non local edit in ts file, rebuilds in watch compilation", () => {
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
host.writeFile(logic[1].path, `${logic[1].content}
describe("non local edit in ts file, rebuilds in watch compilation", () => {
verifyScenario((host, solutionBuilder) => {
host.writeFile(logic[1].path, `${logic[1].content}
export function gfoo() {
}`);
solutionBuilder.invalidateProject(logic[0].path);
solutionBuilder.buildInvalidatedProject();
solutionBuilder.invalidateProject(logic[0].path);
solutionBuilder.buildInvalidatedProject();
}, expectedProgramFiles);
});
host.checkTimeoutQueueLengthAndRun(1);
checkOutputErrorsIncremental(host, emptyArray);
checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]);
describe("change in project reference config file builds correctly", () => {
verifyScenario((host, solutionBuilder) => {
host.writeFile(logic[0].path, JSON.stringify({
compilerOptions: { composite: true, declaration: true, declarationDir: "decls" },
references: [{ path: "../core" }]
}));
solutionBuilder.invalidateProject(logic[0].path, ConfigFileProgramReloadLevel.Full);
solutionBuilder.buildInvalidatedProject();
}, [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]);
});
});
it("change in project reference config file builds correctly", () => {
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
host.writeFile(logic[0].path, JSON.stringify({
compilerOptions: { composite: true, declaration: true, declarationDir: "decls" },
references: [{ path: "../core" }]
}));
solutionBuilder.invalidateProject(logic[0].path, ConfigFileProgramReloadLevel.Full);
solutionBuilder.buildInvalidatedProject();
describe("on transitive references", () => {
const project = "transitiveReferences";
const aTsFile = getFileFromProject(project, "a.ts");
const bTsFile = getFileFromProject(project, "b.ts");
const cTsFile = getFileFromProject(project, "c.ts");
const aTsconfigFile = getFileFromProject(project, "tsconfig.a.json");
const bTsconfigFile = getFileFromProject(project, "tsconfig.b.json");
const cTsconfigFile = getFileFromProject(project, "tsconfig.c.json");
const refs = getFileFromProject(project, "refs/a.d.ts");
host.checkTimeoutQueueLengthAndRun(1);
checkOutputErrorsIncremental(host, emptyArray);
checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]);
function getRootFile(multiFolder: boolean, fileFromDisk: File, multiFolderPath: string): File {
return multiFolder ? {
path: getFilePathInProject(project, multiFolderPath),
content: fileFromDisk.content
// Replace the relative imports
.replace("./", "../")
} : fileFromDisk;
}
function dtsFile(extensionLessFile: string) {
return getFilePathInProject(project, `${extensionLessFile}.d.ts`);
}
function jsFile(extensionLessFile: string) {
return getFilePathInProject(project, `${extensionLessFile}.js`);
}
function verifyWatchState(
host: WatchedSystem,
watch: Watch,
expectedProgramFiles: ReadonlyArray<string>,
expectedWatchedFiles: ReadonlyArray<string>,
expectedWatchedDirectoriesRecursive: ReadonlyArray<string>,
dependencies: ReadonlyArray<[string, ReadonlyArray<string>]>,
expectedWatchedDirectories?: ReadonlyArray<string>) {
checkProgramActualFiles(watch().getProgram(), expectedProgramFiles);
verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories);
for (const [file, deps] of dependencies) {
verifyDependencies(watch, file, deps);
}
}
function getTsConfigFile(multiFolder: boolean, fileFromDisk: File, folder: string): File {
if (!multiFolder) return fileFromDisk;
return {
path: getFilePathInProject(project, `${folder}/tsconfig.json`),
content: fileFromDisk.content
// Replace files array
.replace(`${folder}.ts`, "index.ts")
// Replace path mappings
.replace("./*", "../*")
.replace("./refs", "../refs")
// Replace references
.replace("tsconfig.a.json", "../a")
.replace("tsconfig.b.json", "../b")
};
}
// function writeFile(file: File) {
// Harness.IO.writeFile(file.path.replace(projectsLocation, "c:/temp"), file.content);
// }
function verifyTransitiveReferences(multiFolder: boolean) {
const aTs = getRootFile(multiFolder, aTsFile, "a/index.ts");
const bTs = getRootFile(multiFolder, bTsFile, "b/index.ts");
const cTs = getRootFile(multiFolder, cTsFile, "c/index.ts");
const configToBuild = multiFolder ? "c/tsconfig.json" : "tsconfig.c.json";
const aTsconfig = getTsConfigFile(multiFolder, aTsconfigFile, "a");
const bTsconfig = getTsConfigFile(multiFolder, bTsconfigFile, "b");
const cTsconfig = getTsConfigFile(multiFolder, cTsconfigFile, "c");
// if (multiFolder) {
// writeFile(aTs);
// writeFile(bTs);
// writeFile(cTs);
// writeFile(aTsconfig);
// writeFile(bTsconfig);
// writeFile(cTsconfig);
// }
const allFiles = [libFile, aTs, bTs, cTs, aTsconfig, bTsconfig, cTsconfig, refs];
const aDts = dtsFile(multiFolder ? "a/index" : "a"), bDts = dtsFile(multiFolder ? "b/index" : "b");
const expectedFiles = [jsFile(multiFolder ? "a/index" : "a"), aDts, jsFile(multiFolder ? "b/index" : "b"), bDts, jsFile(multiFolder ? "c/index" : "c")];
const expectedProgramFiles = [cTs.path, libFile.path, aDts, refs.path, bDts];
const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase());
const expectedWatchedDirectories = multiFolder ? [
getProjectPath(project).toLowerCase() // watches for directories created for resolution of b
] : emptyArray;
const nrefsPath = multiFolder ? ["../nrefs/*"] : ["./nrefs/*"];
const expectedWatchedDirectoriesRecursive = [
...(multiFolder ? [
getFilePathInProject(project, "a"), // Failed to package json
getFilePathInProject(project, "b"), // Failed to package json
] : []),
getFilePathInProject(project, "refs"), // Failed lookup since refs/a.ts does not exist
...projectSystem.getTypeRootsFromLocation(multiFolder ? getFilePathInProject(project, "c") : getProjectPath(project))
].map(s => s.toLowerCase());
const defaultDependencies: ReadonlyArray<[string, ReadonlyArray<string>]> = [
[aDts, [aDts]],
[bDts, [bDts, aDts]],
[refs.path, [refs.path]],
[cTs.path, [cTs.path, refs.path, bDts]]
];
function createSolutionAndWatchMode() {
return createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), configToBuild, configToBuild, getOutputFileStamps);
}
function createSolutionAndService() {
return createSolutionAndServiceOfProject(allFiles, getProjectPath(project), configToBuild, cTs.path, getOutputFileStamps);
}
function getOutputFileStamps(host: WatchedSystem) {
return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp);
}
function verifyProgram(host: WatchedSystem, watch: Watch) {
verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies, expectedWatchedDirectories);
}
function verifyProject(host: WatchedSystem, service: projectSystem.TestProjectService, orphanInfos?: ReadonlyArray<string>) {
verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos);
}
function verifyServerState(
host: WatchedSystem,
service: projectSystem.TestProjectService,
expectedProgramFiles: ReadonlyArray<string>,
expectedWatchedFiles: ReadonlyArray<string>,
expectedWatchedDirectoriesRecursive: ReadonlyArray<string>,
orphanInfos?: ReadonlyArray<string>) {
checkProjectActualFiles(service, cTsconfig.path, expectedProgramFiles.concat(cTsconfig.path));
const watchedFiles = expectedWatchedFiles.filter(f => f !== cTs.path.toLowerCase());
if (orphanInfos) {
for (const orphan of orphanInfos) {
const info = service.getScriptInfoForPath(orphan as Path);
assert.isDefined(info);
assert.equal(info!.containingProjects.length, 0);
watchedFiles.push(orphan);
}
}
verifyWatchesOfProject(host, watchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories);
}
function verifyScenario(
edit: (host: WatchedSystem, solutionBuilder: SolutionBuilder) => void,
expectedEditErrors: ReadonlyArray<string>,
expectedProgramFiles: ReadonlyArray<string>,
expectedWatchedFiles: ReadonlyArray<string>,
expectedWatchedDirectoriesRecursive: ReadonlyArray<string>,
dependencies: ReadonlyArray<[string, ReadonlyArray<string>]>,
revert?: (host: WatchedSystem) => void,
orphanInfosAfterEdit?: ReadonlyArray<string>,
orphanInfosAfterRevert?: ReadonlyArray<string>) {
it("with tsc-watch", () => {
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
edit(host, solutionBuilder);
host.checkTimeoutQueueLengthAndRun(1);
checkOutputErrorsIncremental(host, expectedEditErrors);
verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, dependencies, expectedWatchedDirectories);
if (revert) {
revert(host);
host.checkTimeoutQueueLengthAndRun(1);
checkOutputErrorsIncremental(host, emptyArray);
verifyProgram(host, watch);
}
});
if (!multiFolder) return; // With side by side file open is in inferred project without any settings
it("with tsserver", () => {
const { host, solutionBuilder, service } = createSolutionAndService();
edit(host, solutionBuilder);
host.checkTimeoutQueueLengthAndRun(2);
verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfosAfterEdit);
if (revert) {
revert(host);
host.checkTimeoutQueueLengthAndRun(2);
verifyProject(host, service, orphanInfosAfterRevert);
}
});
}
describe("verifies dependencies and watches", () => {
// Initial build
it("with tsc-watch", () => {
const { host, watch } = createSolutionAndWatchMode();
verifyProgram(host, watch);
});
if (!multiFolder) return;
it("with tsserver", () => {
const { host, service } = createSolutionAndService();
verifyProject(host, service);
});
});
describe("non local edit updates the program and watch correctly", () => {
verifyScenario(
(host, solutionBuilder) => {
// edit
host.writeFile(bTs.path, `${bTs.content}
export function gfoo() {
}`);
solutionBuilder.invalidateProject(bTsconfig.path);
solutionBuilder.buildInvalidatedProject();
},
emptyArray,
expectedProgramFiles,
expectedWatchedFiles,
expectedWatchedDirectoriesRecursive,
defaultDependencies);
});
describe("edit on config file", () => {
const nrefReplacer = (f: string) => f.replace("refs", "nrefs");
const nrefs: File = {
path: getFilePathInProject(project, "nrefs/a.d.ts"),
content: refs.content
};
verifyScenario(
host => {
const cTsConfigJson = JSON.parse(cTsconfig.content);
host.ensureFileOrFolder(nrefs);
cTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath };
host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson));
},
emptyArray,
expectedProgramFiles.map(nrefReplacer),
expectedWatchedFiles.map(nrefReplacer),
expectedWatchedDirectoriesRecursive.map(nrefReplacer),
[
[aDts, [aDts]],
[bDts, [bDts, aDts]],
[nrefs.path, [nrefs.path]],
[cTs.path, [cTs.path, nrefs.path, bDts]]
],
// revert the update
host => host.writeFile(cTsconfig.path, cTsconfig.content),
// AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open
[refs.path.toLowerCase()],
// AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open
[nrefs.path.toLowerCase()]
);
});
describe("edit in referenced config file", () => {
const nrefs: File = {
path: getFilePathInProject(project, "nrefs/a.d.ts"),
content: "export declare class A {}"
};
const expectedProgramFiles = [cTs.path, bDts, nrefs.path, refs.path, libFile.path];
const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario
verifyScenario(
host => {
const bTsConfigJson = JSON.parse(bTsconfig.content);
host.ensureFileOrFolder(nrefs);
bTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath };
host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson));
},
emptyArray,
expectedProgramFiles,
expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()),
(multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive).concat(getFilePathInProject(project, "nrefs").toLowerCase()),
[
[nrefs.path, [nrefs.path]],
[bDts, [bDts, nrefs.path]],
[refs.path, [refs.path]],
[cTs.path, [cTs.path, refs.path, bDts]],
],
// revert the update
host => host.writeFile(bTsconfig.path, bTsconfig.content),
// AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open
[aDts.toLowerCase()],
// AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open
[nrefs.path.toLowerCase()]
);
});
describe("deleting referenced config file", () => {
const expectedProgramFiles = [cTs.path, bTs.path, refs.path, libFile.path];
const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario
// Resolutions should change now
// Should map to b.ts instead with options from our own config
verifyScenario(
host => host.deleteFile(bTsconfig.path),
[
`${multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"}(9,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "b" : "tsconfig.b.json"}' not found.\n`
],
expectedProgramFiles,
expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path).map(s => s.toLowerCase()),
multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive,
[
[bTs.path, [bTs.path, refs.path]],
[refs.path, [refs.path]],
[cTs.path, [cTs.path, refs.path, bTs.path]],
],
// revert the update
host => host.writeFile(bTsconfig.path, bTsconfig.content),
// AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open
[bDts.toLowerCase(), aDts.toLowerCase(), aTsconfig.path.toLowerCase()],
// AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open
[bTs.path.toLowerCase()]
);
});
describe("deleting transitively referenced config file", () => {
verifyScenario(
host => host.deleteFile(aTsconfig.path),
[
`${multiFolder ? "b/tsconfig.json" : "tsconfig.b.json"}(10,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "a" : "tsconfig.a.json"}' not found.\n`
],
expectedProgramFiles.map(s => s.replace(aDts, aTs.path)),
expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())),
expectedWatchedDirectoriesRecursive,
[
[aTs.path, [aTs.path]],
[bDts, [bDts, aTs.path]],
[refs.path, [refs.path]],
[cTs.path, [cTs.path, refs.path, bDts]],
],
// revert the update
host => host.writeFile(aTsconfig.path, aTsconfig.content),
// AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open
[aDts.toLowerCase()],
// AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open
[aTs.path.toLowerCase()]
);
});
}
describe("when config files are side by side", () => {
verifyTransitiveReferences(/*multiFolder*/ false);
it("when referenced project uses different module resolution", () => {
const bTs: File = {
path: bTsFile.path,
content: `import {A} from "a";export const b = new A();`
};
const bTsconfig: File = {
path: bTsconfigFile.path,
content: JSON.stringify({
compilerOptions: { composite: true, moduleResolution: "classic" },
files: ["b.ts"],
references: [{ path: "tsconfig.a.json" }]
})
};
const allFiles = [libFile, aTsFile, bTs, cTsFile, aTsconfigFile, bTsconfig, cTsconfigFile, refs];
const aDts = dtsFile("a"), bDts = dtsFile("b");
const expectedFiles = [jsFile("a"), aDts, jsFile("b"), bDts, jsFile("c")];
const expectedProgramFiles = [cTsFile.path, libFile.path, aDts, refs.path, bDts];
const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfigFile.path, bTsconfigFile.path, aTsconfigFile.path).map(s => s.toLowerCase());
const expectedWatchedDirectoriesRecursive = [
getFilePathInProject(project, "refs"), // Failed lookup since refs/a.ts does not exist
...projectSystem.getTypeRootsFromLocation(getProjectPath(project))
].map(s => s.toLowerCase());
const defaultDependencies: ReadonlyArray<[string, ReadonlyArray<string>]> = [
[aDts, [aDts]],
[bDts, [bDts, aDts]],
[refs.path, [refs.path]],
[cTsFile.path, [cTsFile.path, refs.path, bDts]]
];
function getOutputFileStamps(host: WatchedSystem) {
return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp);
}
const { host, watch } = createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), "tsconfig.c.json", "tsconfig.c.json", getOutputFileStamps);
verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies);
});
});
describe("when config files are in side by side folders", () => {
verifyTransitiveReferences(/*multiFolder*/ true);
});
});
});
});
+225 -7
View File
@@ -12,11 +12,11 @@ namespace ts.tscWatch {
export import checkOutputDoesNotContain = TestFSWithWatch.checkOutputDoesNotContain;
export import Tsc_WatchDirectory = TestFSWithWatch.Tsc_WatchDirectory;
export function checkProgramActualFiles(program: Program, expectedFiles: string[]) {
export function checkProgramActualFiles(program: Program, expectedFiles: ReadonlyArray<string>) {
checkArray(`Program actual files`, program.getSourceFiles().map(file => file.fileName), expectedFiles);
}
export function checkProgramRootFiles(program: Program, expectedFiles: string[]) {
export function checkProgramRootFiles(program: Program, expectedFiles: ReadonlyArray<string>) {
checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles);
}
@@ -34,8 +34,10 @@ namespace ts.tscWatch {
return () => watch.getCurrentProgram().getProgram();
}
function createWatchOfFilesAndCompilerOptions(rootFiles: string[], host: WatchedSystem, options: CompilerOptions = {}) {
const watch = createWatchProgram(createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, host));
function createWatchOfFilesAndCompilerOptions(rootFiles: string[], host: WatchedSystem, options: CompilerOptions = {}, maxNumberOfFilesToIterateForInvalidation?: number) {
const compilerHost = createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, host);
compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation;
const watch = createWatchProgram(compilerHost);
return () => watch.getCurrentProgram().getProgram();
}
@@ -1072,7 +1074,10 @@ namespace ts.tscWatch {
const host = createWatchedSystem([file1, configFile, libFile]);
const watch = createWatchOfConfigFile(configFile.path, host);
checkProgramActualFiles(watch(), [libFile.path]);
checkProgramActualFiles(watch(), emptyArray);
checkOutputErrorsInitial(host, [
"error TS18003: No inputs were found in config file '/a/b/tsconfig.json'. Specified 'include' paths were '[\"app/*\",\"test/**/*\",\"something\"]' and 'exclude' paths were '[]'.\n"
]);
});
it("non-existing directories listed in config file input array should be able to handle @types if input file list is empty", () => {
@@ -1098,7 +1103,10 @@ namespace ts.tscWatch {
const host = createWatchedSystem([f, config, t1, t2], { currentDirectory: getDirectoryPath(f.path) });
const watch = createWatchOfConfigFile(config.path, host);
checkProgramActualFiles(watch(), [t1.path, t2.path]);
checkProgramActualFiles(watch(), emptyArray);
checkOutputErrorsInitial(host, [
"tsconfig.json(1,24): error TS18002: The 'files' list in config file '/a/tsconfig.json' is empty.\n"
]);
});
it("should support files without extensions", () => {
@@ -1290,7 +1298,7 @@ export default test;`;
]);
changeParameterType("y", "string", [
getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.indexOf("5"), 1, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, "5", "string"),
getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("y /"), 1, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type)
getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("y /"), 1, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type)
]);
function changeParameterType(parameterName: string, toType: string, expectedErrors: ReadonlyArray<Diagnostic>) {
@@ -1350,6 +1358,49 @@ export class B
assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs);
});
it("updates errors when deep import through declaration file changes", () => {
const currentDirectory = "/user/username/projects/myproject";
const aFile: File = {
path: `${currentDirectory}/a.ts`,
content: `import {B} from './b';
declare var console: any;
let b = new B();
console.log(b.c.d);`
};
const bFile: File = {
path: `${currentDirectory}/b.d.ts`,
content: `import {C} from './c';
export class B
{
c: C;
}`
};
const cFile: File = {
path: `${currentDirectory}/c.d.ts`,
content: `export class C
{
d: number;
}`
};
const config: File = {
path: `${currentDirectory}/tsconfig.json`,
content: `{}`
};
const files = [aFile, bFile, cFile, config, libFile];
const host = createWatchedSystem(files, { currentDirectory });
const watch = createWatchOfConfigFile("tsconfig.json", host);
checkProgramActualFiles(watch(), [aFile.path, bFile.path, cFile.path, libFile.path]);
checkOutputErrorsInitial(host, emptyArray);
const modifiedTimeOfAJs = host.getModifiedTime(`${currentDirectory}/a.js`);
host.writeFile(cFile.path, cFile.content.replace("d", "d2"));
host.runQueuedTimeoutCallbacks();
checkOutputErrorsIncremental(host, [
getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.lastIndexOf("d"), 1, Diagnostics.Property_0_does_not_exist_on_type_1, "d", "C")
]);
// File a need not be rewritten
assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs);
});
it("updates errors when strictNullChecks changes", () => {
const currentDirectory = "/user/username/projects/myproject";
const aFile: File = {
@@ -1386,6 +1437,133 @@ foo().hello`
// File a need not be rewritten
assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs);
});
it("updates errors when ambient modules of program changes", () => {
const currentDirectory = "/user/username/projects/myproject";
const aFile: File = {
path: `${currentDirectory}/a.ts`,
content: `declare module 'a' {
type foo = number;
}`
};
const config: File = {
path: `${currentDirectory}/tsconfig.json`,
content: "{}"
};
const files = [aFile, config, libFile];
const host = createWatchedSystem(files, { currentDirectory });
const watch = createWatchOfConfigFile("tsconfig.json", host);
checkProgramActualFiles(watch(), [aFile.path, libFile.path]);
checkOutputErrorsInitial(host, emptyArray);
// Create bts with same file contents
const bTsPath = `${currentDirectory}/b.ts`;
host.writeFile(bTsPath, aFile.content);
host.runQueuedTimeoutCallbacks();
checkProgramActualFiles(watch(), [aFile.path, "b.ts", libFile.path]);
checkOutputErrorsIncremental(host, [
"a.ts(2,8): error TS2300: Duplicate identifier 'foo'.\n",
"b.ts(2,8): error TS2300: Duplicate identifier 'foo'.\n"
]);
// Delete bTs
host.deleteFile(bTsPath);
host.runQueuedTimeoutCallbacks();
checkProgramActualFiles(watch(), [aFile.path, libFile.path]);
checkOutputErrorsIncremental(host, emptyArray);
});
describe("updates errors when file transitively exported file changes", () => {
const projectLocation = "/user/username/projects/myproject";
const config: File = {
path: `${projectLocation}/tsconfig.json`,
content: JSON.stringify({
files: ["app.ts"],
compilerOptions: { baseUrl: "." }
})
};
const app: File = {
path: `${projectLocation}/app.ts`,
content: `import { Data } from "lib2/public";
export class App {
public constructor() {
new Data().test();
}
}`
};
const lib2Public: File = {
path: `${projectLocation}/lib2/public.ts`,
content: `export * from "./data";`
};
const lib2Data: File = {
path: `${projectLocation}/lib2/data.ts`,
content: `import { ITest } from "lib1/public";
export class Data {
public test() {
const result: ITest = {
title: "title"
}
return result;
}
}`
};
const lib1Public: File = {
path: `${projectLocation}/lib1/public.ts`,
content: `export * from "./tools/public";`
};
const lib1ToolsPublic: File = {
path: `${projectLocation}/lib1/tools/public.ts`,
content: `export * from "./tools.interface";`
};
const lib1ToolsInterface: File = {
path: `${projectLocation}/lib1/tools/tools.interface.ts`,
content: `export interface ITest {
title: string;
}`
};
function verifyTransitiveExports(filesWithoutConfig: ReadonlyArray<File>) {
const files = [config, ...filesWithoutConfig];
const host = createWatchedSystem(files, { currentDirectory: projectLocation });
const watch = createWatchOfConfigFile(config.path, host);
checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path));
checkOutputErrorsInitial(host, emptyArray);
host.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title", "title2"));
host.checkTimeoutQueueLengthAndRun(1);
checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path));
checkOutputErrorsIncremental(host, [
"lib2/data.ts(5,13): error TS2322: Type '{ title: string; }' is not assignable to type 'ITest'.\n Object literal may only specify known properties, but 'title' does not exist in type 'ITest'. Did you mean to write 'title2'?\n"
]);
}
it("when there are no circular import and exports", () => {
verifyTransitiveExports([libFile, app, lib2Public, lib2Data, lib1Public, lib1ToolsPublic, lib1ToolsInterface]);
});
it("when there are circular import and exports", () => {
const lib2Data: File = {
path: `${projectLocation}/lib2/data.ts`,
content: `import { ITest } from "lib1/public"; import { Data2 } from "./data2";
export class Data {
public dat?: Data2; public test() {
const result: ITest = {
title: "title"
}
return result;
}
}`
};
const lib2Data2: File = {
path: `${projectLocation}/lib2/data2.ts`,
content: `import { Data } from "./data";
export class Data2 {
public dat?: Data;
}`
};
verifyTransitiveExports([libFile, app, lib2Public, lib2Data, lib2Data2, lib1Public, lib1ToolsPublic, lib1ToolsInterface]);
});
});
});
describe("tsc-watch emit with outFile or out setting", () => {
@@ -2389,6 +2567,46 @@ declare module "fs" {
checkProgramActualFiles(watch(), [file.path, libFile.path, `${currentDirectory}/node_modules/@types/qqq/index.d.ts`]);
checkOutputErrorsIncremental(host, emptyArray);
});
describe("ignores files/folder changes in node_modules that start with '.'", () => {
const projectPath = "/user/username/projects/project";
const npmCacheFile: File = {
path: `${projectPath}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`,
content: JSON.stringify({ something: 10 })
};
const file1: File = {
path: `${projectPath}/test.ts`,
content: `import { x } from "somemodule";`
};
const file2: File = {
path: `${projectPath}/node_modules/somemodule/index.d.ts`,
content: `export const x = 10;`
};
const files = [libFile, file1, file2];
const expectedFiles = files.map(f => f.path);
it("when watching node_modules in inferred project for failed lookup", () => {
const host = createWatchedSystem(files);
const watch = createWatchOfFilesAndCompilerOptions([file1.path], host, {}, /*maxNumberOfFilesToIterateForInvalidation*/ 1);
checkProgramActualFiles(watch(), expectedFiles);
host.checkTimeoutQueueLength(0);
host.ensureFileOrFolder(npmCacheFile);
host.checkTimeoutQueueLength(0);
});
it("when watching node_modules as part of wild card directories in config project", () => {
const config: File = {
path: `${projectPath}/tsconfig.json`,
content: "{}"
};
const host = createWatchedSystem(files.concat(config));
const watch = createWatchOfConfigFile(config.path, host);
checkProgramActualFiles(watch(), expectedFiles);
host.checkTimeoutQueueLength(0);
host.ensureFileOrFolder(npmCacheFile);
host.checkTimeoutQueueLength(0);
});
});
});
describe("tsc-watch with when module emit is specified as node", () => {
+1 -1
View File
@@ -141,7 +141,7 @@ namespace ts {
it("returns object with error when json is invalid", () => {
const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", "invalid");
assert.deepEqual(parsed.config, { invalid: undefined });
assert.deepEqual(parsed.config, {});
const expected = createCompilerDiagnostic(Diagnostics._0_expected, "{");
const error = parsed.error!;
assert.equal(error.messageText, expected.messageText);
File diff suppressed because it is too large. Load diff
+47 -3
View File
@@ -310,7 +310,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>) {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
@@ -409,7 +409,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>) {
super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
@@ -451,7 +451,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>) {
super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
@@ -986,6 +986,50 @@ namespace ts.projectSystem {
checkProjectActualFiles(service.inferredProjects[0], [file.path, node.path, commander.path]);
});
it("should redo resolution that resolved to '.js' file after typings are installed", () => {
const file: TestFSWithWatch.File = {
path: "/a/b/app.js",
content: `
import * as commander from "commander";`
};
const cachePath = "/a/cache";
const commanderJS: TestFSWithWatch.File = {
path: "/node_modules/commander/index.js",
content: "module.exports = 0",
};
const typeNames: ReadonlyArray<string> = ["commander"];
const typePath = (name: string): string => `${cachePath}/node_modules/@types/${name}/index.d.ts`;
const host = createServerHost([file, commanderJS]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry(...typeNames) });
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
const installedTypings = typeNames.map(name => `@types/${name}`);
const typingFiles = typeNames.map((name): TestFSWithWatch.File => ({ path: typePath(name), content: "" }));
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
const service = createProjectService(host, { typingsInstaller: installer });
service.openClientFile(file.path);
checkWatchedFiles(host, [...flatMap(["/a/b", "/a", ""], x => [x + "/tsconfig.json", x + "/jsconfig.json"]), "/a/lib/lib.d.ts"]);
checkWatchedDirectories(host, [], /*recursive*/ false);
// Does not include cachePath because that is handled by typingsInstaller
checkWatchedDirectories(host, ["/node_modules", "/a/b/node_modules", "/a/b/node_modules/@types", "/a/b/bower_components"], /*recursive*/ true);
service.checkNumberOfProjects({ inferredProjects: 1 });
checkProjectActualFiles(service.inferredProjects[0], [file.path, commanderJS.path]);
installer.installAll(/*expectedCount*/1);
for (const name of typeNames) {
assert.isTrue(host.fileExists(typePath(name)), `typings for '${name}' should be created`);
}
host.checkTimeoutQueueLengthAndRun(2);
checkProjectActualFiles(service.inferredProjects[0], [file.path, ...typeNames.map(typePath)]);
});
it("should pick typing names from non-relative unresolved imports", () => {
const f1 = {
path: "/a/b/app.js",